inboxer 0.4.9 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -77,7 +77,11 @@ export declare class Mail {
77
77
  private readonly domains;
78
78
  private readonly timers;
79
79
  private readonly files;
80
+ /** Fires "change" after every write, so open pages can refresh. */
81
+ readonly changes: EventTarget;
80
82
  constructor(store: Store, provider: MailProvider, cfg: InboxerConfig);
83
+ /** Runs `fn` in the store's write queue, then announces the change. */
84
+ private write;
81
85
  listMailboxes(scope: Scope): {
82
86
  id: string;
83
87
  address: string;
@@ -89,6 +93,8 @@ export declare class Mail {
89
93
  private catchAllAddress;
90
94
  /** The account a thread belongs to: its mailbox or, in the catch-all, the address it was written to. */
91
95
  accountOf(thread: Thread): string;
96
+ /** The address an account receives mail at: a configured mailbox's address, or the catch-all address itself. */
97
+ addressOf(account: string): string;
92
98
  /** Mailboxes in scope, with the catch-all split into the addresses it has received mail for. */
93
99
  listAccounts(scope: Scope): Promise<string[]>;
94
100
  requireMessage(id: string, scope: Scope): Promise<Message>;
package/dist/core/mail.js CHANGED
@@ -31,6 +31,8 @@ export class Mail {
31
31
  domains;
32
32
  timers = new Map();
33
33
  files;
34
+ /** Fires "change" after every write, so open pages can refresh. */
35
+ changes = new EventTarget();
34
36
  constructor(store, provider, cfg) {
35
37
  this.store = store;
36
38
  this.provider = provider;
@@ -39,6 +41,12 @@ export class Mail {
39
41
  this.domains = new Set(Object.values(cfg.mailboxes).map(m => domainOf(m.address)));
40
42
  this.files = new AttachmentFiles(cfg.dataDir);
41
43
  }
44
+ /** Runs `fn` in the store's write queue, then announces the change. */
45
+ async write(fn) {
46
+ const result = await this.store.serialize(fn);
47
+ this.changes.dispatchEvent(new Event("change"));
48
+ return result;
49
+ }
42
50
  listMailboxes(scope) {
43
51
  return [
44
52
  ...Object.entries(this.cfg.mailboxes).map(([id, m]) => ({ id, address: m.address, name: m.name })),
@@ -58,6 +66,11 @@ export class Mail {
58
66
  accountOf(thread) {
59
67
  return thread.mailbox === CATCHALL ? this.catchAllAddress(thread.participants) ?? CATCHALL : thread.mailbox;
60
68
  }
69
+ /** The address an account receives mail at: a configured mailbox's address, or the catch-all address itself. */
70
+ addressOf(account) {
71
+ const mailbox = this.cfg.mailboxes[account];
72
+ return mailbox ? bareAddress(mailbox.address) : account;
73
+ }
61
74
  /** Mailboxes in scope, with the catch-all split into the addresses it has received mail for. */
62
75
  async listAccounts(scope) {
63
76
  const mailboxes = this.listMailboxes(scope).map(m => m.id).filter(id => id !== CATCHALL);
@@ -124,7 +137,7 @@ export class Mail {
124
137
  return id;
125
138
  }
126
139
  storeInbound(providerId, inbound) {
127
- return this.store.serialize(async () => {
140
+ return this.write(async () => {
128
141
  const existing = await this.store.lookupProviderId(this.provider.name, providerId);
129
142
  if (existing)
130
143
  return existing;
@@ -187,7 +200,7 @@ export class Mail {
187
200
  }
188
201
  /** Status updates never move backwards: a late `sent` does not overwrite `delivered`. */
189
202
  applyStatus(providerId, status, messageId) {
190
- return this.store.serialize(async () => {
203
+ return this.write(async () => {
191
204
  const id = await this.store.lookupProviderId(this.provider.name, providerId);
192
205
  if (!id)
193
206
  return;
@@ -284,7 +297,7 @@ export class Mail {
284
297
  if (!bare.includes("@"))
285
298
  throw new InvalidRequestError(`"${address}" is not an email address`);
286
299
  await this.requireContactAccess(bare, actor.scope);
287
- return this.store.serialize(async () => {
300
+ return this.write(async () => {
288
301
  const contact = { address: bare, ...this.merge(await this.store.getContact(bare), patch, actor) };
289
302
  await this.store.putContact(contact);
290
303
  await this.store.audit("contact.update", actor, bare, { ...patch });
@@ -292,7 +305,7 @@ export class Mail {
292
305
  });
293
306
  }
294
307
  setThreadContext(threadId, patch, actor) {
295
- return this.store.serialize(async () => {
308
+ return this.write(async () => {
296
309
  await this.requireThread(threadId, actor.scope);
297
310
  const context = this.merge(await this.store.getThreadContext(threadId), patch, actor);
298
311
  await this.store.putThreadContext(threadId, context);
@@ -325,7 +338,7 @@ export class Mail {
325
338
  return [...new Set(out)];
326
339
  }
327
340
  updateMessages(ids, actor, action, change) {
328
- return this.store.serialize(async () => {
341
+ return this.write(async () => {
329
342
  const messageIds = await this.resolveMessageIds(ids, actor.scope);
330
343
  const threads = new Set();
331
344
  for (const id of messageIds) {
@@ -358,7 +371,7 @@ export class Mail {
358
371
  }
359
372
  // Drafts and sending
360
373
  createDraft(input, actor) {
361
- return this.store.serialize(() => this.createDraftUnlocked(input, actor));
374
+ return this.write(() => this.createDraftUnlocked(input, actor));
362
375
  }
363
376
  /** Who a reply to `replyToId` goes to and its subject, without creating anything. */
364
377
  async replyTo(replyToId, replyAll, scope) {
@@ -460,7 +473,7 @@ export class Mail {
460
473
  * human edited unless it passes `force`. A UI edit regenerates the HTML from the text at send time.
461
474
  */
462
475
  updateDraft(id, version, patch, actor, force = false) {
463
- return this.store.serialize(async () => {
476
+ return this.write(async () => {
464
477
  const draft = await this.requireDraft(id, actor.scope);
465
478
  if (draft.version !== version)
466
479
  throw new ConflictError(draft);
@@ -484,7 +497,7 @@ export class Mail {
484
497
  });
485
498
  }
486
499
  discardDraft(id, actor) {
487
- return this.store.serialize(() => this.discardDraftUnlocked(id, actor));
500
+ return this.write(() => this.discardDraftUnlocked(id, actor));
488
501
  }
489
502
  async discardDraftUnlocked(id, actor) {
490
503
  const draft = await this.requireDraft(id, actor.scope);
@@ -497,7 +510,7 @@ export class Mail {
497
510
  }
498
511
  /** Attaching does not change `version`: it never conflicts with text edits in flight. */
499
512
  attach(id, file, actor) {
500
- return this.store.serialize(async () => {
513
+ return this.write(async () => {
501
514
  const draft = await this.requireDraft(id, actor.scope);
502
515
  if (draft.pending)
503
516
  throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
@@ -517,7 +530,7 @@ export class Mail {
517
530
  });
518
531
  }
519
532
  detach(id, attachmentId, actor) {
520
- return this.store.serialize(async () => {
533
+ return this.write(async () => {
521
534
  const draft = await this.requireDraft(id, actor.scope);
522
535
  if (draft.pending)
523
536
  throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
@@ -533,7 +546,7 @@ export class Mail {
533
546
  // Undo window: a human's send or discard waits `ui.undoSec` and survives a restart.
534
547
  /** Starts the undo window for a send or discard. Calling it again keeps the first one. */
535
548
  schedule(id, action, actor) {
536
- return this.store.serialize(async () => {
549
+ return this.write(async () => {
537
550
  const draft = await this.requireDraft(id, actor.scope);
538
551
  if (!draft.pending) {
539
552
  draft.pending = { action, at: new Date(Date.now() + this.cfg.ui.undoSec * 1000).toISOString(), by: actor.name };
@@ -545,7 +558,7 @@ export class Mail {
545
558
  });
546
559
  }
547
560
  undo(id, actor) {
548
- return this.store.serialize(async () => {
561
+ return this.write(async () => {
549
562
  const draft = await this.requireDraft(id, actor.scope);
550
563
  clearTimeout(this.timers.get(id));
551
564
  this.timers.delete(id);
@@ -581,7 +594,7 @@ export class Mail {
581
594
  /** A failed send leaves a plain pending draft, so the reviewer sees it was not sent. */
582
595
  runPending(id) {
583
596
  this.timers.delete(id);
584
- return this.store.serialize(async () => {
597
+ return this.write(async () => {
585
598
  const draft = await this.store.getMessage(id);
586
599
  if (!draft || draft.status !== "draft" || !draft.pending)
587
600
  return;
@@ -596,7 +609,7 @@ export class Mail {
596
609
  });
597
610
  }
598
611
  sendDraft(id, actor) {
599
- return this.store.serialize(() => this.sendDraftUnlocked(id, actor));
612
+ return this.write(() => this.sendDraftUnlocked(id, actor));
600
613
  }
601
614
  /**
602
615
  * The draft id is the idempotency key and the Message-ID is stored before the provider call,
@@ -646,7 +659,7 @@ export class Mail {
646
659
  }
647
660
  /** Direct send. If the provider fails, the message stays as a pending draft. */
648
661
  send(input, actor) {
649
- return this.store.serialize(async () => {
662
+ return this.write(async () => {
650
663
  const draft = await this.createDraftUnlocked(input, actor);
651
664
  return this.sendDraftUnlocked(draft.id, actor);
652
665
  });
package/dist/ui/routes.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
2
+ import { streamSSE } from "hono/streaming";
2
3
  import { domainOf, splitAddresses } from "../core/address.js";
3
4
  import { ConflictError, InvalidRequestError, toView } from "../core/mail.js";
4
5
  import { CATCHALL } from "../types.js";
@@ -23,6 +24,7 @@ function uiActor(session) {
23
24
  export function registerUi(app, mail, access, cfg) {
24
25
  const secret = cfg.ui.cookieSecret;
25
26
  const cookieOptions = { httpOnly: true, secure: true, sameSite: "Lax", path: "/", maxAge: COOKIE_MAX_AGE };
27
+ const hue = V.accentHue([...new Set(Object.values(cfg.mailboxes).map(m => domainOf(m.address)))]);
26
28
  const own = (address) => mail.isOwn(address);
27
29
  /** Recipients that are our own addresses are implied by the mailbox badge. */
28
30
  const shown = (m) => ({
@@ -38,7 +40,7 @@ export function registerUi(app, mail, access, cfg) {
38
40
  const shell = session
39
41
  ? { draftCount: (await mail.listDrafts(undefined, session.scope)).length, senders: senders(session) }
40
42
  : {};
41
- return c.html(V.layout(title, body, { theme: theme(c), page: current, signedIn: !!session, fullScreen, ...shell }), status);
43
+ return c.html(V.layout(title, body, { theme: theme(c), hue, page: current, signedIn: !!session, fullScreen, ...shell }), status);
42
44
  };
43
45
  // Sign-in: GET only shows a button, so link previews and scanners do not burn the link.
44
46
  // A used or expired link on a browser that is already signed in just opens the app.
@@ -70,7 +72,7 @@ export function registerUi(app, mail, access, cfg) {
70
72
  const path = back && new URL(back).origin === new URL(c.req.url).origin ? new URL(back).pathname + new URL(back).search : "/";
71
73
  return c.redirect(path, 303);
72
74
  });
73
- const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/compose", "/devices", "/devices/*", "/settings", "/logout"];
75
+ const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/compose", "/devices", "/devices/*", "/settings", "/logout", "/events"];
74
76
  for (const path of ui) {
75
77
  app.use(path, async (c, next) => {
76
78
  const value = await getSignedCookie(c, secret, SESSION_COOKIE);
@@ -196,7 +198,7 @@ export function registerUi(app, mail, access, cfg) {
196
198
  const filter = inboxFilter(c);
197
199
  const threads = await mail.listThreads({ mailbox: filter.mailbox || undefined, status: filter.status, limit: 200 }, session.scope);
198
200
  const accounts = await mail.listAccounts(session.scope);
199
- return V.threadList(threads, { accounts, accountOf: t => mail.accountOf(t), domains: domainsOf(session), filter, own, current });
201
+ return V.threadList(threads, { accounts, accountOf: t => mail.accountOf(t), addressOf: a => mail.addressOf(a), domains: domainsOf(session), filter, own, current });
200
202
  };
201
203
  app.get("/inbox", async (c) => page(c, S.navInbox, V.inboxPage(await threadList(c, null), null), "inbox"));
202
204
  /** A thread with its drafts in place; opening it marks it read. */
@@ -327,8 +329,15 @@ export function registerUi(app, mail, access, cfg) {
327
329
  });
328
330
  app.get("/devices", async (c) => {
329
331
  const session = c.get("session");
330
- return page(c, S.navDevices, V.devicesPage(await access.listSessions(session.scope), session.id), "devices");
332
+ return page(c, S.navDevices, V.devicesPage(await access.listSessions(session.scope), session.id, a => mail.addressOf(a)), "devices");
331
333
  });
334
+ // Every write pings open pages, which refetch their live regions; the stream carries no mail data.
335
+ app.get("/events", c => streamSSE(c, async (stream) => {
336
+ const ping = () => void stream.writeSSE({ event: "change", data: "1" });
337
+ mail.changes.addEventListener("change", ping);
338
+ await new Promise(resolve => stream.onAbort(resolve));
339
+ mail.changes.removeEventListener("change", ping);
340
+ }));
332
341
  app.get("/settings", async (c) => page(c, S.navSettings, V.settingsPage(theme(c)), "settings"));
333
342
  app.post("/devices/:id/revoke", async (c) => {
334
343
  await access.revokeSession(c.req.param("id"), uiActor(c.get("session")));
@@ -338,6 +347,6 @@ export function registerUi(app, mail, access, cfg) {
338
347
  const session = c.get("session");
339
348
  await access.revokeSession(session.id, uiActor(session), "session.logout");
340
349
  deleteCookie(c, SESSION_COOKIE, { path: "/", secure: true });
341
- return c.html(V.layout(S.signedOut, V.message([S.signedOut]), { theme: theme(c), page: null, signedIn: false }));
350
+ return c.html(V.layout(S.signedOut, V.message([S.signedOut]), { theme: theme(c), hue, page: null, signedIn: false }));
342
351
  });
343
352
  }
@@ -33,11 +33,72 @@ document.addEventListener("keydown", event => {
33
33
  if (event.key === "Escape") document.body.classList.remove("context-open");
34
34
  });
35
35
 
36
- // A thread opens at its latest message.
37
- document.addEventListener("DOMContentLoaded", () => {
36
+ // Links and forms load the next page with htmx and swap only the body, so scripts and styles stay loaded.
37
+ // The body's classes come from the new page, and an error page shows instead of nothing.
38
+ // Back and forward reload the page (see htmx-config), so a page is never restored with stale mail.
39
+ document.addEventListener("htmx:beforeSwap", event => {
40
+ if (!event.detail.boosted) return;
41
+ if (event.detail.xhr.status >= 400) {
42
+ event.detail.shouldSwap = true;
43
+ event.detail.isError = false;
44
+ }
45
+ document.body.className = /<body[^>]*class="([^"]*)"/.exec(event.detail.serverResponse)?.[1] ?? "";
46
+ });
47
+
48
+ document.addEventListener("htmx:afterSwap", event => {
49
+ if (event.detail.boosted) pageShown();
50
+ });
51
+
52
+ document.addEventListener("DOMContentLoaded", pageShown);
53
+
54
+ // A thread opens at its latest message; a signed-in page listens for changes.
55
+ function pageShown() {
38
56
  const messages = document.querySelector("[data-scroll-end]");
39
57
  if (messages) messages.scrollTop = messages.scrollHeight;
40
- });
58
+ listen();
59
+ }
60
+
61
+ // The server reports every change to the mail; the page then refetches itself once and swaps in its
62
+ // [data-live] regions by id. A burst of changes waits for a short quiet spell.
63
+ const REFRESH_DELAY_MS = 300;
64
+ let source = null;
65
+ let timer = null;
66
+
67
+ function listen() {
68
+ const signedIn = document.body.classList.contains("app");
69
+ if (signedIn && !source) {
70
+ source = new EventSource("/events");
71
+ source.addEventListener("change", refreshSoon);
72
+ // After a reconnect, changes made while it was down are caught up.
73
+ let opened = false;
74
+ source.addEventListener("open", () => opened ? refreshSoon() : opened = true);
75
+ } else if (!signedIn && source) {
76
+ source.close();
77
+ source = null;
78
+ }
79
+ }
80
+
81
+ function refreshSoon() {
82
+ clearTimeout(timer);
83
+ timer = setTimeout(refresh, REFRESH_DELAY_MS);
84
+ }
85
+
86
+ async function refresh() {
87
+ if (!document.querySelector("[data-live]")) return;
88
+ const url = location.href;
89
+ const res = await fetch(url);
90
+ if (!res.ok || location.href !== url) return;
91
+ const next = new DOMParser().parseFromString(await res.text(), "text/html");
92
+ for (const region of document.querySelectorAll("[data-live]")) {
93
+ const fresh = next.getElementById(region.id);
94
+ if (!fresh || region.contains(document.activeElement?.closest("input, select, textarea"))) continue;
95
+ const atEnd = region.scrollHeight - region.scrollTop - region.clientHeight < 2;
96
+ const scrollTop = region.scrollTop;
97
+ region.replaceWith(fresh);
98
+ fresh.scrollTop = fresh.hasAttribute("data-scroll-end") && atEnd ? fresh.scrollHeight : scrollTop;
99
+ htmx.process(fresh);
100
+ }
101
+ }
41
102
 
42
103
  // Files dropped on a [data-drop] zone go to its file input, which uploads them through htmx.
43
104
  const zoneOf = event => event.target instanceof Element ? event.target.closest("[data-drop]") : null;
@@ -7,10 +7,11 @@
7
7
  --soft: light-dark(#f1f1ef, #1f1f1e);
8
8
  --chip: light-dark(#e9e9e6, #333331);
9
9
  --surface: light-dark(#ffffff, #2e2e2c);
10
- --mine: light-dark(#ffe6d6, #4a2e20);
11
- --mine-line: light-dark(#ffd2b8, #5e3a28);
12
- --accent: light-dark(#ff4d00, #ff7a3d);
13
- --accent-text: light-dark(#c43d00, #ff8f5c);
10
+ /* --hue is set per instance on <html>, from its mail domains. */
11
+ --mine: light-dark(oklch(0.95 0.03 var(--hue)), oklch(0.33 0.045 var(--hue)));
12
+ --mine-line: light-dark(oklch(0.89 0.055 var(--hue)), oklch(0.4 0.06 var(--hue)));
13
+ --accent: light-dark(oklch(0.75 0.13 var(--hue)), oklch(0.78 0.11 var(--hue)));
14
+ --accent-text: light-dark(oklch(0.5 0.13 var(--hue)), oklch(0.83 0.09 var(--hue)));
14
15
  --focus: light-dark(#0a0a0a, #a3a39e);
15
16
  --primary-bg: light-dark(#0a0a0a, #ececea);
16
17
  --primary-fg: light-dark(#fbfbfa, #1f1f1e);
@@ -31,7 +32,7 @@
31
32
  body { margin: 0; background: var(--bg); color: var(--fg); }
32
33
  a { color: inherit; text-decoration: none; }
33
34
  h1 { font-size: 2rem; line-height: 1.1; letter-spacing: -0.04em; font-weight: 700; margin: 0 0 24px; }
34
- ::selection { background: var(--accent); color: #fff; }
35
+ ::selection { background: var(--accent); color: #1f1f1e; }
35
36
  .icon { flex: none; }
36
37
 
37
38
  /* Shell: a tab bar on a phone, a sidebar on a wide screen */
@@ -8,8 +8,12 @@ export interface Mailbox {
8
8
  id: string;
9
9
  address: string;
10
10
  }
11
+ /** The accent hue of an instance, picked by a hash of its mail domains. */
12
+ export declare function accentHue(domains: string[]): number;
11
13
  export interface LayoutOptions {
12
14
  theme: Theme;
15
+ /** The accent's hue, from `accentHue`. */
16
+ hue: number;
13
17
  page: Page;
14
18
  signedIn: boolean;
15
19
  draftCount?: number;
@@ -64,6 +68,7 @@ interface ThreadListOptions {
64
68
  /** Mailbox ids and catch-all addresses, as filter values. */
65
69
  accounts: string[];
66
70
  accountOf: (t: Thread) => string;
71
+ addressOf: (account: string) => string;
67
72
  filter: InboxFilter;
68
73
  own: (address: string) => boolean;
69
74
  current: string | null;
@@ -86,6 +91,6 @@ export declare function threadView(thread: Thread, entries: ThreadEntry[], ctx:
86
91
  };
87
92
  }): View;
88
93
  export declare function archiveButton(thread: Thread): View;
89
- export declare function devicesPage(sessions: Session[], currentId: string): View;
94
+ export declare function devicesPage(sessions: Session[], currentId: string, addressOf: (account: string) => string): View;
90
95
  export declare function settingsPage(theme: Theme): View;
91
96
  export {};
package/dist/ui/views.js CHANGED
@@ -1,6 +1,7 @@
1
+ import { crc32 } from "node:zlib";
1
2
  import { html, raw } from "hono/html";
2
3
  import { bareAddress } from "../core/address.js";
3
- import { CATCHALL } from "../types.js";
4
+ import {} from "../types.js";
4
5
  import { ASSETS } from "./assets.js";
5
6
  import { S } from "./strings.js";
6
7
  /** Views never await, so `html` returns a plain escaped string. */
@@ -63,25 +64,32 @@ function initials(address) {
63
64
  const words = (name.includes("@") ? name.split("@")[0] : name).split(/[\s._-]+/).filter(Boolean);
64
65
  return (words.length > 1 ? words[0][0] + words[1][0] : (words[0] ?? "?").slice(0, 2)).toUpperCase();
65
66
  }
67
+ /** Pastel hues (OKLCH degrees) for the accent, so several Inboxers tell apart at a glance. */
68
+ const ACCENT_HUES = [45, 75, 105, 145, 175, 205, 235, 265, 295, 325, 355];
69
+ /** The accent hue of an instance, picked by a hash of its mail domains. */
70
+ export function accentHue(domains) {
71
+ return ACCENT_HUES[crc32([...domains].sort().join(",")) % ACCENT_HUES.length];
72
+ }
66
73
  export function layout(title, body, opts) {
67
74
  const link = (page, href, label, name, extra = "") => h `<a href="${href}" ${raw(opts.page === page ? 'aria-current="page"' : "")}>${icon(name)}<span>${label}</span>${extra}</a>`;
68
75
  const count = opts.draftCount ? h `<span class="count">${opts.draftCount}</span>` : "";
69
76
  const canSend = !!opts.senders?.length;
70
77
  return h `<!doctype html>
71
- <html lang="en" ${raw(opts.theme === "system" ? "" : `data-theme="${opts.theme}"`)}>
78
+ <html lang="en" style="--hue: ${opts.hue}" ${raw(opts.theme === "system" ? "" : `data-theme="${opts.theme}"`)}>
72
79
  <head>
73
80
  <meta charset="utf-8">
74
81
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
75
82
  <title>${title} · ${S.appName}</title>
83
+ <meta name="htmx-config" content='{"historyCacheSize":0,"refreshOnHistoryMiss":true}'>
76
84
  <link rel="stylesheet" href="${ASSETS["style.css"].url}">
77
85
  <script src="${ASSETS["htmx.min.js"].url}" defer></script>
78
86
  <script src="${ASSETS["app.js"].url}" defer></script>
79
87
  </head>
80
- <body class="${opts.signedIn ? "app" : ""} ${opts.fullScreen ? "full" : ""}">
88
+ <body class="${opts.signedIn ? "app" : ""} ${opts.fullScreen ? "full" : ""}" hx-boost="true">
81
89
  ${when(opts.signedIn, () => h `<aside class="sidebar">
82
90
  <div class="brand">${S.appName}<span>.</span></div>
83
91
  ${when(canSend, () => h `<button type="button" class="primary new-mail" data-compose>${icon("plus")}${S.newMail}</button>`)}
84
- <nav class="side-nav" aria-label="${S.mainNav}">
92
+ <nav class="side-nav" id="side-nav" data-live aria-label="${S.mainNav}">
85
93
  ${link("drafts", "/", S.navDrafts, "drafts", count)}
86
94
  ${link("inbox", "/inbox", S.navInbox, "inbox")}
87
95
  ${link("devices", "/devices", S.navDevices, "devices")}
@@ -89,7 +97,7 @@ ${when(opts.signedIn, () => h `<aside class="sidebar">
89
97
  <nav class="side-nav side-end" aria-label="${S.navSettings}">${link("settings", "/settings", S.navSettings, "settings")}</nav>
90
98
  </aside>`)}
91
99
  <main>${body}</main>
92
- ${when(opts.signedIn, () => h `<nav class="tabbar" aria-label="${S.mainNav}">
100
+ ${when(opts.signedIn, () => h `<nav class="tabbar" id="tabbar" data-live aria-label="${S.mainNav}">
93
101
  ${link("drafts", "/", S.navDrafts, "drafts", count)}
94
102
  ${link("inbox", "/inbox", S.navInbox, "inbox")}
95
103
  ${when(canSend, () => h `<button type="button" class="tab-compose" data-compose aria-label="${S.newMail}"><span>${icon("plus")}</span></button>`)}
@@ -156,12 +164,15 @@ export function signIn(token, valid) {
156
164
  <form method="post" action="/auth/${token}"><button class="primary">${S.signInButton}</button></form>
157
165
  </div>`;
158
166
  }
159
- /** An account by its mailbox id, or by the local part of an address the catch-all received. */
160
- function mailboxBadge(account) {
161
- return h `<span class="badge mailbox">${account.includes("@") ? account.slice(0, account.lastIndexOf("@")) : account}</span>`;
167
+ function localPart(address) {
168
+ return address.includes("@") ? address.slice(0, address.lastIndexOf("@")) : address;
169
+ }
170
+ /** An account by the local part of the address it receives mail at. */
171
+ function mailboxBadge(address) {
172
+ return h `<span class="badge mailbox">${localPart(address)}</span>`;
162
173
  }
163
174
  function draftAccount(d) {
164
- return d.mailbox === CATCHALL ? bareAddress(d.from) : d.mailbox;
175
+ return bareAddress(d.from);
165
176
  }
166
177
  const PREVIEWABLE = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
167
178
  /** Image types a browser renders without running code; SVG is left out on purpose. */
@@ -320,7 +331,7 @@ function listTitle(domains, label) {
320
331
  }
321
332
  /** Drafts waiting for review, listed like the inbox; each opens its thread. */
322
333
  export function draftList(drafts, domains, current) {
323
- return h `<section class="list">
334
+ return h `<section class="list" id="list" data-live>
324
335
  <header class="list-head">${listTitle(domains, S.navDrafts)}</header>
325
336
  ${drafts.length ? join(drafts.map(d => h `<a class="row" href="/drafts/${d.id}" ${raw(d.id === current ? 'aria-current="page"' : "")}>
326
337
  <span class="avatar" aria-hidden="true">${initials(d.to[0] ?? d.mailbox)}</span>
@@ -329,7 +340,7 @@ export function draftList(drafts, domains, current) {
329
340
  <span class="row-subject">${d.subject || "—"}</span>
330
341
  <span class="row-snippet">${d.text}</span>
331
342
  <span class="row-tags">
332
- ${mailboxBadge(d.mailbox)}
343
+ ${mailboxBadge(draftAccount(d))}
333
344
  <span class="row-by">${d.edited_by_human ? S.editedByHuman : S.byAgent}</span>
334
345
  </span>
335
346
  </span>
@@ -342,16 +353,17 @@ export function inboxQuery(filter) {
342
353
  /** The thread list; on a wide screen it stays beside the open thread. */
343
354
  export function threadList(threads, opts) {
344
355
  const { filter } = opts;
356
+ const mailboxLabel = (m) => opts.domains.length === 1 ? localPart(opts.addressOf(m)) : opts.addressOf(m);
345
357
  const tab = (status, label) => h `<a class="chip" href="/inbox?${inboxQuery({ ...filter, status })}" ${raw(filter.status === status ? 'aria-current="page"' : "")}>${label}</a>`;
346
- return h `<section class="list">
358
+ return h `<section class="list" id="list" data-live>
347
359
  <header class="list-head">
348
360
  ${listTitle(opts.domains, S.navInbox)}
349
361
  <form class="filters" method="get" action="/inbox">
350
362
  <input type="hidden" name="status" value="${filter.status}">
351
363
  <nav class="chips" aria-label="${S.filter}">${tab("unanswered", S.filterPending)}${tab("all", S.filterAll)}${tab("archived", S.filterArchived)}</nav>
352
- ${when(opts.accounts.length > 1, () => h `<span class="select"><select name="mailbox" aria-label="${S.allMailboxes}" onchange="this.form.submit()">
364
+ ${when(opts.accounts.length > 1, () => h `<span class="select"><select name="mailbox" aria-label="${S.allMailboxes}" onchange="this.form.requestSubmit()">
353
365
  <option value="">${S.allMailboxes}</option>
354
- ${join(opts.accounts.map(m => h `<option value="${m}" ${raw(m === filter.mailbox ? "selected" : "")}>${m}</option>`))}
366
+ ${join(opts.accounts.map(m => h `<option value="${m}" ${raw(m === filter.mailbox ? "selected" : "")}>${mailboxLabel(m)}</option>`))}
355
367
  </select></span>`)}
356
368
  </form>
357
369
  </header>
@@ -367,7 +379,7 @@ function threadRow(t, opts) {
367
379
  <span class="row-subject">${t.subject || "—"}</span>
368
380
  ${when(t.has_draft || opts.accounts.length > 1 || t.unread, () => h `<span class="row-tags">
369
381
  ${when(t.has_draft, () => h `<span class="badge draft">${S.hasDraft}</span>`)}
370
- ${when(opts.accounts.length > 1, () => mailboxBadge(opts.accountOf(t)))}
382
+ ${when(opts.accounts.length > 1, () => mailboxBadge(opts.addressOf(opts.accountOf(t))))}
371
383
  ${when(t.unread, () => h `<span class="dot" title="${S.unread}"></span>`)}
372
384
  </span>`)}
373
385
  </span>
@@ -401,7 +413,7 @@ export function threadView(thread, entries, ctx, opts) {
401
413
  ${when(rows.length, () => h `<button type="button" class="context-btn" data-context-toggle aria-controls="context">${S.context}</button>`)}
402
414
  ${archiveButton(thread)}
403
415
  </header>
404
- <div class="messages" data-scroll-end>${join(items)}</div>
416
+ <div class="messages" id="messages" data-live data-scroll-end>${join(items)}</div>
405
417
  ${when(opts.reply.allowed, () => h `<form class="composer" method="post" action="/threads/${thread.id}/reply?${query}">
406
418
  ${when(opts.reply.replyAll, () => h `<label class="reply-all"><input type="checkbox" name="reply_all" value="1">${S.replyAll}</label>`)}
407
419
  <button type="button" class="icon-btn" aria-label="${S.fullReply}" title="${S.fullReply}" hx-get="/threads/${thread.id}/reply/full?${query}" hx-include="closest form" hx-target="#edit-sheet" hx-swap="innerHTML">${icon("plus")}</button>
@@ -423,7 +435,7 @@ export function archiveButton(thread) {
423
435
  <button class="icon-btn" aria-label="${label}" title="${label}">${icon(thread.archived ? "unarchive" : "archive")}</button>
424
436
  </form>`;
425
437
  }
426
- export function devicesPage(sessions, currentId) {
438
+ export function devicesPage(sessions, currentId, addressOf) {
427
439
  return h `<section class="list">
428
440
  <header class="list-head"><h1>${S.navDevices}</h1></header>
429
441
  ${sessions.length ? join(sessions.map(s => h `<div class="row device" id="session-${s.id}">
@@ -433,7 +445,7 @@ export function devicesPage(sessions, currentId) {
433
445
  ${when(s.label && s.user_agent, () => h `<span class="row-subject">${s.user_agent}</span>`)}
434
446
  <span class="row-tags">
435
447
  ${when(s.id === currentId, () => h `<span class="badge">${S.thisDevice}</span>`)}
436
- ${when(s.scope, () => join(s.scope.map(mailboxBadge)))}
448
+ ${when(s.scope, () => join(s.scope.map(m => mailboxBadge(addressOf(m)))))}
437
449
  <span class="row-by">${S.signedIn} ${formatDate(s.created_at)} · ${S.createdBy} ${s.created_by}</span>
438
450
  </span>
439
451
  </span>
@@ -446,7 +458,7 @@ export function devicesPage(sessions, currentId) {
446
458
  export function settingsPage(theme) {
447
459
  return h `<div class="page">
448
460
  <h1>${S.navSettings}</h1>
449
- <form class="setting" method="post" action="/theme">
461
+ <form class="setting" method="post" action="/theme" hx-boost="false">
450
462
  <label for="theme">${S.theme}</label>
451
463
  <span class="select"><select id="theme" name="theme" onchange="this.form.submit()">
452
464
  ${join(["system", "light", "dark"].map(t => h `<option value="${t}" ${raw(t === theme ? "selected" : "")}>${{ system: S.themeSystem, light: S.themeLight, dark: S.themeDark }[t]}</option>`))}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inboxer",
3
- "version": "0.4.9",
3
+ "version": "0.4.10",
4
4
  "description": "A self-hosted mail layer for agents: persists every inbound and outbound email, exposes an MCP server, and ships a minimal UI to review drafts.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/src/core/mail.ts CHANGED
@@ -101,6 +101,8 @@ export class Mail {
101
101
  private readonly domains: Set<string>;
102
102
  private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
103
103
  private readonly files: AttachmentFiles;
104
+ /** Fires "change" after every write, so open pages can refresh. */
105
+ readonly changes = new EventTarget();
104
106
 
105
107
  constructor(store: Store, provider: MailProvider, cfg: InboxerConfig) {
106
108
  this.store = store;
@@ -111,6 +113,13 @@ export class Mail {
111
113
  this.files = new AttachmentFiles(cfg.dataDir);
112
114
  }
113
115
 
116
+ /** Runs `fn` in the store's write queue, then announces the change. */
117
+ private async write<T>(fn: () => Promise<T>): Promise<T> {
118
+ const result = await this.store.serialize(fn);
119
+ this.changes.dispatchEvent(new Event("change"));
120
+ return result;
121
+ }
122
+
114
123
  listMailboxes(scope: Scope): { id: string; address: string; name: string }[] {
115
124
  return [
116
125
  ...Object.entries(this.cfg.mailboxes).map(([id, m]) => ({ id, address: m.address, name: m.name })),
@@ -134,6 +143,12 @@ export class Mail {
134
143
  return thread.mailbox === CATCHALL ? this.catchAllAddress(thread.participants) ?? CATCHALL : thread.mailbox;
135
144
  }
136
145
 
146
+ /** The address an account receives mail at: a configured mailbox's address, or the catch-all address itself. */
147
+ addressOf(account: string): string {
148
+ const mailbox = this.cfg.mailboxes[account];
149
+ return mailbox ? bareAddress(mailbox.address) : account;
150
+ }
151
+
137
152
  /** Mailboxes in scope, with the catch-all split into the addresses it has received mail for. */
138
153
  async listAccounts(scope: Scope): Promise<string[]> {
139
154
  const mailboxes = this.listMailboxes(scope).map(m => m.id).filter(id => id !== CATCHALL);
@@ -202,7 +217,7 @@ export class Mail {
202
217
  }
203
218
 
204
219
  private storeInbound(providerId: string, inbound: Awaited<ReturnType<MailProvider["getInbound"]>>): Promise<string> {
205
- return this.store.serialize(async () => {
220
+ return this.write(async () => {
206
221
  const existing = await this.store.lookupProviderId(this.provider.name, providerId);
207
222
  if (existing) return existing;
208
223
 
@@ -271,7 +286,7 @@ export class Mail {
271
286
 
272
287
  /** Status updates never move backwards: a late `sent` does not overwrite `delivered`. */
273
288
  applyStatus(providerId: string, status: DeliveryStatus, messageId: string | null): Promise<void> {
274
- return this.store.serialize(async () => {
289
+ return this.write(async () => {
275
290
  const id = await this.store.lookupProviderId(this.provider.name, providerId);
276
291
  if (!id) return;
277
292
  const message = await this.store.requireMessage(id);
@@ -359,7 +374,7 @@ export class Mail {
359
374
  const bare = bareAddress(address);
360
375
  if (!bare.includes("@")) throw new InvalidRequestError(`"${address}" is not an email address`);
361
376
  await this.requireContactAccess(bare, actor.scope);
362
- return this.store.serialize(async () => {
377
+ return this.write(async () => {
363
378
  const contact: Contact = { address: bare, ...this.merge(await this.store.getContact(bare), patch, actor) };
364
379
  await this.store.putContact(contact);
365
380
  await this.store.audit("contact.update", actor, bare, { ...patch });
@@ -368,7 +383,7 @@ export class Mail {
368
383
  }
369
384
 
370
385
  setThreadContext(threadId: string, patch: ContextPatch, actor: Actor): Promise<Context> {
371
- return this.store.serialize(async () => {
386
+ return this.write(async () => {
372
387
  await this.requireThread(threadId, actor.scope);
373
388
  const context = this.merge(await this.store.getThreadContext(threadId), patch, actor);
374
389
  await this.store.putThreadContext(threadId, context);
@@ -403,7 +418,7 @@ export class Mail {
403
418
  }
404
419
 
405
420
  private updateMessages(ids: string[], actor: Actor, action: string, change: (m: Message) => void): Promise<number> {
406
- return this.store.serialize(async () => {
421
+ return this.write(async () => {
407
422
  const messageIds = await this.resolveMessageIds(ids, actor.scope);
408
423
  const threads = new Set<string>();
409
424
  for (const id of messageIds) {
@@ -435,7 +450,7 @@ export class Mail {
435
450
  // Drafts and sending
436
451
 
437
452
  createDraft(input: CreateDraftInput, actor: Actor): Promise<Message> {
438
- return this.store.serialize(() => this.createDraftUnlocked(input, actor));
453
+ return this.write(() => this.createDraftUnlocked(input, actor));
439
454
  }
440
455
 
441
456
  /** Who a reply to `replyToId` goes to and its subject, without creating anything. */
@@ -537,7 +552,7 @@ export class Mail {
537
552
  * human edited unless it passes `force`. A UI edit regenerates the HTML from the text at send time.
538
553
  */
539
554
  updateDraft(id: string, version: number, patch: DraftPatch, actor: Actor, force = false): Promise<Message> {
540
- return this.store.serialize(async () => {
555
+ return this.write(async () => {
541
556
  const draft = await this.requireDraft(id, actor.scope);
542
557
  if (draft.version !== version) throw new ConflictError(draft);
543
558
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
@@ -559,7 +574,7 @@ export class Mail {
559
574
  }
560
575
 
561
576
  discardDraft(id: string, actor: Actor): Promise<void> {
562
- return this.store.serialize(() => this.discardDraftUnlocked(id, actor));
577
+ return this.write(() => this.discardDraftUnlocked(id, actor));
563
578
  }
564
579
 
565
580
  private async discardDraftUnlocked(id: string, actor: Actor): Promise<void> {
@@ -574,7 +589,7 @@ export class Mail {
574
589
 
575
590
  /** Attaching does not change `version`: it never conflicts with text edits in flight. */
576
591
  attach(id: string, file: { filename: string; contentType: string; body: Uint8Array }, actor: Actor): Promise<Message> {
577
- return this.store.serialize(async () => {
592
+ return this.write(async () => {
578
593
  const draft = await this.requireDraft(id, actor.scope);
579
594
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
580
595
  const meta: AttachmentMeta = {
@@ -594,7 +609,7 @@ export class Mail {
594
609
  }
595
610
 
596
611
  detach(id: string, attachmentId: string, actor: Actor): Promise<Message> {
597
- return this.store.serialize(async () => {
612
+ return this.write(async () => {
598
613
  const draft = await this.requireDraft(id, actor.scope);
599
614
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
600
615
  const index = draft.attachments.findIndex(a => a.id === attachmentId);
@@ -610,7 +625,7 @@ export class Mail {
610
625
 
611
626
  /** Starts the undo window for a send or discard. Calling it again keeps the first one. */
612
627
  schedule(id: string, action: PendingAction["action"], actor: Actor): Promise<Message> {
613
- return this.store.serialize(async () => {
628
+ return this.write(async () => {
614
629
  const draft = await this.requireDraft(id, actor.scope);
615
630
  if (!draft.pending) {
616
631
  draft.pending = { action, at: new Date(Date.now() + this.cfg.ui.undoSec * 1000).toISOString(), by: actor.name };
@@ -623,7 +638,7 @@ export class Mail {
623
638
  }
624
639
 
625
640
  undo(id: string, actor: Actor): Promise<Message> {
626
- return this.store.serialize(async () => {
641
+ return this.write(async () => {
627
642
  const draft = await this.requireDraft(id, actor.scope);
628
643
  clearTimeout(this.timers.get(id));
629
644
  this.timers.delete(id);
@@ -661,7 +676,7 @@ export class Mail {
661
676
  /** A failed send leaves a plain pending draft, so the reviewer sees it was not sent. */
662
677
  private runPending(id: string): Promise<void> {
663
678
  this.timers.delete(id);
664
- return this.store.serialize(async () => {
679
+ return this.write(async () => {
665
680
  const draft = await this.store.getMessage(id);
666
681
  if (!draft || draft.status !== "draft" || !draft.pending) return;
667
682
  const { action, by } = draft.pending;
@@ -674,7 +689,7 @@ export class Mail {
674
689
  }
675
690
 
676
691
  sendDraft(id: string, actor: Actor): Promise<Message> {
677
- return this.store.serialize(() => this.sendDraftUnlocked(id, actor));
692
+ return this.write(() => this.sendDraftUnlocked(id, actor));
678
693
  }
679
694
 
680
695
  /**
@@ -729,7 +744,7 @@ export class Mail {
729
744
 
730
745
  /** Direct send. If the provider fails, the message stays as a pending draft. */
731
746
  send(input: CreateDraftInput, actor: Actor): Promise<Message> {
732
- return this.store.serialize(async () => {
747
+ return this.write(async () => {
733
748
  const draft = await this.createDraftUnlocked(input, actor);
734
749
  return this.sendDraftUnlocked(draft.id, actor);
735
750
  });
package/src/ui/routes.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Context, Hono } from "hono";
2
2
  import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
3
+ import { streamSSE } from "hono/streaming";
3
4
  import type { Access } from "../auth.ts";
4
5
  import { domainOf, splitAddresses } from "../core/address.ts";
5
6
  import { ConflictError, InvalidRequestError, toView, type Mail, type MessageView, type ThreadStatus } from "../core/mail.ts";
@@ -33,6 +34,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
33
34
  const secret = cfg.ui.cookieSecret;
34
35
  const cookieOptions = { httpOnly: true, secure: true, sameSite: "Lax", path: "/", maxAge: COOKIE_MAX_AGE } as const;
35
36
 
37
+ const hue = V.accentHue([...new Set(Object.values(cfg.mailboxes).map(m => domainOf(m.address)))]);
36
38
  const own = (address: string): boolean => mail.isOwn(address);
37
39
  /** Recipients that are our own addresses are implied by the mailbox badge. */
38
40
  const shown = (m: MessageView): MessageView => ({
@@ -50,7 +52,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
50
52
  const shell = session
51
53
  ? { draftCount: (await mail.listDrafts(undefined, session.scope)).length, senders: senders(session) }
52
54
  : {};
53
- return c.html(V.layout(title, body, { theme: theme(c), page: current, signedIn: !!session, fullScreen, ...shell }), status);
55
+ return c.html(V.layout(title, body, { theme: theme(c), hue, page: current, signedIn: !!session, fullScreen, ...shell }), status);
54
56
  };
55
57
 
56
58
  // Sign-in: GET only shows a button, so link previews and scanners do not burn the link.
@@ -83,7 +85,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
83
85
  return c.redirect(path, 303);
84
86
  });
85
87
 
86
- const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/compose", "/devices", "/devices/*", "/settings", "/logout"];
88
+ const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/compose", "/devices", "/devices/*", "/settings", "/logout", "/events"];
87
89
  for (const path of ui) {
88
90
  app.use(path, async (c, next) => {
89
91
  const value = await getSignedCookie(c, secret, SESSION_COOKIE);
@@ -211,7 +213,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
211
213
  const filter = inboxFilter(c);
212
214
  const threads = await mail.listThreads({ mailbox: filter.mailbox || undefined, status: filter.status as ThreadStatus, limit: 200 }, session.scope);
213
215
  const accounts = await mail.listAccounts(session.scope);
214
- return V.threadList(threads, { accounts, accountOf: t => mail.accountOf(t), domains: domainsOf(session), filter, own, current });
216
+ return V.threadList(threads, { accounts, accountOf: t => mail.accountOf(t), addressOf: a => mail.addressOf(a), domains: domainsOf(session), filter, own, current });
215
217
  };
216
218
 
217
219
  app.get("/inbox", async c => page(c, S.navInbox, V.inboxPage(await threadList(c, null), null), "inbox"));
@@ -339,9 +341,17 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
339
341
 
340
342
  app.get("/devices", async c => {
341
343
  const session = c.get("session");
342
- return page(c, S.navDevices, V.devicesPage(await access.listSessions(session.scope), session.id), "devices");
344
+ return page(c, S.navDevices, V.devicesPage(await access.listSessions(session.scope), session.id, a => mail.addressOf(a)), "devices");
343
345
  });
344
346
 
347
+ // Every write pings open pages, which refetch their live regions; the stream carries no mail data.
348
+ app.get("/events", c => streamSSE(c, async stream => {
349
+ const ping = () => void stream.writeSSE({ event: "change", data: "1" });
350
+ mail.changes.addEventListener("change", ping);
351
+ await new Promise<void>(resolve => stream.onAbort(resolve));
352
+ mail.changes.removeEventListener("change", ping);
353
+ }));
354
+
345
355
  app.get("/settings", async c => page(c, S.navSettings, V.settingsPage(theme(c)), "settings"));
346
356
 
347
357
  app.post("/devices/:id/revoke", async c => {
@@ -353,6 +363,6 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
353
363
  const session = c.get("session");
354
364
  await access.revokeSession(session.id, uiActor(session), "session.logout");
355
365
  deleteCookie(c, SESSION_COOKIE, { path: "/", secure: true });
356
- return c.html(V.layout(S.signedOut, V.message([S.signedOut]), { theme: theme(c), page: null, signedIn: false }));
366
+ return c.html(V.layout(S.signedOut, V.message([S.signedOut]), { theme: theme(c), hue, page: null, signedIn: false }));
357
367
  });
358
368
  }
@@ -33,11 +33,72 @@ document.addEventListener("keydown", event => {
33
33
  if (event.key === "Escape") document.body.classList.remove("context-open");
34
34
  });
35
35
 
36
- // A thread opens at its latest message.
37
- document.addEventListener("DOMContentLoaded", () => {
36
+ // Links and forms load the next page with htmx and swap only the body, so scripts and styles stay loaded.
37
+ // The body's classes come from the new page, and an error page shows instead of nothing.
38
+ // Back and forward reload the page (see htmx-config), so a page is never restored with stale mail.
39
+ document.addEventListener("htmx:beforeSwap", event => {
40
+ if (!event.detail.boosted) return;
41
+ if (event.detail.xhr.status >= 400) {
42
+ event.detail.shouldSwap = true;
43
+ event.detail.isError = false;
44
+ }
45
+ document.body.className = /<body[^>]*class="([^"]*)"/.exec(event.detail.serverResponse)?.[1] ?? "";
46
+ });
47
+
48
+ document.addEventListener("htmx:afterSwap", event => {
49
+ if (event.detail.boosted) pageShown();
50
+ });
51
+
52
+ document.addEventListener("DOMContentLoaded", pageShown);
53
+
54
+ // A thread opens at its latest message; a signed-in page listens for changes.
55
+ function pageShown() {
38
56
  const messages = document.querySelector("[data-scroll-end]");
39
57
  if (messages) messages.scrollTop = messages.scrollHeight;
40
- });
58
+ listen();
59
+ }
60
+
61
+ // The server reports every change to the mail; the page then refetches itself once and swaps in its
62
+ // [data-live] regions by id. A burst of changes waits for a short quiet spell.
63
+ const REFRESH_DELAY_MS = 300;
64
+ let source = null;
65
+ let timer = null;
66
+
67
+ function listen() {
68
+ const signedIn = document.body.classList.contains("app");
69
+ if (signedIn && !source) {
70
+ source = new EventSource("/events");
71
+ source.addEventListener("change", refreshSoon);
72
+ // After a reconnect, changes made while it was down are caught up.
73
+ let opened = false;
74
+ source.addEventListener("open", () => opened ? refreshSoon() : opened = true);
75
+ } else if (!signedIn && source) {
76
+ source.close();
77
+ source = null;
78
+ }
79
+ }
80
+
81
+ function refreshSoon() {
82
+ clearTimeout(timer);
83
+ timer = setTimeout(refresh, REFRESH_DELAY_MS);
84
+ }
85
+
86
+ async function refresh() {
87
+ if (!document.querySelector("[data-live]")) return;
88
+ const url = location.href;
89
+ const res = await fetch(url);
90
+ if (!res.ok || location.href !== url) return;
91
+ const next = new DOMParser().parseFromString(await res.text(), "text/html");
92
+ for (const region of document.querySelectorAll("[data-live]")) {
93
+ const fresh = next.getElementById(region.id);
94
+ if (!fresh || region.contains(document.activeElement?.closest("input, select, textarea"))) continue;
95
+ const atEnd = region.scrollHeight - region.scrollTop - region.clientHeight < 2;
96
+ const scrollTop = region.scrollTop;
97
+ region.replaceWith(fresh);
98
+ fresh.scrollTop = fresh.hasAttribute("data-scroll-end") && atEnd ? fresh.scrollHeight : scrollTop;
99
+ htmx.process(fresh);
100
+ }
101
+ }
41
102
 
42
103
  // Files dropped on a [data-drop] zone go to its file input, which uploads them through htmx.
43
104
  const zoneOf = event => event.target instanceof Element ? event.target.closest("[data-drop]") : null;
@@ -7,10 +7,11 @@
7
7
  --soft: light-dark(#f1f1ef, #1f1f1e);
8
8
  --chip: light-dark(#e9e9e6, #333331);
9
9
  --surface: light-dark(#ffffff, #2e2e2c);
10
- --mine: light-dark(#ffe6d6, #4a2e20);
11
- --mine-line: light-dark(#ffd2b8, #5e3a28);
12
- --accent: light-dark(#ff4d00, #ff7a3d);
13
- --accent-text: light-dark(#c43d00, #ff8f5c);
10
+ /* --hue is set per instance on <html>, from its mail domains. */
11
+ --mine: light-dark(oklch(0.95 0.03 var(--hue)), oklch(0.33 0.045 var(--hue)));
12
+ --mine-line: light-dark(oklch(0.89 0.055 var(--hue)), oklch(0.4 0.06 var(--hue)));
13
+ --accent: light-dark(oklch(0.75 0.13 var(--hue)), oklch(0.78 0.11 var(--hue)));
14
+ --accent-text: light-dark(oklch(0.5 0.13 var(--hue)), oklch(0.83 0.09 var(--hue)));
14
15
  --focus: light-dark(#0a0a0a, #a3a39e);
15
16
  --primary-bg: light-dark(#0a0a0a, #ececea);
16
17
  --primary-fg: light-dark(#fbfbfa, #1f1f1e);
@@ -31,7 +32,7 @@
31
32
  body { margin: 0; background: var(--bg); color: var(--fg); }
32
33
  a { color: inherit; text-decoration: none; }
33
34
  h1 { font-size: 2rem; line-height: 1.1; letter-spacing: -0.04em; font-weight: 700; margin: 0 0 24px; }
34
- ::selection { background: var(--accent); color: #fff; }
35
+ ::selection { background: var(--accent); color: #1f1f1e; }
35
36
  .icon { flex: none; }
36
37
 
37
38
  /* Shell: a tab bar on a phone, a sidebar on a wide screen */
package/src/ui/views.ts CHANGED
@@ -1,8 +1,9 @@
1
+ import { crc32 } from "node:zlib";
1
2
  import { html, raw } from "hono/html";
2
3
  import type { HtmlEscapedString } from "hono/utils/html";
3
4
  import { bareAddress } from "../core/address.ts";
4
5
  import type { MessageView } from "../core/mail.ts";
5
- import { CATCHALL, type Contact, type Context, type Message, type Session, type Thread } from "../types.ts";
6
+ import { type Contact, type Context, type Message, type Session, type Thread } from "../types.ts";
6
7
  import { ASSETS } from "./assets.ts";
7
8
  import { S } from "./strings.ts";
8
9
 
@@ -85,8 +86,18 @@ export interface Mailbox {
85
86
  address: string;
86
87
  }
87
88
 
89
+ /** Pastel hues (OKLCH degrees) for the accent, so several Inboxers tell apart at a glance. */
90
+ const ACCENT_HUES = [45, 75, 105, 145, 175, 205, 235, 265, 295, 325, 355];
91
+
92
+ /** The accent hue of an instance, picked by a hash of its mail domains. */
93
+ export function accentHue(domains: string[]): number {
94
+ return ACCENT_HUES[crc32([...domains].sort().join(",")) % ACCENT_HUES.length]!;
95
+ }
96
+
88
97
  export interface LayoutOptions {
89
98
  theme: Theme;
99
+ /** The accent's hue, from `accentHue`. */
100
+ hue: number;
90
101
  page: Page;
91
102
  signedIn: boolean;
92
103
  draftCount?: number;
@@ -102,20 +113,21 @@ export function layout(title: string, body: View, opts: LayoutOptions): View {
102
113
  const count = opts.draftCount ? h`<span class="count">${opts.draftCount}</span>` : "";
103
114
  const canSend = !!opts.senders?.length;
104
115
  return h`<!doctype html>
105
- <html lang="en" ${raw(opts.theme === "system" ? "" : `data-theme="${opts.theme}"`)}>
116
+ <html lang="en" style="--hue: ${opts.hue}" ${raw(opts.theme === "system" ? "" : `data-theme="${opts.theme}"`)}>
106
117
  <head>
107
118
  <meta charset="utf-8">
108
119
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
109
120
  <title>${title} · ${S.appName}</title>
121
+ <meta name="htmx-config" content='{"historyCacheSize":0,"refreshOnHistoryMiss":true}'>
110
122
  <link rel="stylesheet" href="${ASSETS["style.css"]!.url}">
111
123
  <script src="${ASSETS["htmx.min.js"]!.url}" defer></script>
112
124
  <script src="${ASSETS["app.js"]!.url}" defer></script>
113
125
  </head>
114
- <body class="${opts.signedIn ? "app" : ""} ${opts.fullScreen ? "full" : ""}">
126
+ <body class="${opts.signedIn ? "app" : ""} ${opts.fullScreen ? "full" : ""}" hx-boost="true">
115
127
  ${when(opts.signedIn, () => h`<aside class="sidebar">
116
128
  <div class="brand">${S.appName}<span>.</span></div>
117
129
  ${when(canSend, () => h`<button type="button" class="primary new-mail" data-compose>${icon("plus")}${S.newMail}</button>`)}
118
- <nav class="side-nav" aria-label="${S.mainNav}">
130
+ <nav class="side-nav" id="side-nav" data-live aria-label="${S.mainNav}">
119
131
  ${link("drafts", "/", S.navDrafts, "drafts", count)}
120
132
  ${link("inbox", "/inbox", S.navInbox, "inbox")}
121
133
  ${link("devices", "/devices", S.navDevices, "devices")}
@@ -123,7 +135,7 @@ ${when(opts.signedIn, () => h`<aside class="sidebar">
123
135
  <nav class="side-nav side-end" aria-label="${S.navSettings}">${link("settings", "/settings", S.navSettings, "settings")}</nav>
124
136
  </aside>`)}
125
137
  <main>${body}</main>
126
- ${when(opts.signedIn, () => h`<nav class="tabbar" aria-label="${S.mainNav}">
138
+ ${when(opts.signedIn, () => h`<nav class="tabbar" id="tabbar" data-live aria-label="${S.mainNav}">
127
139
  ${link("drafts", "/", S.navDrafts, "drafts", count)}
128
140
  ${link("inbox", "/inbox", S.navInbox, "inbox")}
129
141
  ${when(canSend, () => h`<button type="button" class="tab-compose" data-compose aria-label="${S.newMail}"><span>${icon("plus")}</span></button>`)}
@@ -195,13 +207,17 @@ export function signIn(token: string, valid: boolean): View {
195
207
  </div>`;
196
208
  }
197
209
 
198
- /** An account by its mailbox id, or by the local part of an address the catch-all received. */
199
- function mailboxBadge(account: string): View {
200
- return h`<span class="badge mailbox">${account.includes("@") ? account.slice(0, account.lastIndexOf("@")) : account}</span>`;
210
+ function localPart(address: string): string {
211
+ return address.includes("@") ? address.slice(0, address.lastIndexOf("@")) : address;
212
+ }
213
+
214
+ /** An account by the local part of the address it receives mail at. */
215
+ function mailboxBadge(address: string): View {
216
+ return h`<span class="badge mailbox">${localPart(address)}</span>`;
201
217
  }
202
218
 
203
219
  function draftAccount(d: Message): string {
204
- return d.mailbox === CATCHALL ? bareAddress(d.from) : d.mailbox;
220
+ return bareAddress(d.from);
205
221
  }
206
222
 
207
223
  const PREVIEWABLE = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
@@ -383,7 +399,7 @@ function listTitle(domains: string[], label: string): View {
383
399
 
384
400
  /** Drafts waiting for review, listed like the inbox; each opens its thread. */
385
401
  export function draftList(drafts: Message[], domains: string[], current: string | null): View {
386
- return h`<section class="list">
402
+ return h`<section class="list" id="list" data-live>
387
403
  <header class="list-head">${listTitle(domains, S.navDrafts)}</header>
388
404
  ${drafts.length ? join(drafts.map(d => h`<a class="row" href="/drafts/${d.id}" ${raw(d.id === current ? 'aria-current="page"' : "")}>
389
405
  <span class="avatar" aria-hidden="true">${initials(d.to[0] ?? d.mailbox)}</span>
@@ -392,7 +408,7 @@ export function draftList(drafts: Message[], domains: string[], current: string
392
408
  <span class="row-subject">${d.subject || "—"}</span>
393
409
  <span class="row-snippet">${d.text}</span>
394
410
  <span class="row-tags">
395
- ${mailboxBadge(d.mailbox)}
411
+ ${mailboxBadge(draftAccount(d))}
396
412
  <span class="row-by">${d.edited_by_human ? S.editedByHuman : S.byAgent}</span>
397
413
  </span>
398
414
  </span>
@@ -412,17 +428,18 @@ export function inboxQuery(filter: InboxFilter): string {
412
428
  /** The thread list; on a wide screen it stays beside the open thread. */
413
429
  export function threadList(threads: Thread[], opts: ThreadListOptions & { domains: string[] }): View {
414
430
  const { filter } = opts;
415
- const tab = (status: string, label: string) =>
431
+ const mailboxLabel = (m: string) => opts.domains.length === 1 ? localPart(opts.addressOf(m)) : opts.addressOf(m);
432
+ const tab =(status: string, label: string) =>
416
433
  h`<a class="chip" href="/inbox?${inboxQuery({ ...filter, status })}" ${raw(filter.status === status ? 'aria-current="page"' : "")}>${label}</a>`;
417
- return h`<section class="list">
434
+ return h`<section class="list" id="list" data-live>
418
435
  <header class="list-head">
419
436
  ${listTitle(opts.domains, S.navInbox)}
420
437
  <form class="filters" method="get" action="/inbox">
421
438
  <input type="hidden" name="status" value="${filter.status}">
422
439
  <nav class="chips" aria-label="${S.filter}">${tab("unanswered", S.filterPending)}${tab("all", S.filterAll)}${tab("archived", S.filterArchived)}</nav>
423
- ${when(opts.accounts.length > 1, () => h`<span class="select"><select name="mailbox" aria-label="${S.allMailboxes}" onchange="this.form.submit()">
440
+ ${when(opts.accounts.length > 1, () => h`<span class="select"><select name="mailbox" aria-label="${S.allMailboxes}" onchange="this.form.requestSubmit()">
424
441
  <option value="">${S.allMailboxes}</option>
425
- ${join(opts.accounts.map(m => h`<option value="${m}" ${raw(m === filter.mailbox ? "selected" : "")}>${m}</option>`))}
442
+ ${join(opts.accounts.map(m => h`<option value="${m}" ${raw(m === filter.mailbox ? "selected" : "")}>${mailboxLabel(m)}</option>`))}
426
443
  </select></span>`)}
427
444
  </form>
428
445
  </header>
@@ -434,6 +451,7 @@ interface ThreadListOptions {
434
451
  /** Mailbox ids and catch-all addresses, as filter values. */
435
452
  accounts: string[];
436
453
  accountOf: (t: Thread) => string;
454
+ addressOf: (account: string) => string;
437
455
  filter: InboxFilter;
438
456
  own: (address: string) => boolean;
439
457
  current: string | null;
@@ -448,7 +466,7 @@ function threadRow(t: Thread, opts: ThreadListOptions): View {
448
466
  <span class="row-subject">${t.subject || "—"}</span>
449
467
  ${when(t.has_draft || opts.accounts.length > 1 || t.unread, () => h`<span class="row-tags">
450
468
  ${when(t.has_draft, () => h`<span class="badge draft">${S.hasDraft}</span>`)}
451
- ${when(opts.accounts.length > 1, () => mailboxBadge(opts.accountOf(t)))}
469
+ ${when(opts.accounts.length > 1, () => mailboxBadge(opts.addressOf(opts.accountOf(t))))}
452
470
  ${when(t.unread, () => h`<span class="dot" title="${S.unread}"></span>`)}
453
471
  </span>`)}
454
472
  </span>
@@ -488,7 +506,7 @@ export function threadView(thread: Thread, entries: ThreadEntry[], ctx: ContextV
488
506
  ${when(rows.length, () => h`<button type="button" class="context-btn" data-context-toggle aria-controls="context">${S.context}</button>`)}
489
507
  ${archiveButton(thread)}
490
508
  </header>
491
- <div class="messages" data-scroll-end>${join(items)}</div>
509
+ <div class="messages" id="messages" data-live data-scroll-end>${join(items)}</div>
492
510
  ${when(opts.reply.allowed, () => h`<form class="composer" method="post" action="/threads/${thread.id}/reply?${query}">
493
511
  ${when(opts.reply.replyAll, () => h`<label class="reply-all"><input type="checkbox" name="reply_all" value="1">${S.replyAll}</label>`)}
494
512
  <button type="button" class="icon-btn" aria-label="${S.fullReply}" title="${S.fullReply}" hx-get="/threads/${thread.id}/reply/full?${query}" hx-include="closest form" hx-target="#edit-sheet" hx-swap="innerHTML">${icon("plus")}</button>
@@ -512,7 +530,7 @@ export function archiveButton(thread: Thread): View {
512
530
  </form>`;
513
531
  }
514
532
 
515
- export function devicesPage(sessions: Session[], currentId: string): View {
533
+ export function devicesPage(sessions: Session[], currentId: string, addressOf: (account: string) => string): View {
516
534
  return h`<section class="list">
517
535
  <header class="list-head"><h1>${S.navDevices}</h1></header>
518
536
  ${sessions.length ? join(sessions.map(s => h`<div class="row device" id="session-${s.id}">
@@ -522,7 +540,7 @@ export function devicesPage(sessions: Session[], currentId: string): View {
522
540
  ${when(s.label && s.user_agent, () => h`<span class="row-subject">${s.user_agent}</span>`)}
523
541
  <span class="row-tags">
524
542
  ${when(s.id === currentId, () => h`<span class="badge">${S.thisDevice}</span>`)}
525
- ${when(s.scope, () => join(s.scope!.map(mailboxBadge)))}
543
+ ${when(s.scope, () => join(s.scope!.map(m => mailboxBadge(addressOf(m)))))}
526
544
  <span class="row-by">${S.signedIn} ${formatDate(s.created_at)} · ${S.createdBy} ${s.created_by}</span>
527
545
  </span>
528
546
  </span>
@@ -536,7 +554,7 @@ export function devicesPage(sessions: Session[], currentId: string): View {
536
554
  export function settingsPage(theme: Theme): View {
537
555
  return h`<div class="page">
538
556
  <h1>${S.navSettings}</h1>
539
- <form class="setting" method="post" action="/theme">
557
+ <form class="setting" method="post" action="/theme" hx-boost="false">
540
558
  <label for="theme">${S.theme}</label>
541
559
  <span class="select"><select id="theme" name="theme" onchange="this.form.submit()">
542
560
  ${join((["system", "light", "dark"] as const).map(t =>