inboxer 0.3.0 → 0.4.0

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.
package/dist/ui/routes.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
2
2
  import { bareAddress, domainOf, splitAddresses } from "../core/address.js";
3
- import { ConflictError, InvalidRequestError } from "../core/mail.js";
3
+ import { ConflictError, InvalidRequestError, toView } from "../core/mail.js";
4
4
  import { CATCHALL } from "../types.js";
5
5
  import { S } from "./strings.js";
6
6
  import * as V from "./views.js";
@@ -17,11 +17,6 @@ function clientInfo(c) {
17
17
  const forwarded = c.req.header("x-forwarded-for")?.split(",")[0]?.trim();
18
18
  return { ip: forwarded || c.req.header("x-real-ip") || null, userAgent: c.req.header("user-agent") ?? null };
19
19
  }
20
- /** htmx sends the page URL; draft cards on a thread page leave out the thread around them. */
21
- function onThreadPage(c) {
22
- const current = c.req.header("hx-current-url");
23
- return !!current && new URL(current).pathname.startsWith("/threads/");
24
- }
25
20
  function uiActor(session) {
26
21
  return { kind: "ui", name: session.label ?? session.id.slice(0, 12), scope: session.scope };
27
22
  }
@@ -35,21 +30,32 @@ export function registerUi(app, mail, access, cfg) {
35
30
  to: m.to.filter(a => !own.has(bareAddress(a))),
36
31
  cc: m.cc.filter(a => !own.has(bareAddress(a))),
37
32
  });
