@wtfalch/email 0.13.1 → 0.14.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.
Files changed (42) hide show
  1. package/README.md +66 -4
  2. package/dist/mailbox/client.d.ts +22 -1
  3. package/dist/mailbox/client.js +45 -0
  4. package/dist/mailbox/fake/mailbox.js +205 -5
  5. package/dist/mailbox/index.d.ts +11 -7
  6. package/dist/mailbox/index.js +5 -3
  7. package/dist/mailbox/mail.css +13 -0
  8. package/dist/mailbox/mailboxes.d.ts +95 -1
  9. package/dist/mailbox/mailboxes.js +243 -1
  10. package/dist/mailbox/mutate.d.ts +21 -0
  11. package/dist/mailbox/mutate.js +71 -0
  12. package/dist/mailbox/quoted.d.ts +94 -0
  13. package/dist/mailbox/quoted.js +158 -0
  14. package/dist/mailbox/react/Composer.js +13 -1
  15. package/dist/mailbox/react/Mail.js +273 -33
  16. package/dist/mailbox/react/ThreadView.d.ts +13 -1
  17. package/dist/mailbox/react/ThreadView.js +5 -4
  18. package/dist/mailbox/react/index.d.ts +3 -1
  19. package/dist/mailbox/react/index.js +2 -1
  20. package/dist/mailbox/react/quotedHtml.d.ts +105 -0
  21. package/dist/mailbox/react/quotedHtml.js +163 -0
  22. package/dist/mailbox/snooze.d.ts +48 -0
  23. package/dist/mailbox/snooze.js +176 -0
  24. package/dist/mailbox/submit.d.ts +26 -0
  25. package/dist/mailbox/submit.js +88 -7
  26. package/dist/mailbox/threads.js +2 -0
  27. package/dist/mailbox/types.d.ts +40 -0
  28. package/dist/postmaster/apply.d.ts +154 -1
  29. package/dist/postmaster/apply.js +336 -1
  30. package/dist/postmaster/audit.d.ts +22 -1
  31. package/dist/postmaster/audit.js +7 -0
  32. package/dist/postmaster/client.d.ts +49 -0
  33. package/dist/postmaster/client.js +43 -0
  34. package/dist/postmaster/index.d.ts +4 -3
  35. package/dist/postmaster/index.js +3 -2
  36. package/dist/postmaster/objects.js +11 -0
  37. package/dist/postmaster/overview.d.ts +4 -0
  38. package/dist/postmaster/queue.d.ts +111 -0
  39. package/dist/postmaster/queue.js +64 -0
  40. package/dist/postmaster/writes.d.ts +59 -0
  41. package/dist/postmaster/writes.js +106 -0
  42. package/package.json +1 -1
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Finding the line where a received message's own words end and the quoted
3
+ * history it carries begins.
4
+ *
5
+ * This is `quoteText` (./drafts.ts) run backwards: that one takes a message
6
+ * and adds the `>` markers so a reply can carry the original along; this one
7
+ * takes a message that already has them and finds where they start.
8
+ * Composing a reply is pure text-building with no failure mode. Reading one
9
+ * is a heuristic that can guess wrong on a message this package never wrote,
10
+ * so it gets its own module, its own contract, and its own tests for the
11
+ * cases it is known not to cover.
12
+ *
13
+ * **The result is a boundary, not a summary.** A caller collapsing the
14
+ * thread view renders `body` and offers `quoted` behind a disclosure; a
15
+ * caller that wants everything just concatenates them back. `body + quoted`
16
+ * is always exactly the original string: nothing is trimmed, reformatted or
17
+ * thrown away in either half. A message with no quoted history returns the
18
+ * whole thing as `body` and `''` as `quoted`; a bare forward that is nothing
19
+ * but quoted history returns `''` as `body` and the whole thing as `quoted`.
20
+ *
21
+ * **HTML quote detection is not in this file, on purpose.** The natural tool
22
+ * for `<blockquote>`, Gmail's `gmail_quote` class and Outlook's `<div
23
+ * style="border-top:...">` divider is the inert-`DOMParser` walk this
24
+ * package already has, in `mailbox/react/sanitise.ts` — reusing it beats
25
+ * writing a second HTML parser or reaching for a regex over markup. But that
26
+ * file lives under `mailbox/react/`, the browser-only half of this package
27
+ * (`mailDocument`'s own doc comment: "Browser only: it needs `DOMParser`"),
28
+ * while this module is exported from `mailbox/index.ts`, the JMAP client
29
+ * core that has no `react` peer dependency and has to keep working with no
30
+ * DOM at all — `MailClient` is plain fetch and JSON. Importing
31
+ * `sanitise.ts` from here would make the core depend on the UI layer it is
32
+ * built under, and would make `@wtfalch/email/mailbox` throw in Node the
33
+ * first time a caller touched an HTML message. The HTML half belongs beside
34
+ * `sanitise.ts`, under `mailbox/react/`, as its own follow-up; this ships
35
+ * the text half only. See the PR body for the issue this opens.
36
+ */
37
+ /** The RFC 3676 quote leader: `>`, `>>`, `> >`... A line already inside a
38
+ * quote of a quote still starts with it, which is what lets a reply chain
39
+ * nest instead of losing its outer quote. Up to three leading spaces,
40
+ * because some clients indent a quoted block before the marker. */
41
+ const QUOTE_LEADER = /^ {0,3}>/;
42
+ /** Outlook's classic plain-text divider, any dash count either side. */
43
+ const ORIGINAL_MESSAGE_DIVIDER = /^ {0,3}-{2,}\s*Original Message\s*-{2,}\s*$/i;
44
+ /** Gmail's, Apple Mail's and this package's own (`attribution`, ./drafts.ts)
45
+ * attribution line, in whatever date format the sender's client wrote —
46
+ * `.{3,300}` is deliberately loose about the date and the name so long as
47
+ * the line reads `On <anything> wrote:` and nothing else. */
48
+ const ATTRIBUTION_LINE = /^ {0,3}On .{3,300} wrote:\s*$/i;
49
+ /** A line with nothing on it, so a client's unmarked blank line inside a
50
+ * multi-paragraph quote still counts as part of the trailing quote block. */
51
+ const BLANK_LINE = /^\s*$/;
52
+ function lines(text) {
53
+ const found = [];
54
+ let offset = 0;
55
+ while (offset <= text.length) {
56
+ const newline = text.indexOf('\n', offset);
57
+ const end = newline === -1 ? text.length : newline;
58
+ found.push({ start: offset, text: text.slice(offset, end) });
59
+ if (newline === -1)
60
+ break;
61
+ offset = newline + 1;
62
+ }
63
+ return found;
64
+ }
65
+ /**
66
+ * Whether `rest` — a line and everything after it — is nothing but blank
67
+ * lines and further `>` lines, all the way to the end of the message.
68
+ *
69
+ * This is what tells a genuine trailing block of quoted history apart from
70
+ * a `>` used for something else in the middle of a message: mail history is
71
+ * always top-posted, so a real quote never has ordinary text *after* it. A
72
+ * pasted diff or a Markdown quote does.
73
+ */
74
+ function onlyQuotedToEnd(rest) {
75
+ return rest.every((line) => BLANK_LINE.test(line.text) || QUOTE_LEADER.test(line.text));
76
+ }
77
+ /**
78
+ * The offset into `text` where its quoted history begins, or `text.length`
79
+ * when none of the three marker forms below appear.
80
+ *
81
+ * Walked one line at a time, not matched over the whole string, because `>`
82
+ * and `-----Original Message-----` are markers only at the start of a line —
83
+ * a `>` in the middle of a sentence is punctuation, not a quote. The
84
+ * attribution line and the Outlook divider open the boundary the moment
85
+ * either is seen; the `>` leader only gets one attempt, at the *first* `>`
86
+ * line in the message, and only opens the boundary there if the rest of the
87
+ * message is quote all the way down — see `onlyQuotedToEnd`. A `>` line
88
+ * that fails that check is not retried further down: the leader has nothing
89
+ * left to say about this message, on purpose (see `splitQuoted`'s doc
90
+ * comment on the interleaved case).
91
+ */
92
+ function boundaryOffset(text) {
93
+ const found = lines(text);
94
+ let quoteLeaderTried = false;
95
+ for (const [index, line] of found.entries()) {
96
+ if (ORIGINAL_MESSAGE_DIVIDER.test(line.text) || ATTRIBUTION_LINE.test(line.text)) {
97
+ return line.start;
98
+ }
99
+ if (!quoteLeaderTried && QUOTE_LEADER.test(line.text)) {
100
+ quoteLeaderTried = true;
101
+ if (onlyQuotedToEnd(found.slice(index)))
102
+ return line.start;
103
+ }
104
+ }
105
+ return text.length;
106
+ }
107
+ /**
108
+ * Where a received plain-text body's own words end and its quoted history
109
+ * begins.
110
+ *
111
+ * Covers three marker forms, deliberately not more:
112
+ * - `>` (and `>>`, nested) leading a line — but only when nothing but blank
113
+ * lines and further `>` lines follow it to the end of the message. A
114
+ * pasted diff (`> - old line`) or a Markdown quote (`> To be or not to
115
+ * be...`) followed by the sender's own text is not mail history and is
116
+ * left alone.
117
+ * - `On <when>, <who> wrote:` alone on a line.
118
+ * - `-----Original Message-----` alone on a line.
119
+ *
120
+ * Not covered, deliberately, because the issue budgets English and the
121
+ * marker forms above, not every locale:
122
+ * - a localised attribution or divider (French `Le ... a écrit :`, German
123
+ * `-----Ursprüngliche Nachricht-----`, Norwegian `-----Opprinnelig
124
+ * melding-----`, ...).
125
+ * - Apple Mail's `Begin forwarded message:` header (no dashes, no
126
+ * `wrote:`).
127
+ * - an attribution or divider line a client's own wrap split across two
128
+ * lines.
129
+ * - a genuine reply interleaved *between* two `>` blocks (quote, new text,
130
+ * quote): the trailing-only rule above is what keeps a pasted diff out of
131
+ * `quoted`, but it costs the same thing here on purpose — the first `>`
132
+ * line gets one attempt, finds real text after it, and gives up for the
133
+ * whole message rather than guessing which later `>` block is the real
134
+ * one. The entire message stays as `body`, unsplit. That is the safe
135
+ * direction to be wrong in: nothing new is ever lost into `quoted`, only
136
+ * nothing gets collapsed.
137
+ * - a stray `On ... wrote:` sentence that is someone's actual new writing,
138
+ * alone on its own line, rather than a header. Unlike the `>` leader this
139
+ * one is not checked for trailing content, so it is a real false
140
+ * positive: everything from that line to the end of the message —
141
+ * however much text that is — is read as quoted history and disappears
142
+ * from `body`.
143
+ *
144
+ * A message that trips none of the three markers keeps its whole text as
145
+ * `body` — the same answer this gives a message with no quoted history at
146
+ * all, which is the safe direction to be wrong in: nothing is hidden, it is
147
+ * just not collapsed.
148
+ */
149
+ export function splitQuoted(text) {
150
+ const offset = boundaryOffset(text);
151
+ return { body: text.slice(0, offset), quoted: text.slice(offset) };
152
+ }
153
+ /** `splitQuoted` against a received message's own plain-text body. A
154
+ * message with no text body (HTML-only) has nothing to split: the whole
155
+ * boundary is empty, not a guess. */
156
+ export function quoteBoundary(message) {
157
+ return splitQuoted(message.text ?? '');
158
+ }
@@ -39,8 +39,20 @@ export function Composer({ draft, onChange, onSend, onCancel, identities, onAtta
39
39
  const [uploads, setUploads] = useState([]);
40
40
  const [dropping, setDropping] = useState(false);
41
41
  const picker = useRef(null);
42
+ const root = useRef(null);
42
43
  const controllers = useRef(new Map());
43
44
  const counter = useRef(0);
45
+ /* Scrolls itself into view the moment it mounts. `ThreadView` inserts a
46
+ reply where three small buttons used to be, at whatever scroll position
47
+ the reader was already at, and nothing else moves the page to show the
48
+ newly-tall form -- or the message directly above it, which is what
49
+ `block: 'nearest'` keeps in frame rather than re-centring past it (#56).
50
+ `key={drafted}` (`Mail.tsx`) remounts this on every new reply, forward
51
+ or "New message", including a second reply started while the first is
52
+ still open, so an empty dependency list still fires once per compose. */
53
+ useEffect(() => {
54
+ root.current?.scrollIntoView({ block: 'nearest' });
55
+ }, []);
44
56
  /* dragenter and dragleave fire for every child the pointer crosses, so
45
57
  "is something over the composer" is a count, not the last event seen. */
46
58
  const depth = useRef(0);
@@ -149,7 +161,7 @@ export function Composer({ draft, onChange, onSend, onCancel, identities, onAtta
149
161
  browser in place of the page -- and the page here is somebody's
150
162
  half-written message. Text dragged into the body is left alone. */
151
163
  const carriesFiles = (event) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
152
- return (_jsxs("form", { className: `composer${dropping ? ' is-dropping' : ''}${className ? ` ${className}` : ''}`, onSubmit: (event) => {
164
+ return (_jsxs("form", { ref: root, className: `composer${dropping ? ' is-dropping' : ''}${className ? ` ${className}` : ''}`, onSubmit: (event) => {
153
165
  event.preventDefault();
154
166
  if (canSend)
155
167
  void onSend();
@@ -3,10 +3,10 @@ import { Button, Command, Icon, Modal, SplitPane } from '@wtfalch/design';
3
3
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
4
  import { attach } from "../attach.js";
5
5
  import { downloadAttachment } from "../download.js";
6
- import { forwardDraft, replyDraft } from "../drafts.js";
6
+ import { forwardDraft, forwardIntroduction, quoteText, replyDraft } from "../drafts.js";
7
7
  import { findRole } from "../mailboxes.js";
8
- import { moveToRole, setFlagged, setRead } from "../mutate.js";
9
- import { send } from "../submit.js";
8
+ import { moveThread, moveToRole, setFlagged, setRead } from "../mutate.js";
9
+ import { saveDraft, send } from "../submit.js";
10
10
  import { Composer } from "./Composer.js";
11
11
  import { MailboxTree, flatMailboxes } from "./MailboxTree.js";
12
12
  import { ThreadList } from "./ThreadList.js";
@@ -55,6 +55,17 @@ const OFFLINE_GRACE_MS = 10_000;
55
55
  /** A logo or a signature is kilobytes; five megabytes is a photograph, and
56
56
  * past that it is an attachment wearing a `cid:`. */
57
57
  const INLINE_MAX_BYTES = 5 * 1024 * 1024;
58
+ /** A mailbox tree turned into `Command`'s shape, one picker's action bound
59
+ * to each row. Shared by the `⌘K` "Go to" group and the `v` move list,
60
+ * which differ only in what running a row does. */
61
+ function mailboxCommands(nodes, onPick) {
62
+ return nodes.map((box) => ({
63
+ id: box.id,
64
+ label: box.name,
65
+ keywords: [box.role ?? ''],
66
+ onRun: () => onPick(box),
67
+ }));
68
+ }
58
69
  export function Mail({ client, location, onNavigate, account, onError, now, className, }) {
59
70
  const [ownMailboxId, setOwnMailboxId] = useState(null);
60
71
  const [ownThreadId, setOwnThreadId] = useState(null);
@@ -85,9 +96,17 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
85
96
  to the draft it was opened for: without a new key, a file still uploading
86
97
  for one message would land on the next. */
87
98
  const [drafted, setDrafted] = useState(0);
99
+ /* Which thread a reply or forward belongs to, so it renders under *that*
100
+ thread and nowhere else (#56). `null` means either nothing is being
101
+ composed or `c` started a message with no thread to sit under -- the two
102
+ look the same to a renderer deciding where to put a `Composer`, so one
103
+ flag covers both and the modal below is what `null` means when `draft`
104
+ is not. */
105
+ const [draftThreadId, setDraftThreadId] = useState(null);
88
106
  const [sending, setSending] = useState(false);
89
107
  const [sendError, setSendError] = useState();
90
108
  const [paletteOpen, setPaletteOpen] = useState(false);
109
+ const [moveOpen, setMoveOpen] = useState(false);
91
110
  const [drawerOpen, setDrawerOpen] = useState(false);
92
111
  const [helpOpen, setHelpOpen] = useState(false);
93
112
  const [acting, setActing] = useState(false);
@@ -216,38 +235,197 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
216
235
  };
217
236
  }, [client, threadId, summary, refresh]);
218
237
  const identity = identities.data?.[0];
219
- const startReply = useCallback((message, all) => {
238
+ /**
239
+ * An identity's plain-text signature, by exact id -- never a fallback,
240
+ * because by the time this is called the id in hand is already the right
241
+ * one: the session default at draft creation, or (below) the identity
242
+ * just picked in the composer. There is nothing to fall back to; unlike
243
+ * `doSend`'s `sendAs`, this never resolves a `draft.identityId` that
244
+ * could name an identity nobody has confirmed exists.
245
+ */
246
+ const signatureFor = useCallback((identityId) => identities.data?.find((one) => one.id === identityId)?.textSignature ?? '', [identities.data]);
247
+ /** A draft for `who`, built from `source` the same way regardless of
248
+ * whether this is the first build (draft creation) or a rebuild (an
249
+ * identity switch, below). `replyDraft`/`forwardDraft` stay pure and
250
+ * completely untouched: the signature is spliced onto what they return,
251
+ * here, once per build, never folded into builders that are meant to be
252
+ * safe to call on every keystroke. */
253
+ const buildDraft = useCallback((source, who) => {
254
+ const signature = signatureFor(who.id);
255
+ if (source.kind === 'reply') {
256
+ const base = replyDraft(source.message, { identity: who, all: source.all });
257
+ // An empty signature leaves `base` -- the untouched `"\n\n" + quote`
258
+ // -- exactly as it was before this feature existed.
259
+ return signature
260
+ ? { ...base, text: `\n\n${signature}\n\n${quoteText(source.message)}` }
261
+ : base;
262
+ }
263
+ if (source.kind === 'forward') {
264
+ const base = forwardDraft(source.message, { identity: who });
265
+ return signature
266
+ ? {
267
+ ...base,
268
+ text: `\n\n${signature}\n\n${forwardIntroduction(source.message)}\n${source.message.text ?? ''}`,
269
+ }
270
+ : base;
271
+ }
272
+ // The signature is the whole body: an empty one leaves the literal
273
+ // empty string this always started with.
274
+ return { identityId: who.id, to: [], subject: '', text: signature };
275
+ }, [signatureFor]);
276
+ /** The draft in hand right now, as `buildDraft` last produced it, so an
277
+ * identity switch (in `changeDraft`, below) can tell whether the body is
278
+ * still exactly what it started as. */
279
+ const [origin, setOrigin] = useState(null);
280
+ const start = useCallback((source) => {
220
281
  if (!identity)
221
282
  return;
222
283
  setSendError(undefined);
223
284
  setDrafted((n) => n + 1);
224
- setDraft(replyDraft(message, { identity, all }));
225
- }, [identity]);
226
- const startForward = useCallback((message) => {
227
- if (!identity)
285
+ // Ties this draft to the open thread, so it renders under it rather
286
+ // than in the "new message" modal (#56) -- except `new`, which has no
287
+ // thread to sit under and keeps the modal. Always the thread on
288
+ // screen: every caller of `startReply`/`startForward` -- the toolbar,
289
+ // the per-message menu, the foot buttons, the `r`/`a`/`f` shortcuts --
290
+ // acts on a message drawn from `thread.data`, and that is always the
291
+ // thread `threadId` names.
292
+ setDraftThreadId(source.kind === 'new' ? null : threadId);
293
+ const next = buildDraft(source, identity);
294
+ setOrigin({ identityId: next.identityId, text: next.text ?? '', source });
295
+ setDraft(next);
296
+ }, [identity, buildDraft, threadId]);
297
+ const startReply = useCallback((message, all) => start({ kind: 'reply', message, all }), [start]);
298
+ const startForward = useCallback((message) => start({ kind: 'forward', message }), [start]);
299
+ const startNew = useCallback(() => start({ kind: 'new' }), [start]);
300
+ /**
301
+ * What the composer's `onChange` actually calls (#42 follow-up).
302
+ *
303
+ * `doSend` sends as `draft.identityId` -- the picker's own choice (#61) --
304
+ * so starting a reply and then switching identities sends correctly.
305
+ * Left alone, the *signature* would not follow: it is spliced in once, at
306
+ * creation, from whichever identity built the draft, and a plain
307
+ * `setDraft` on an identity change would leave that signature sitting
308
+ * under a `From` it no longer names.
309
+ *
310
+ * This re-signs, but only when the body is untouched: `origin` remembers
311
+ * the text the draft was last built with, and a change that both picks a
312
+ * new identity *and* still matches that text, exactly, is treated as "no
313
+ * one has typed anything yet" and rebuilt for the new identity. Anything
314
+ * else -- a single keystroke, even one since undone back to the same
315
+ * text -- is sent straight through: overwriting what somebody wrote is
316
+ * worse than a signature that does not match. No marker is embedded in
317
+ * the body to tell the two cases apart -- decision #34 ruled a marker
318
+ * convention out -- so exact equality with the last built text is the
319
+ * one thing this checks.
320
+ *
321
+ * A signature and a send can still disagree: type first, then switch
322
+ * identities, and the body -- signature included -- is left exactly as
323
+ * written, on purpose.
324
+ */
325
+ const changeDraft = useCallback((next) => {
326
+ if (origin && next.identityId !== origin.identityId && next.text === origin.text) {
327
+ const picked = identities.data?.find((one) => one.id === next.identityId);
328
+ if (picked) {
329
+ const rebuilt = buildDraft(origin.source, picked);
330
+ setOrigin({
331
+ identityId: rebuilt.identityId,
332
+ text: rebuilt.text ?? '',
333
+ source: origin.source,
334
+ });
335
+ setDraft(rebuilt);
336
+ return;
337
+ }
338
+ }
339
+ setDraft(next);
340
+ }, [origin, identities.data, buildDraft]);
341
+ /** Discards whichever composer is open -- the "new message" modal or the
342
+ * reply/forward panel under the thread. This is the *un*-saved close: the
343
+ * ✕, and Escape. Not while a send is in flight: that would abandon a
344
+ * message already on its way, the same guard the modal's own close
345
+ * button and scrim used. */
346
+ const closeComposer = useCallback(() => {
347
+ setDraft(null);
348
+ setDraftThreadId(null);
349
+ }, []);
350
+ /**
351
+ * Leaving the thread a reply or forward belongs to -- while it is still
352
+ * open -- without an explicit Discard.
353
+ *
354
+ * A modal made this impossible to do by accident: the scrim and the focus
355
+ * trap blocked every other control, so the only ways out were Send,
356
+ * Discard, and Escape, all of them a deliberate act of leaving. An inline
357
+ * composer has no such wall -- the list and the mailbox tree stay
358
+ * reachable beside it on the medium and wide layouts, `⌘K` "Go to" still
359
+ * opens, and a host wiring `location`/`onNavigate` to a router can move
360
+ * `threadId` out from under it on a browser Back with nothing pressed at
361
+ * all. So this is not a click handler on any one of those controls -- it
362
+ * is `threadId` itself, watched below, which is the one thing every path
363
+ * off the thread changes in common, including archiving or trashing the
364
+ * thread the reply belongs to.
365
+ *
366
+ * An untouched draft -- `origin`'s own test, the one `changeDraft` above
367
+ * already relies on for the same reason (there is no marker in the body
368
+ * to tell "typed" from "not" apart, #34) -- is discarded: nothing was
369
+ * written, so there is nothing to lose. Anything else is saved to Drafts
370
+ * first, the same store `saveDraft` has always written to and that
371
+ * nothing under `react/` had ever called. A failed save is not swallowed
372
+ * either -- it is said the way a failed archive or move already is
373
+ * (`act`, above).
374
+ */
375
+ const settleComposer = useCallback(async () => {
376
+ if (!draft || draftThreadId === null)
228
377
  return;
229
- setSendError(undefined);
230
- setDrafted((n) => n + 1);
231
- setDraft(forwardDraft(message, { identity }));
232
- }, [identity]);
233
- const startNew = useCallback(() => {
234
- if (!identity)
378
+ const leaving = draft;
379
+ const untouched = origin !== null && (leaving.text ?? '') === origin.text;
380
+ closeComposer();
381
+ if (untouched)
235
382
  return;
236
- setSendError(undefined);
237
- setDrafted((n) => n + 1);
238
- setDraft({ identityId: identity.id, to: [], subject: '', text: '' });
239
- }, [identity]);
383
+ try {
384
+ const sendAs = identities.data?.find((one) => one.id === leaving.identityId) ?? identity;
385
+ await saveDraft(client, leaving, undefined, {
386
+ ...(sendAs ? { identity: sendAs } : {}),
387
+ ...(boxes.data ? { mailboxes: boxes.data } : {}),
388
+ });
389
+ setNote('Saved to Drafts.');
390
+ refresh();
391
+ }
392
+ catch (error) {
393
+ setNote(error instanceof Error ? error.message : 'The draft was not saved.');
394
+ }
395
+ }, [
396
+ draft,
397
+ draftThreadId,
398
+ origin,
399
+ identities.data,
400
+ identity,
401
+ client,
402
+ boxes.data,
403
+ closeComposer,
404
+ refresh,
405
+ ]);
406
+ useEffect(() => {
407
+ if (draftThreadId !== null && draftThreadId !== threadId)
408
+ void settleComposer();
409
+ }, [threadId, draftThreadId, settleComposer]);
240
410
  const doSend = async () => {
241
411
  if (!draft)
242
412
  return;
243
413
  setSending(true);
244
414
  setSendError(undefined);
245
415
  try {
416
+ // The identity to send as is the draft's own -- what the picker in
417
+ // `Composer` writes -- not the one-per-session default `identity` used
418
+ // to *build* a draft. Passing that default here would override the
419
+ // picker's choice, because `submit.ts`'s `options.identity` wins over
420
+ // `draft.identityId` on purpose (a caller holding the identity already
421
+ // saves an `Identity/get`). Falling back to `identity` only when the
422
+ // draft names none keeps a single-identity account unchanged.
423
+ const sendAs = identities.data?.find((one) => one.id === draft.identityId) ?? identity;
246
424
  await send(client, draft, {
247
- ...(identity ? { identity } : {}),
425
+ ...(sendAs ? { identity: sendAs } : {}),
248
426
  ...(boxes.data ? { mailboxes: boxes.data } : {}),
249
427
  });
250
- setDraft(null);
428
+ closeComposer();
251
429
  setNote('Message sent.');
252
430
  refresh();
253
431
  }
@@ -300,6 +478,15 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
300
478
  return;
301
479
  void act(() => setRead(client, threadId, false), 'Marked unread.');
302
480
  }, [act, client, threadId]);
481
+ /** Files the open conversation into any mailbox, chosen from the `v`
482
+ * picker below -- unlike `archive`/`trash`, which move to a *role* and
483
+ * throw when the account has none, this moves to an id the reader just
484
+ * picked from the tree, so there is nothing to be missing. */
485
+ const move = useCallback((mailbox) => {
486
+ if (!threadId)
487
+ return;
488
+ void act(() => moveThread(client, threadId, mailbox.id), `Moved to ${mailbox.name}.`);
489
+ }, [act, client, threadId]);
303
490
  /**
304
491
  * An attachment, fetched and handed to the browser.
305
492
  *
@@ -347,13 +534,24 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
347
534
  *
348
535
  * **A field swallows everything but Escape and Cmd-K.** `c` for compose and
349
536
  * `c` typed into a subject line are the same keystroke, and a client that
350
- * cannot tell them apart is a client you cannot write mail in. The test is
351
- * the event's target, not a focus flag, because focus can be inside a
352
- * portalled dialog that this component never rendered.
537
+ * cannot tell them apart is a client you cannot write mail in. The test
538
+ * started as the event's target, not a focus flag, because focus can be
539
+ * inside a portalled dialog that this component never rendered.
540
+ *
541
+ * **The target alone stopped being enough once `Command` got a second
542
+ * job.** React Aria's `Autocomplete` -- what both the Cmd-K palette and the
543
+ * `v` picker are built on -- re-dispatches a keydown onto a wrapping `<div>`
544
+ * for its virtual-focus bookkeeping before letting it bubble, so by the
545
+ * time this window listener sees it, `event.target` is that div, not the
546
+ * search field the person is actually looking at. `document.activeElement`
547
+ * does not lie about that, so it is checked too: a field, by either
548
+ * account, is a field. Real focus is what a checkbox or a button leaves it
549
+ * on, and this codebase's earlier "focus can be inside a portalled dialog"
550
+ * concern is answered the same way `event.target` always answered it --
551
+ * `document.activeElement` reaches into a portal exactly as well.
353
552
  */
354
553
  useEffect(() => {
355
- const typing = (target) => {
356
- const el = target;
554
+ const isField = (el) => {
357
555
  if (!el?.tagName)
358
556
  return false;
359
557
  return (el.tagName === 'INPUT' ||
@@ -361,12 +559,28 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
361
559
  el.tagName === 'SELECT' ||
362
560
  el.isContentEditable);
363
561
  };
562
+ const typing = (target) => isField(target) ||
563
+ isField(document.activeElement);
364
564
  const onKey = (event) => {
365
565
  if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
366
566
  event.preventDefault();
367
567
  setPaletteOpen(true);
368
568
  return;
369
569
  }
570
+ /* The reply/forward composer sits inline now, under its thread, with
571
+ no dialog trapping Escape the way the "new message" modal still
572
+ does -- so this is that dialog's Escape, by hand. Checked before
573
+ "typing" swallows it, because it has to work while focus is inside
574
+ the composer's own fields, and before the narrow layout's
575
+ Escape-goes-back-to-the-list case below, so closing the composer
576
+ never also navigates off the thread it belongs to (#56). */
577
+ if (event.key === 'Escape' && draftThreadId !== null) {
578
+ if (sending)
579
+ return;
580
+ event.preventDefault();
581
+ closeComposer();
582
+ return;
583
+ }
370
584
  if (event.metaKey || event.ctrlKey || event.altKey)
371
585
  return;
372
586
  if (typing(event.target))
@@ -408,6 +622,12 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
408
622
  event.preventDefault();
409
623
  flag(!summary?.isFlagged);
410
624
  break;
625
+ case 'v':
626
+ if (!threadId)
627
+ break;
628
+ event.preventDefault();
629
+ setMoveOpen(true);
630
+ break;
411
631
  case 'r':
412
632
  case 'a': {
413
633
  const newest = thread.data?.messages[thread.data.messages.length - 1];
@@ -455,16 +675,14 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
455
675
  archiveBox,
456
676
  trashBox,
457
677
  refresh,
678
+ draftThreadId,
679
+ sending,
680
+ closeComposer,
458
681
  ]);
459
682
  const paletteGroups = useMemo(() => [
460
683
  {
461
684
  title: 'Go to',
462
- commands: flatMailboxes(boxes.data ?? []).map((box) => ({
463
- id: box.id,
464
- label: box.name,
465
- keywords: [box.role ?? ''],
466
- onRun: () => go(box),
467
- })),
685
+ commands: mailboxCommands(flatMailboxes(boxes.data ?? []), go),
468
686
  },
469
687
  {
470
688
  title: 'Message',
@@ -489,6 +707,17 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
489
707
  ],
490
708
  },
491
709
  ], [boxes.data, go, refresh, startNew, threadId, archive, trash, markUnread, archiveBox, trashBox]);
710
+ /* The `v` picker's list: the same mailboxes as "Go to", minus the one the
711
+ conversation is already sitting in -- filing it where it already is is
712
+ not a move. Nothing else is excluded: `MailboxNode` carries no rights a
713
+ server refused, so the current folder is the only destination this
714
+ client knows in advance is wrong. */
715
+ const moveGroups = useMemo(() => [
716
+ {
717
+ title: 'Move to',
718
+ commands: mailboxCommands(flatMailboxes(boxes.data ?? []).filter((box) => box.id !== mailboxId), move),
719
+ },
720
+ ], [boxes.data, mailboxId, move]);
492
721
  /* On one column the message replaces the list; on two or three they are
493
722
  both up and this is always false. */
494
723
  const reading = panes === 'narrow' && threadId !== null;
@@ -514,8 +743,18 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
514
743
  setQuery('');
515
744
  }, "aria-label": "Clear the search", children: _jsx(Icon, { name: "close", size: 13 }) })) : (_jsx("span", { className: "mail-search-key", "aria-hidden": "true", children: "/" }))] }));
516
745
  const list = (_jsx(ThreadList, { page: threads.data, selectedId: threadId, onSelect: openThread, onPage: (threads.data?.total ?? 0) > PAGE ? setPosition : undefined, limit: PAGE, loading: threads.loading, now: now, title: query ? `Results for “${query}”` : current?.name, empty: query ? _jsxs("p", { className: "threads-quiet", children: ["Nothing matches \u201C", query, "\u201D."] }) : undefined }));
517
- const reader = (_jsx(ThreadView, { thread: thread.data, loading: thread.loading, onReply: startReply, onForward: startForward, onArchive: archiveBox ? archive : undefined, onTrash: trashBox ? trash : undefined, onMarkUnread: markUnread, onFlag: flag, onDownload: (file) => void download(file), downloading: downloading, fetchInline: fetchInline, flagged: summary?.isFlagged ?? false, busy: acting, onBack: panes === 'narrow' ? () => setThreadId(null) : undefined }));
518
- return (_jsxs("div", { className: `mail is-${panes}${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "mail-bar", children: [_jsxs("div", { className: "mail-bar-start", children: [panes === 'narrow' && (_jsx(Button, { kind: "ghost", iconOnly: true, onClick: () => setDrawerOpen(true), "aria-label": "Mailboxes", children: _jsx(Icon, { name: "menu" }) })), _jsx("span", { className: "mail-wordmark", children: "Mail" })] }), searchBox, _jsxs("div", { className: "mail-bar-end", children: [!live && (_jsxs("span", { className: "mail-offline", title: OFFLINE_TITLE, children: [_jsx(Icon, { name: "wifi-off", size: 15 }), _jsx("span", { className: "mail-offline-word", children: "Not live" })] })), _jsx(Button, { kind: "ghost", iconOnly: true, onClick: refresh, "aria-label": live ? 'Refresh' : OFFLINE_TITLE, children: _jsx(Icon, { name: "refresh", size: 15 }) }), _jsxs(Button, { kind: "primary", size: "sm", onClick: startNew, disabled: !identity, children: [_jsx(Icon, { name: "pen", size: 15 }), " ", _jsx("span", { className: "mail-compose-word", children: "Compose" })] }), account] })] }), panes === 'wide' && (_jsxs(SplitPane, { className: "mail-panes", label: "Mailbox list width", defaultSize: 15, min: 11, max: 28, storageKey: "mail-sidebar", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }), _jsxs(SplitPane, { label: "Conversation list width", defaultSize: 36, min: 26, max: 55, storageKey: "mail-list", children: [list, reader] })] })), panes === 'medium' && (_jsxs("div", { className: "mail-panes", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading, rail: true }), _jsxs(SplitPane, { className: "mail-panes-split", label: "Conversation list width", defaultSize: 40, min: 28, max: 60, storageKey: "mail-list", children: [list, reader] })] })), panes === 'narrow' && _jsx("div", { className: "mail-panes", children: reading ? reader : list }), drawerOpen && (_jsx(Modal, { title: "Mailboxes", width: "20rem", onClose: () => setDrawerOpen(false), children: _jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }) })), _jsx(Command, { open: paletteOpen, onOpenChange: setPaletteOpen, groups: paletteGroups }), helpOpen && (_jsx(Modal, { title: "Keyboard shortcuts", width: "26rem", onClose: () => setHelpOpen(false), children: _jsx(Shortcuts, {}) })), draft && (_jsx(Modal, { title: draft.subject ? draft.subject : 'New message', width: "46rem", onClose: sending ? undefined : () => setDraft(null), closeDisabled: sending, children: _jsx(Composer, { draft: draft, onChange: setDraft, onSend: doSend, onCancel: () => setDraft(null), identities: identities.data ?? [], onAttach: (file, signal) => attach(client, file, { signal }), limits: limits, sending: sending, error: sendError }, drafted) })), _jsx(Note, { said: note, onDone: () => setNote(null) })] }));
746
+ /* The composer, built once so the same element -- and the same upload
747
+ state inside it -- lands wherever `draftThreadId` says it belongs: the
748
+ modal for a message with no thread, or under the thread itself (#56). */
749
+ const composerElement = draft && (_jsx(Composer, { draft: draft, onChange: changeDraft, onSend: doSend, onCancel: closeComposer, identities: identities.data ?? [], onAttach: (file, signal) => attach(client, file, { signal }), limits: limits, sending: sending, error: sendError }, drafted));
750
+ /* Whether the open draft is a reply or forward addressed to the thread
751
+ currently on screen -- the only case an inline composer is drawn for.
752
+ False for a beat after navigating away from `draftThreadId`, which
753
+ `settleComposer` above saves or discards on the next tick; nothing
754
+ renders there in the meantime, which is correct and not visible. */
755
+ const replyingHere = draftThreadId !== null && draftThreadId === threadId;
756
+ const reader = (_jsx(ThreadView, { thread: thread.data, loading: thread.loading, onReply: startReply, onForward: startForward, onArchive: archiveBox ? archive : undefined, onTrash: trashBox ? trash : undefined, onMove: () => setMoveOpen(true), onMarkUnread: markUnread, onFlag: flag, onDownload: (file) => void download(file), downloading: downloading, fetchInline: fetchInline, flagged: summary?.isFlagged ?? false, busy: acting, onBack: panes === 'narrow' ? () => setThreadId(null) : undefined, composer: replyingHere ? composerElement : undefined }));
757
+ return (_jsxs("div", { className: `mail is-${panes}${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "mail-bar", children: [_jsxs("div", { className: "mail-bar-start", children: [panes === 'narrow' && (_jsx(Button, { kind: "ghost", iconOnly: true, onClick: () => setDrawerOpen(true), "aria-label": "Mailboxes", children: _jsx(Icon, { name: "menu" }) })), _jsx("span", { className: "mail-wordmark", children: "Mail" })] }), searchBox, _jsxs("div", { className: "mail-bar-end", children: [!live && (_jsxs("span", { className: "mail-offline", title: OFFLINE_TITLE, children: [_jsx(Icon, { name: "wifi-off", size: 15 }), _jsx("span", { className: "mail-offline-word", children: "Not live" })] })), _jsx(Button, { kind: "ghost", iconOnly: true, onClick: refresh, "aria-label": live ? 'Refresh' : OFFLINE_TITLE, children: _jsx(Icon, { name: "refresh", size: 15 }) }), _jsxs(Button, { kind: "primary", size: "sm", onClick: startNew, disabled: !identity, children: [_jsx(Icon, { name: "pen", size: 15 }), " ", _jsx("span", { className: "mail-compose-word", children: "Compose" })] }), account] })] }), panes === 'wide' && (_jsxs(SplitPane, { className: "mail-panes", label: "Mailbox list width", defaultSize: 15, min: 11, max: 28, storageKey: "mail-sidebar", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }), _jsxs(SplitPane, { label: "Conversation list width", defaultSize: 36, min: 26, max: 55, storageKey: "mail-list", children: [list, reader] })] })), panes === 'medium' && (_jsxs("div", { className: "mail-panes", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading, rail: true }), _jsxs(SplitPane, { className: "mail-panes-split", label: "Conversation list width", defaultSize: 40, min: 28, max: 60, storageKey: "mail-list", children: [list, reader] })] })), panes === 'narrow' && _jsx("div", { className: "mail-panes", children: reading ? reader : list }), drawerOpen && (_jsx(Modal, { title: "Mailboxes", width: "20rem", onClose: () => setDrawerOpen(false), children: _jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }) })), _jsx(Command, { open: paletteOpen, onOpenChange: setPaletteOpen, groups: paletteGroups }), _jsx(Command, { open: moveOpen, onOpenChange: setMoveOpen, groups: moveGroups, label: "Move to a folder", placeholder: "Move to\u2026" }), helpOpen && (_jsx(Modal, { title: "Keyboard shortcuts", width: "26rem", onClose: () => setHelpOpen(false), children: _jsx(Shortcuts, {}) })), draft && draftThreadId === null && (_jsx(Modal, { title: draft.subject ? draft.subject : 'New message', width: "46rem", onClose: sending ? undefined : closeComposer, closeDisabled: sending, children: composerElement })), _jsx(Note, { said: note, onDone: () => setNote(null) })] }));
519
758
  }