38
- const page = async (c, title, body, current, status = 200) => {
33
+ /** Mailboxes a session can send from: every one in its scope but the catch-all. */
34
+ const senders = (session) => mail.listMailboxes(session.scope).filter(m => m.id !== CATCHALL);
35
+ const domainsOf = (session) => [...new Set(senders(session).map(m => domainOf(m.address)))];
36
+ const page = async (c, title, body, current, status = 200, fullScreen = false) => {
39
37
  const session = c.get("session");
40
- const draftCount = session ? (await mail.listDrafts(undefined, session.scope)).length : 0;
41
- const domains = session
42
- ? [...new Set(mail.listMailboxes(session.scope).filter(m => m.id !== CATCHALL).map(m => domainOf(m.address)))]
43
- : [];
44
- return c.html(V.layout(title, body, { theme: theme(c), page: current, draftCount, signedIn: !!session, domains }), status);
38
+ const shell = session
39
+ ? { draftCount: (await mail.listDrafts(undefined, session.scope)).length, senders: senders(session) }
40
+ : {};
41
+ return c.html(V.layout(title, body, { theme: theme(c), page: current, signedIn: !!session, fullScreen, ...shell }), status);
45
42
  };
46
43
  // Sign-in: GET only shows a button, so link previews and scanners do not burn the link.
44
+ // A used or expired link on a browser that is already signed in just opens the app.
45
+ const signedInSession = async (c) => {
46
+ const value = await getSignedCookie(c, secret, SESSION_COOKIE);
47
+ return value ? access.authenticate(value) : null;
48
+ };
47
49
  app.get("/auth/:token", async (c) => {
48
50
  const valid = await access.isLinkValid(c.req.param("token"));
51
+ if (!valid && (await signedInSession(c)))
52
+ return c.redirect("/", 303);
49
53
  return page(c, S.signInTitle, V.signIn(c.req.param("token"), valid), null, valid ? 200 : 404);
50
54
  });
51
55
  app.post("/auth/:token", async (c) => {
52
56
  const signedIn = await access.consumeLoginLink(c.req.param("token"), clientInfo(c));
57
+ if (!signedIn && (await signedInSession(c)))
58
+ return c.redirect("/", 303);
53
59
  if (!signedIn)
54
60
  return page(c, S.signInTitle, V.signIn("", false), null, 404);
55
61
  await setSignedCookie(c, SESSION_COOKIE, signedIn.secret, secret, cookieOptions);
@@ -64,7 +70,7 @@ export function registerUi(app, mail, access, cfg) {
64
70
  const path = back && new URL(back).origin === new URL(c.req.url).origin ? new URL(back).pathname + new URL(back).search : "/";
65
71
  return c.redirect(path, 303);
66
72
  });
67
- const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/devices", "/devices/*", "/logout"];
73
+ const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/compose", "/devices", "/devices/*", "/settings", "/logout"];
68
74
  for (const path of ui) {
69
75
  app.use(path, async (c, next) => {
70
76
  const value = await getSignedCookie(c, secret, SESSION_COOKIE);
@@ -80,36 +86,35 @@ export function registerUi(app, mail, access, cfg) {
80
86
  await next();
81
87
  });
82
88
  }
83
- /** The sent and received messages around a draft, newest first, and the context of its thread. */
84
- const draftExtras = async (draft, session) => {
85
- const { messages, context, contacts } = await mail.getThread(draft.thread_id, session.scope);
86
- const history = messages.filter(m => m.id !== draft.id && m.status !== "draft").reverse().map(shown);
87
- return { history, ctx: { context, contacts } };
88
- };
89
- /** The card for a draft in whatever state it is now. */
89
+ /** The card for a draft in whatever state it is now; once sent, its message in the thread. */
90
90
  const draftView = async (c, id) => {
91
- const session = c.get("session");
92
- const draft = await mail.requireMessage(id, session.scope);
91
+ const draft = await mail.requireMessage(id, c.get("session").scope);
93
92
  if (draft.status === "discarded")
94
93
  return V.draftDone(id, S.discarded);
95
94
  if (draft.status !== "draft")
96
- return V.draftDone(id, `${S.sentTo} ${draft.to.join(", ")}`);
97
- if (onThreadPage(c))
98
- return V.draftCard(draft, [], null);
99
- const { history, ctx } = await draftExtras(draft, session);
100
- return V.draftCard(draft, history, ctx);
95
+ return V.messageBubble(shown(toView(draft)), false);
96
+ return V.draftCard(draft);
101
97
  };
102
98
  app.get("/", async (c) => {
99
+ const drafts = await mail.listDrafts(undefined, c.get("session").scope);
100
+ return page(c, S.navDrafts, V.inboxPage(V.draftList(drafts, null), null), "drafts");
101
+ });
102
+ app.get("/drafts/:id", async (c) => {
103
103
  const session = c.get("session");
104
+ const draft = await mail.requireMessage(c.req.param("id"), session.scope);
105
+ if (draft.status !== "draft")
106
+ return c.redirect(`/threads/${draft.thread_id}?status=all`, 303);
107
+ const { thread, view } = await threadPane(c, draft.thread_id, "/");
104
108
  const drafts = await mail.listDrafts(undefined, session.scope);
105
- const items = await Promise.all(drafts.map(async (draft) => ({ draft, ...(await draftExtras(draft, session)) })));
106
- return page(c, S.navDrafts, V.draftsPage(items), "drafts");
109
+ return page(c, thread.subject || S.navDrafts, V.inboxPage(V.draftList(drafts, draft.id), view), "drafts", 200, true);
107
110
  });
108
111
  app.get("/drafts/:id/card", async (c) => c.html(await draftView(c, c.req.param("id"))));
109
112
  app.get("/drafts/:id/edit", async (c) => {
110
113
  const draft = await mail.requireMessage(c.req.param("id"), c.get("session").scope);
111
- if (draft.status !== "draft" || draft.pending)
112
- return c.html(await draftView(c, draft.id));
114
+ if (draft.status !== "draft" || draft.pending) {
115
+ c.header("HX-Refresh", "true");
116
+ return c.body(null, 204);
117
+ }
113
118
  const form = { to: draft.to.join(", "), cc: draft.cc.join(", "), subject: draft.subject, text: draft.text };
114
119
  return c.html(V.draftEditor(draft, form, null));
115
120
  });
@@ -127,6 +132,7 @@ export function registerUi(app, mail, access, cfg) {
127
132
  }, actor);
128
133
  if (body.send === "1")
129
134
  await mail.schedule(id, "send", actor);
135
+ c.header("HX-Refresh", "true");
130
136
  return c.html(await draftView(c, id));
131
137
  }
132
138
  catch (err) {
@@ -137,20 +143,23 @@ export function registerUi(app, mail, access, cfg) {
137
143
  throw err;
138
144
  }
139
145
  });
140
- app.post("/drafts/:id/attachments", async (c) => {
141
- const id = c.req.param("id");
142
- const actor = uiActor(c.get("session"));
143
- const body = await c.req.parseBody({ all: true });
144
- const files = [].concat(body.files ?? []).filter((f) => f instanceof File);
146
+ /** Uploaded files within the size limit, and a message naming the last one over it. */
147
+ const uploads = (body) => {
148
+ const all = [].concat(body.files ?? []).filter((f) => f instanceof File && f.name !== "");
145
149
  const limit = cfg.ui.maxUploadMb * 1024 * 1024;
146
- let error = null;
150
+ const over = all.filter(f => f.size > limit).at(-1);
151
+ return { files: all.filter(f => f.size <= limit), error: over ? `${over.name} ${S.tooLarge} ${cfg.ui.maxUploadMb} MB` : null };
152
+ };
153
+ const attachAll = async (draftId, files, actor) => {
147
154
  for (const file of files) {
148
- if (file.size > limit) {
149
- error = `${file.name} ${S.tooLarge} ${cfg.ui.maxUploadMb} MB`;
150
- continue;
151
- }
152
- await mail.attach(id, { filename: file.name, contentType: file.type, body: new Uint8Array(await file.arrayBuffer()) }, actor);
155
+ await mail.attach(draftId, { filename: file.name, contentType: file.type, body: new Uint8Array(await file.arrayBuffer()) }, actor);
153
156
  }
157
+ };
158
+ app.post("/drafts/:id/attachments", async (c) => {
159
+ const id = c.req.param("id");
160
+ const actor = uiActor(c.get("session"));
161
+ const { files, error } = uploads(await c.req.parseBody({ all: true }));
162
+ await attachAll(id, files, actor);
154
163
  return c.html(V.draftFiles(await mail.requireMessage(id, actor.scope), error));
155
164
  });
156
165
  app.post("/drafts/:id/attachments/:attachmentId/remove", async (c) => {
@@ -175,27 +184,100 @@ export function registerUi(app, mail, access, cfg) {
175
184
  return c.html(await draftView(c, id));
176
185
  });
177
186
  }
178
- app.get("/inbox", async (c) => {
179
- const mailbox = c.req.query("mailbox") ?? "";
187
+ /** The inbox filter from the query, carried along when a thread opens beside the list. */
188
+ const inboxFilter = (c) => {
180
189
  const requested = c.req.query("status");
181
190
  const status = requested === "all" || requested === "archived" ? requested : "unanswered";
182
- const scope = c.get("session").scope;
183
- const threads = await mail.listThreads({ mailbox: mailbox || undefined, status, limit: 200 }, scope);
184
- const mailboxes = mail.listMailboxes(scope);
185
- const own = new Set(mailboxes.map(m => bareAddress(m.address)));
186
- return page(c, S.navInbox, V.inboxPage(threads, mailboxes.map(m => m.id), { mailbox, status }, own), "inbox");
187
- });
191
+ return { mailbox: c.req.query("mailbox") ?? "", status };
192
+ };
193
+ const threadList = async (c, current) => {
194
+ const session = c.get("session");
195
+ const filter = inboxFilter(c);
196
+ const threads = await mail.listThreads({ mailbox: filter.mailbox || undefined, status: filter.status, limit: 200 }, session.scope);
197
+ const mailboxes = mail.listMailboxes(session.scope).map(m => m.id);
198
+ return V.threadList(threads, { mailboxes, domains: domainsOf(session), filter, own, current });
199
+ };
200
+ app.get("/inbox", async (c) => page(c, S.navInbox, V.inboxPage(await threadList(c, null), null), "inbox"));
201
+ /** A thread with its drafts in place; opening it marks it read. */
202
+ const threadPane = async (c, id, back) => {
203
+ const session = c.get("session");
204
+ let thread = await mail.requireThread(id, session.scope);
205
+ if (thread.unread) {
206
+ await mail.mark([id], { read: true }, uiActor(session));
207
+ thread = await mail.requireThread(id, session.scope);
208
+ }
209
+ const { messages, context, contacts } = await mail.getThread(id, session.scope);
210
+ const people = thread.participants.filter(p => !own.has(p));
211
+ const entries = await Promise.all(messages.map(async (m) => ({
212
+ at: m.date,
213
+ view: m.status === "draft" ? V.draftCard(await mail.store.requireMessage(m.id)) : V.messageBubble(shown(m), people.length > 1),
214
+ })));
215
+ const reply = { allowed: senders(session).some(m => m.id === thread.mailbox), replyAll: people.length > 1 };
216
+ return { thread, view: V.threadView(thread, entries, { context, contacts }, { back, filter: inboxFilter(c), own, reply }) };
217
+ };
188
218
  app.get("/threads/:id", async (c) => {
189
219
  const id = c.req.param("id");
190
- const scope = c.get("session").scope;
191
- let thread = await mail.requireThread(id, scope);
192
- if (thread.unread) {
193
- await mail.mark([id], { read: true }, uiActor(c.get("session")));
194
- thread = await mail.requireThread(id, scope);
220
+ const { thread, view } = await threadPane(c, id, `/inbox?${V.inboxQuery(inboxFilter(c))}`);
221
+ return page(c, thread.subject || S.navInbox, V.inboxPage(await threadList(c, id), view), "inbox", 200, true);
222
+ });
223
+ /** Replies to the latest message; a reply sent from here gets the same undo window as a draft. */
224
+ /** Opens a reply to the latest message in the edit sheet, for Cc, subject and attachments. */
225
+ app.post("/threads/:id/reply/full", async (c) => {
226
+ const actor = uiActor(c.get("session"));
227
+ const body = await c.req.parseBody();
228
+ const { messages } = await mail.getThread(c.req.param("id"), actor.scope);
229
+ const latest = messages.filter(m => m.status !== "draft").at(-1);
230
+ if (!latest)
231
+ throw new InvalidRequestError("nothing to reply to");
232
+ const draft = await mail.createDraft({ replyToId: latest.id, replyAll: body.reply_all === "1", text: String(body.text ?? "") }, actor);
233
+ return c.html(V.newReplyEditor(draft));
234
+ });
235
+ app.post("/threads/:id/reply", async (c) => {
236
+ const id = c.req.param("id");
237
+ const actor = uiActor(c.get("session"));
238
+ const body = await c.req.parseBody();
239
+ const text = String(body.text ?? "");
240
+ const { messages } = await mail.getThread(id, actor.scope);
241
+ const latest = messages.filter(m => m.status !== "draft").at(-1);
242
+ const back = `/threads/${id}?${V.inboxQuery(inboxFilter(c))}`;
243
+ if (!latest || !text.trim())
244
+ return c.redirect(back, 303);
245
+ try {
246
+ const draft = await mail.createDraft({ replyToId: latest.id, replyAll: body.reply_all === "1", text }, actor);
247
+ if (body.action === "send")
248
+ await mail.schedule(draft.id, "send", actor);
249
+ }
250
+ catch (err) {
251
+ if (err instanceof InvalidRequestError)
252
+ return page(c, S.reply, V.message([err.message]), "inbox", 400);
253
+ throw err;
254
+ }
255
+ return c.redirect(back, 303);
256
+ });
257
+ app.post("/compose", async (c) => {
258
+ const actor = uiActor(c.get("session"));
259
+ const body = await c.req.parseBody({ all: true });
260
+ const { files, error } = uploads(body);
261
+ if (error)
262
+ return page(c, S.newMail, V.message([error]), null, 400);
263
+ try {
264
+ const draft = await mail.createDraft({
265
+ mailbox: String(body.mailbox ?? ""),
266
+ to: splitAddresses(String(body.to ?? "")),
267
+ cc: splitAddresses(String(body.cc ?? "")),
268
+ subject: String(body.subject ?? ""),
269
+ text: String(body.text ?? ""),
270
+ }, actor);
271
+ await attachAll(draft.id, files, actor);
272
+ if (body.action === "send")
273
+ await mail.schedule(draft.id, "send", actor);
274
+ return c.redirect(`/threads/${draft.thread_id}?status=all`, 303);
275
+ }
276
+ catch (err) {
277
+ if (err instanceof InvalidRequestError)
278
+ return page(c, S.newMail, V.message([err.message]), null, 400);
279
+ throw err;
195
280
  }
196
- const { messages, context, contacts } = await mail.getThread(id, scope);
197
- const items = await Promise.all([...messages].reverse().map(async (m) => m.status === "draft" ? V.draftCard(await mail.store.requireMessage(m.id), [], null) : V.messageCard(shown(m))));
198
- return page(c, thread.subject || S.navInbox, V.threadPage(thread, items, { context, contacts }), "inbox");
199
281
  });
200
282
  app.post("/threads/:id/archive", async (c) => {
201
283
  const id = c.req.param("id");
@@ -219,6 +301,7 @@ export function registerUi(app, mail, access, cfg) {
219
301
  const session = c.get("session");
220
302
  return page(c, S.navDevices, V.devicesPage(await access.listSessions(session.scope), session.id), "devices");
221
303
  });
304
+ app.get("/settings", async (c) => page(c, S.navSettings, V.settingsPage(theme(c)), "settings"));
222
305
  app.post("/devices/:id/revoke", async (c) => {
223
306
  await access.revokeSession(c.req.param("id"), uiActor(c.get("session")));
224
307
  return c.body(null, 200);
@@ -1,3 +1,49 @@
1
+ // New mail opens as a modal sheet; a click on its backdrop or a [data-close] button closes it.
2
+ document.addEventListener("click", event => {
3
+ const target = event.target instanceof Element ? event.target : null;
4
+ if (!target) return;
5
+ if (target.closest("[data-compose]")) {
6
+ const dialog = document.getElementById("compose");
7
+ dialog.showModal();
8
+ dialog.querySelector("#compose-to").focus();
9
+ } else if (target.closest("[data-close]")) {
10
+ target.closest("dialog").close();
11
+ } else if (target instanceof HTMLDialogElement && target.open) {
12
+ target.close();
13
+ } else if (target.closest("[data-context-toggle]")) {
14
+ document.body.classList.toggle("context-open");
15
+ }
16
+ });
17
+
18
+ // A draft's editor opens in the edit sheet; one draft is edited at a time.
19
+ document.addEventListener("htmx:afterSwap", event => {
20
+ const sheet = event.detail.target;
21
+ if (sheet.id !== "edit-sheet") return;
22
+ if (!sheet.open) sheet.showModal();
23
+ sheet.querySelector("textarea")?.focus();
24
+ });
25
+
26
+ // Closing the sheet on a reply started from the reply box shows its new draft in the thread.
27
+ document.addEventListener("close", event => {
28
+ if (event.target.id === "edit-sheet" && event.target.querySelector("[data-reload-on-close]")) location.reload();
29
+ }, true);
30
+
31
+ document.addEventListener("change", event => {
32
+ if (event.target.id === "compose-files") {
33
+ document.getElementById("compose-file-names").textContent = [...event.target.files].map(f => f.name).join(", ");
34
+ }
35
+ });
36
+
37
+ document.addEventListener("keydown", event => {
38
+ if (event.key === "Escape") document.body.classList.remove("context-open");
39
+ });
40
+
41
+ // A thread opens at its latest message.
42
+ document.addEventListener("DOMContentLoaded", () => {
43
+ const messages = document.querySelector("[data-scroll-end]");
44
+ if (messages) messages.scrollTop = messages.scrollHeight;
45
+ });
46
+
1
47
  // Files dropped on a [data-drop] zone go to its file input, which uploads them through htmx.
2
48
  const zoneOf = event => event.target instanceof Element ? event.target.closest("[data-drop]") : null;
3
49
  const hasFiles = event => [...(event.dataTransfer?.types ?? [])].includes("Files");