520
759
  /**
521
760
  * What just happened, said once and then gone.
@@ -556,6 +795,7 @@ function Shortcuts() {
556
795
  ['#', 'Delete'],
557
796
  ['U', 'Mark unread'],
558
797
  ['S', 'Flag'],
798
+ ['V', 'Move to a folder'],
559
799
  ['.', 'Refresh'],
560
800
  ['?', 'This list'],
561
801
  ];
@@ -41,6 +41,9 @@ export type ThreadActions = {
41
41
  onForward?: (message: Message) => void;
42
42
  onArchive?: () => void;
43
43
  onTrash?: () => void;
44
+ /** Opens the `v` picker; the picker itself, and the move it runs, are
45
+ * `Mail`'s -- this only says a mouse can reach the same door. */
46
+ onMove?: () => void;
44
47
  onMarkUnread?: () => void;
45
48
  onFlag?: (flagged: boolean) => void;
46
49
  /** True when the thread carries `$flagged`, for the star's pressed state. */
@@ -63,8 +66,17 @@ export type ThreadViewProps = ThreadActions & {
63
66
  fetchInline?: (attachment: Attachment) => Promise<Blob>;
64
67
  /** Back to the list, on a window too narrow to show both. */
65
68
  onBack?: () => void;
69
+ /**
70
+ * A reply or forward composer already wired up by the caller -- rendered
71
+ * where the quick Reply / Reply all / Forward buttons normally sit, in
72
+ * place of them, once one is open for this thread (#56). A slot rather
73
+ * than a `Draft`/`onSend`/`onChange` set of its own: `ThreadView` only
74
+ * places it, the same way `Mail` places `account` in its own header
75
+ * without knowing what is inside it.
76
+ */
77
+ composer?: React.ReactNode;
66
78
  className?: string;
67
79
  };
68
- export declare function ThreadView({ thread, loading, onReply, onForward, onArchive, onTrash, onMarkUnread, onFlag, flagged, busy, onDownload, downloading, fetchInline, onBack, className, }: ThreadViewProps): import("react").JSX.Element;
80
+ export declare function ThreadView({ thread, loading, onReply, onForward, onArchive, onTrash, onMove, onMarkUnread, onFlag, flagged, busy, onDownload, downloading, fetchInline, onBack, composer, className, }: ThreadViewProps): import("react").JSX.Element;
69
81
  /** Bytes, the way a mail client says them. */
70
82
  export declare function bytes(size: number): string;