@rapidmx/web-client 0.19.0 → 0.20.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 (131) hide show
  1. package/README.md +381 -381
  2. package/apps/admin/branding/index.tsx +39 -39
  3. package/apps/admin/data-requests/index.tsx +482 -482
  4. package/apps/admin/domains/[uid].tsx +166 -166
  5. package/apps/admin/escrow-scopes/[uid].tsx +350 -350
  6. package/apps/admin/index.tsx +129 -129
  7. package/apps/admin/mailboxes/[uid].tsx +271 -271
  8. package/apps/admin/mailboxes/new/index.tsx +30 -30
  9. package/apps/admin/plugins/index.tsx +15 -15
  10. package/apps/admin/retention-policy/index.tsx +39 -39
  11. package/apps/admin/signing-certificates/index.tsx +343 -343
  12. package/apps/escrow/audit-log/index.tsx +196 -196
  13. package/apps/escrow/matters/[uid].tsx +621 -621
  14. package/apps/shared/auth/adminAccess.ts +99 -99
  15. package/apps/shared/components/admin/diagnostics/HostCard.tsx +2 -0
  16. package/apps/shared/components/admin/diagnostics/PressureTiles.tsx +108 -0
  17. package/apps/shared/components/admin/diagnostics/PvcTable.tsx +20 -6
  18. package/apps/shared/components/admin/diagnostics/diagnosticsApi.ts +21 -2
  19. package/apps/shared/components/admin/layout/AdminShell.tsx +384 -384
  20. package/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.tsx +238 -238
  21. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -152
  22. package/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.tsx +194 -194
  23. package/apps/shared/components/admin/settings/BrandingForm.tsx +423 -423
  24. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -119
  25. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +198 -198
  26. package/apps/shared/components/admin/settings/PluginsManager.tsx +2093 -1620
  27. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +182 -182
  28. package/apps/shared/components/admin/settings/pluginPreferences.ts +34 -0
  29. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -288
  30. package/apps/shared/components/admin/setup/SetupWizard.tsx +446 -446
  31. package/apps/shared/components/admin/usePagedList.tsx +129 -129
  32. package/apps/shared/components/calendar/EventModal.tsx +206 -206
  33. package/apps/shared/components/calendar/MonthView.tsx +185 -185
  34. package/apps/shared/components/calendar/RecurrenceEditor.tsx +227 -227
  35. package/apps/shared/components/calendar/SplitDayView.tsx +144 -144
  36. package/apps/shared/components/calendar/TimeGridView.tsx +246 -246
  37. package/apps/shared/components/calendar/allDay.ts +124 -124
  38. package/apps/shared/components/contacts/ContactForm.tsx +383 -383
  39. package/apps/shared/components/contacts/ContactsToolbar.tsx +103 -103
  40. package/apps/shared/components/escrow/layout/EscrowShell.tsx +155 -155
  41. package/apps/shared/components/layout/AppShell.tsx +461 -461
  42. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +398 -398
  43. package/apps/shared/components/layout/MailboxProvisioning.tsx +168 -168
  44. package/apps/shared/components/layout/ResponsiveToolbar.tsx +315 -315
  45. package/apps/shared/components/layout/ThemeSwitch.tsx +84 -84
  46. package/apps/shared/components/layout/UserMenu.tsx +439 -439
  47. package/apps/shared/components/mail/ConversationList.tsx +332 -323
  48. package/apps/shared/components/mail/ConversationThreadPane.tsx +613 -613
  49. package/apps/shared/components/mail/MailSelectionBar.tsx +240 -240
  50. package/apps/shared/components/mail/MenuButton.tsx +404 -404
  51. package/apps/shared/components/mail/MessageDetailPane.tsx +1757 -1757
  52. package/apps/shared/components/mail/compose/ComposeContext.tsx +312 -312
  53. package/apps/shared/components/mail/compose/ComposeToolbar.tsx +422 -422
  54. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1681 -1681
  55. package/apps/shared/components/mail/compose/RichTextEditor.tsx +147 -147
  56. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -60
  57. package/apps/shared/components/mail/compose/quotedBody.ts +161 -161
  58. package/apps/shared/components/mail/listPreferences.ts +3 -3
  59. package/apps/shared/components/mail/reading/MessageMoreMenu.tsx +258 -258
  60. package/apps/shared/components/mail/reading/MessageSourceDialog.tsx +79 -79
  61. package/apps/shared/components/mail/reading/messageExport.ts +59 -59
  62. package/apps/shared/components/mail/reading/printMessage.ts +99 -99
  63. package/apps/shared/components/mail/reading/useMessageActions.ts +443 -443
  64. package/apps/shared/components/mail/verificationSeals.ts +125 -125
  65. package/apps/shared/components/rules/RuleBuilder.tsx +311 -311
  66. package/apps/shared/components/settings/SigningCertificateCard.tsx +344 -344
  67. package/apps/shared/keyboard/GlobalShortcuts.tsx +51 -51
  68. package/apps/shared/keyboard/ShortcutProvider.tsx +62 -62
  69. package/apps/shared/keyboard/ShortcutsDialog.tsx +84 -84
  70. package/apps/shared/keyboard/dispatch.ts +124 -124
  71. package/apps/shared/keyboard/format.ts +89 -89
  72. package/apps/shared/keyboard/keymap.ts +114 -114
  73. package/apps/shared/keyboard/registry.ts +65 -65
  74. package/apps/shared/keyboard/targets.ts +79 -79
  75. package/apps/shared/mail/folderOfType.ts +49 -49
  76. package/apps/shared/mail/folderTree.ts +143 -143
  77. package/apps/shared/mail/listAllPages.ts +39 -39
  78. package/apps/shared/mail/newMailNotifications.ts +171 -171
  79. package/apps/shared/mail/outbox/sendJob.ts +445 -445
  80. package/apps/shared/mail/outbox/sendOutcomes.ts +155 -155
  81. package/apps/shared/mail/reportNotices.ts +66 -66
  82. package/apps/shared/mail/senderBlocking.ts +141 -141
  83. package/apps/shared/mail/useMailConnection.ts +205 -205
  84. package/apps/shared/mail/useMailLiveUpdates.ts +277 -277
  85. package/apps/shared/mail/useMailboxUpdateAccess.ts +60 -60
  86. package/apps/shared/mail/useMarkMessageRead.ts +47 -47
  87. package/apps/shared/mail/useNewMailNotifications.ts +178 -178
  88. package/apps/shared/notifications/store.ts +560 -560
  89. package/apps/shared/search/LocalIndexLifecycle.tsx +114 -114
  90. package/apps/shared/search/localIndexBuilder.ts +481 -481
  91. package/apps/shared/signing/enrollmentStorage.ts +33 -33
  92. package/apps/shared/signing/enrollmentTracker.ts +385 -385
  93. package/apps/shared/signing/enrollmentView.ts +251 -251
  94. package/apps/shared/signing/useNow.ts +19 -19
  95. package/apps/shared/signing/useSigningEnrollmentWatcher.ts +90 -90
  96. package/apps/shared/styles/app.css +396 -396
  97. package/apps/www/calendar/index.tsx +581 -581
  98. package/apps/www/contacts/[uid].tsx +112 -112
  99. package/apps/www/index.tsx +3012 -2962
  100. package/apps/www/messages/[uid].tsx +139 -139
  101. package/apps/www/settings/auto-reply/index.tsx +136 -136
  102. package/apps/www/settings/blocked-senders/index.tsx +303 -303
  103. package/apps/www/settings/encryption/index.tsx +1290 -1290
  104. package/apps/www/settings/filters/[uid].tsx +179 -179
  105. package/apps/www/settings/filters/index.tsx +105 -105
  106. package/apps/www/settings/filters/new/index.tsx +165 -165
  107. package/apps/www/settings/labels/index.tsx +207 -207
  108. package/apps/www/settings/privacy/index.tsx +495 -495
  109. package/apps/www/settings/profile/index.tsx +251 -251
  110. package/apps/www/settings/read-receipts/index.tsx +150 -150
  111. package/apps/www/settings/sharing/index.tsx +259 -259
  112. package/apps/www/settings/signatures/[uid].tsx +175 -175
  113. package/apps/www/settings/signatures/index.tsx +91 -91
  114. package/apps/www/settings/signatures/new/index.tsx +138 -138
  115. package/apps/www/tasks/index.tsx +654 -654
  116. package/dist/apps/shared/components/admin/diagnostics/HostCard.js +2 -1
  117. package/dist/apps/shared/components/admin/diagnostics/PressureTiles.d.ts +22 -0
  118. package/dist/apps/shared/components/admin/diagnostics/PressureTiles.js +52 -0
  119. package/dist/apps/shared/components/admin/diagnostics/PvcTable.js +9 -4
  120. package/dist/apps/shared/components/admin/diagnostics/diagnosticsApi.d.ts +35 -2
  121. package/dist/apps/shared/components/admin/settings/BrandingForm.js +3 -3
  122. package/dist/apps/shared/components/admin/settings/PluginsManager.js +267 -35
  123. package/dist/apps/shared/components/admin/settings/pluginPreferences.d.ts +2 -0
  124. package/dist/apps/shared/components/admin/settings/pluginPreferences.js +35 -0
  125. package/dist/apps/shared/components/mail/ConversationList.d.ts +10 -3
  126. package/dist/apps/shared/components/mail/ConversationList.js +9 -5
  127. package/dist/apps/shared/components/mail/listPreferences.d.ts +1 -1
  128. package/dist/apps/shared/components/mail/reading/printMessage.js +11 -11
  129. package/dist/apps/shared/styles/app.css +396 -396
  130. package/dist/apps/www/index.js +51 -10
  131. package/package.json +2 -2
@@ -1,1681 +1,1681 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import React, { ChangeEvent, useEffect, useRef, useState } from "react";
6
- import {
7
- HiOutlineArrowsPointingIn,
8
- HiOutlineArrowsPointingOut,
9
- HiOutlineChevronDown,
10
- HiOutlineLockClosed,
11
- HiOutlineMinus,
12
- HiOutlinePaperClip,
13
- HiOutlineTrash,
14
- HiOutlineXMark,
15
- } from "react-icons/hi2";
16
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
17
- import {
18
- Attachment,
19
- ComposeRecipientInput,
20
- Mailbox,
21
- Message,
22
- assembleDraft,
23
- attachmentContentUrl,
24
- createDraft,
25
- deleteMessage,
26
- getMailbox,
27
- getMessage,
28
- listFolders,
29
- listMailboxes,
30
- uploadAttachment,
31
- } from "@rapidmx/react-shared/mail/mailApi.js";
32
- import { listMailSignatures } from "@rapidmx/react-shared/mail/mailSignaturesApi.js";
33
- import { buildComposeBodyHtml } from "@rapidmx/react-shared/mail/compose/composeQuoting.js";
34
- import { peekMailboxWritability, useMailboxWritability } from "../writableMailboxes.js";
35
- import { orderMailboxes, primaryMailboxUid } from "../../../mail/primaryMailbox.js";
36
- import { resolveRecipientEncryption, RecipientEncryptionStatus } from "@rapidmx/react-shared/crypto/composeSecurity.js";
37
- import { getUnlockedKeys, subscribeKeySession } from "@rapidmx/react-shared/crypto/keySession.js";
38
- import { EncryptionPolicy, findActivePublicKey, getEncryptionPolicy, lookupKeys } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
39
- import { useUnlockPrompt } from "../../layout/UnlockPromptProvider.js";
40
- import useIsMobile from "@rapidmx/react-shared/util/useIsMobile.js";
41
- import { notify } from "../../../notifications/store.js";
42
- import { evaluateEncryptionRequirement } from "./encryptionRequirement.js";
43
- import { decideSend, SendBlock } from "../../../mail/outbox/sendDecision.js";
44
- import { SendRequest, sendDecisionInput, startSend } from "../../../mail/outbox/sendJob.js";
45
- import { useCompose, type ComposeSession } from "./ComposeContext.js";
46
- import { ariaKeyShortcuts, withHint } from "../../../keyboard/format.js";
47
- import { SHORTCUTS, ShortcutDef } from "../../../keyboard/keymap.js";
48
- import { useKeyEnvironment } from "../../../keyboard/ShortcutProvider.js";
49
- import { useShortcut } from "../../../keyboard/useShortcut.js";
50
- import { isSigningOut, registerComposeFlush } from "./composeFlushRegistry.js";
51
- import { markComposePhase } from "./composePerf.js";
52
- import RecipientInput from "./RecipientInput.js";
53
- import { parseRecipientList } from "./recipients.js";
54
- import RichTextEditor from "./RichTextEditor.js";
55
- import ScheduleSendPicker from "./ScheduleSendPicker.js";
56
- import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
57
- import Button from "@rapidmx/react-shared/components/buttons/Button.js";
58
- import Modal from "@rapidmx/react-shared/components/overlays/Modal.js";
59
-
60
- export interface ComposeWindowProps {
61
- session: ComposeSession;
62
- onClose: () => void;
63
- onToggleMinimize: () => void;
64
- /** The signed-in user - identifies their own ("primary") mailbox, the default From when the session
65
- * doesn't name a mailbox. */
66
- userUid?: string;
67
- /** The caller holds a trusted (admin) role - every mailbox is writable, so no per-mailbox access checks. */
68
- trusted?: boolean;
69
- /** How long (ms) after the last edit the draft is autosaved. Defaults to `DEFAULT_AUTOSAVE_DELAY_MS`;
70
- * only overridden by tests. */
71
- autosaveDelayMs?: number;
72
- /** Backoff (ms) between automatic retries of a failed mailbox/encryption-policy load, one entry per retry.
73
- * Defaults to `DEFAULT_CRYPTO_RETRY_DELAYS_MS`; only overridden by tests. */
74
- cryptoRetryDelaysMs?: number[];
75
- }
76
-
77
- /** Debounce between the last edit and the draft autosave. */
78
- export const DEFAULT_AUTOSAVE_DELAY_MS = 2000;
79
-
80
- /** Automatic, silent retries of a failed mailbox/encryption-policy (or recipient key) load, one entry per retry - a flapping gateway is waited out
81
- * in the background, without a word to the user. */
82
- export const DEFAULT_CRYPTO_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000, 30000, 60000];
83
-
84
- /** Thrown by `deleteDraft()` when the server copy is no longer this window's draft (sent or scheduled elsewhere). */
85
- const NO_LONGER_A_DRAFT_MESSAGE = "This message was already sent or scheduled from another window, so it wasn't deleted.";
86
-
87
- /** Whether `fresh` (a re-read of a draft) is still an unsent draft in `folderUid`: never delete a message another
88
- * window has since sent, scheduled, or started sending. */
89
- function isStillDraft(fresh: Message, folderUid: string): boolean {
90
- return fresh.folderUid === folderUid && !fresh.scheduledSendTime && !fresh.scheduledSendLeaseExpiresAt && !fresh.scheduledSendRelayedAt;
91
- }
92
-
93
- const SAVE_STATUS_LABEL = { idle: "", saving: "Saving…", saved: "Draft saved", error: "Couldn't save draft" } as const;
94
-
95
- const DISCARD_TITLE = "Discard this draft?";
96
- /** Shown only for a message that is actually headed for encryption (asked for, or applied by the loaded policy) - see `encryptionRequirement.ts`. */
97
- const ENCRYPTED_CLOSE_MESSAGE = "Encrypted messages aren't saved as drafts, so closing this window discards what you've written.";
98
-
99
- /** The confirmation shown before a Close/Discard throws content away (or when a Close couldn't save it). */
100
- interface ClosePrompt {
101
- title: string;
102
- message: string;
103
- }
104
-
105
- const FIELD_ROW = "flex items-center gap-2 px-3 py-1.5 border-b border-border";
106
- const FIELD_INPUT = "flex-1 min-w-0 text-sm bg-transparent outline-none";
107
-
108
- const MIN_WIDTH = 320;
109
- const MIN_HEIGHT = 320;
110
- // Kept well clear of the viewport edge, not flush against it — this is a resize *ceiling* (the drag
111
- // handles below clamp to it), not the "expanded" preset's own size, which stays a plain `85vh`
112
- // Tailwind class precisely so it never needs `window.innerHeight` at all: that'd have to be read at
113
- // module-evaluation time to live alongside these other constants, and `window` doesn't exist yet
114
- // during this app's SSR pass (see `ReactRoute`) — referencing it here would crash every page render,
115
- // not just this component's.
116
- const VIEWPORT_MARGIN = 24;
117
-
118
- interface Size {
119
- width: number;
120
- height: number;
121
- }
122
-
123
- type ResizeEdge = "left" | "top" | "corner";
124
-
125
- /** A To/Cc/Bcc field's recipients - see `recipients.ts` for the format. */
126
- function parseAddresses(value: string): ComposeRecipientInput[] {
127
- return parseRecipientList(value);
128
- }
129
-
130
- /**
131
- * Normalizes an address into the key `recipientStatuses`/the in-flight and failure trackers below use -
132
- * matching `classifyRecipientTier()`'s own lowercase-domain comparison (`@rapidmx/react-shared`'s
133
- * `composeSecurity.ts`), but applied to the whole address rather than just the domain. Without this, the
134
- * same mailbox typed with different casing across To/Cc/Bcc (plausible via autocomplete vs. a pasted
135
- * signature block) is tracked as two independent recipients: if one lookup lags or fails while the other
136
- * succeeds, `decideMessageEncryption()`'s all-or-nothing check sees a spurious unresolved recipient and
137
- * denies auto-encryption even though every *real* recipient resolved fine. Only ever used as an internal
138
- * cache key - `ComposeRecipientInput.address` itself (what is actually sent as the recipient) is untouched.
139
- */
140
- function addressCacheKey(address: string): string {
141
- return address.trim().toLowerCase();
142
- }
143
-
144
- function HeaderButton({
145
- label,
146
- onClick,
147
- icon: Icon,
148
- disabled,
149
- shortcut,
150
- }: {
151
- label: string;
152
- onClick: () => void;
153
- icon: React.ComponentType<{ size?: number }>;
154
- disabled?: boolean;
155
- /** The keyboard shortcut that does the same, named in the tooltip and `aria-keyshortcuts`. */
156
- shortcut?: ShortcutDef;
157
- }) {
158
- const env = useKeyEnvironment();
159
- return (
160
- <button
161
- type="button"
162
- aria-label={label}
163
- title={shortcut ? withHint(label, shortcut, env) : label}
164
- aria-keyshortcuts={shortcut ? ariaKeyShortcuts(shortcut, env) : undefined}
165
- onClick={onClick}
166
- disabled={disabled}
167
- className="w-6 h-6 flex items-center justify-center rounded-sm text-white/80 hover:bg-white/15 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed"
168
- >
169
- <Icon size={14} />
170
- </button>
171
- );
172
- }
173
-
174
- /**
175
- * A floating, Gmail-style compose window — overlays whatever app is currently showing instead of
176
- * navigating to a dedicated page (see `ComposeContext.tsx`'s doc comment for why: a full-page compose
177
- * form meant losing your place in the inbox/calendar/contacts view behind it, and every navigation to
178
- * `/compose` re-ran this whole app's full mailbox/folder resolution waterfall from scratch). Owns its
179
- * own draft lifecycle end to end (unlike the old page, which read the Drafts folder from `MailShell`'s
180
- * context — this window can be opened from apps that never mount `MailShell` at all, e.g. Contacts'
181
- * "Email" action, so it resolves its own Drafts folder from just a `mailboxUid`).
182
- *
183
- * Below the `md` breakpoint, a non-minimized session instead renders as a full-screen sheet (there's no
184
- * room for a floating window, and the click-drag resize handles below become meaningless full-screen) —
185
- * see `ComposeContext.tsx`'s own doc comment for how that interacts with several sessions being open at
186
- * once.
187
- */
188
- export default function ComposeWindow({
189
- session,
190
- onClose,
191
- onToggleMinimize,
192
- userUid,
193
- trusted,
194
- autosaveDelayMs = DEFAULT_AUTOSAVE_DELAY_MS,
195
- cryptoRetryDelaysMs = DEFAULT_CRYPTO_RETRY_DELAYS_MS,
196
- }: ComposeWindowProps) {
197
- const { id, initialTo, initialCc, initialSubject, initialQuotedHtml, initialEncrypt, signatureContext, suppressSigning, minimized, quotePending, late, resume } = session;
198
- // What a reply worked out after this window opened (see `OpenComposeInput.pending`): better recipients, applied below
199
- // only to fields still exactly as they opened - so these, not `initialTo`/`initialCc`, are what "untouched" is measured against.
200
- const baselineTo = late?.to ?? initialTo;
201
- const baselineCc = late?.cc ?? initialCc;
202
- useEffect(() => {
203
- markComposePhase(id, "shell");
204
- markComposePhase(id, "chunk");
205
- }, []);
206
- // The sending ("From") mailbox. A reply/forward session names the original message's mailbox; a fresh
207
- // compose leaves it unset and defaults to the caller's own mailbox once `listMailboxes()` resolves.
208
- // Everything mailbox-scoped below (Drafts folder, draft, signatures, crypto context) keys off this.
209
- const [fromMailboxUid, setFromMailboxUid] = useState<string | undefined>(session.mailboxUid);
210
- const mailboxUid = fromMailboxUid;
211
- const [mailboxes, setMailboxes] = useState<Mailbox[]>([]);
212
- // Attachments and inline images upload onto the current draft's uid, which lives in one mailbox's
213
- // Drafts folder - so once anything has been uploaded the sender can no longer be switched.
214
- const [hasUploads, setHasUploads] = useState(!!resume && resume.attachments.length > 0);
215
- const isMobile = useIsMobile();
216
- const { requestUnlock } = useUnlockPrompt();
217
- const { openCompose } = useCompose();
218
- const keyEnv = useKeyEnvironment();
219
- // Bumped after a successful on-demand unlock to force a re-render - `getUnlockedKeys()` below is a
220
- // plain read from a module-level store, not React state, so nothing else would pick up the change.
221
- const [, setUnlockRefresh] = useState(0);
222
-
223
- const windowRef = useRef<HTMLDivElement>(null);
224
- const [draftsFolderUid, setDraftsFolderUid] = useState<string | undefined>();
225
- const [folderError, setFolderError] = useState<string | null>(null);
226
- // A window re-opened around a message that was already composed (a failed send's "Open draft") continues that server draft and starts with
227
- // every field as it was typed; its body is not seeded from a signature or a quote.
228
- const [draft, setDraft] = useState<Message | null>(resume?.draft ?? null);
229
- // Drafts replaced by a From switch, awaiting deletion until their replacement has actually been created.
230
- const supersededDraftsRef = useRef<Message[]>([]);
231
- const [draftError, setDraftError] = useState<string | null>(null);
232
- const [expanded, setExpanded] = useState(false);
233
- const [manualSize, setManualSize] = useState<Size | null>(null);
234
- const [to, setTo] = useState(resume?.to ?? initialTo ?? "");
235
- const [cc, setCc] = useState(resume?.cc ?? initialCc ?? "");
236
- const [bcc, setBcc] = useState(resume?.bcc ?? "");
237
- const [showCcBcc, setShowCcBcc] = useState(!!(resume ? resume.cc || resume.bcc : initialCc));
238
- const [subject, setSubject] = useState(resume?.subject ?? initialSubject ?? "");
239
- const [html, setHtml] = useState(resume?.html ?? "");
240
- const [contentReady, setContentReady] = useState(!!resume);
241
- const [attachments, setAttachments] = useState<Attachment[]>(resume?.attachments ?? []);
242
- const [attachError, setAttachError] = useState<string | null>(null);
243
- // A problem with the message as composed (no recipient, an attachment that can't be signed): shown here, and the window stays open. What
244
- // goes wrong after Send was accepted is a pop-up instead (see `sendJob.ts`).
245
- const [sendError, setSendError] = useState<string | null>(null);
246
- // Send was pressed while an attachment was still uploading: the window waits (and says so) rather than send without it.
247
- const [waitingForUploads, setWaitingForUploads] = useState(false);
248
- const [requestReceipt, setRequestReceipt] = useState(!!resume?.requestReceipt);
249
- const [schedulePickerOpen, setSchedulePickerOpen] = useState(false);
250
- const scheduleButtonRef = useRef<HTMLButtonElement>(null);
251
- const [mailbox, setMailbox] = useState<Mailbox | null>(null);
252
- const [encryptionPolicy, setEncryptionPolicy] = useState<EncryptionPolicy | null>(null);
253
- // Defaults off when replying to a detected mailing list (spec's own "Mailing lists" note under
254
- // Digital Signatures - a list that appends a footer after signing invalidates the signature) - see
255
- // `MessageDetailPane.tsx`'s handleReply()/handleReplyAll() for where this is computed. The user can
256
- // still turn it back on; this only changes the default.
257
- const [signEnabled, setSignEnabled] = useState(resume ? resume.signEnabled : !suppressSigning);
258
- // A reply to or forward of an encrypted message starts (and, after a From switch, restarts) with encryption
259
- // requested - see `OpenComposeInput.encrypt`.
260
- const [encryptRequested, setEncryptRequested] = useState(resume ? resume.encryptRequested : !!initialEncrypt);
261
- // Compose-time discovery (spec: "Discovery occurs ... when the user addresses a new message to a
262
- // recipient", never on receipt) - keyed by address so a recipient already looked up isn't re-fetched
263
- // just because the user re-focuses the field. Only ever grows via `checkRecipientDiscovery()` below;
264
- // never cleared, so switching focus between To/Cc/Bcc repeatedly doesn't re-trigger lookups.
265
- const [recipientStatuses, setRecipientStatuses] = useState<Record<string, RecipientEncryptionStatus>>({});
266
- // Addresses whose lookup is on the wire (so the blur handlers and the prefilled-recipient effect don't
267
- // look one up twice), and a counter bumped by a From switch so a lookup for the previous sender is dropped.
268
- const lookupsInFlightRef = useRef(new Set<string>());
269
- const discoveryGenerationRef = useRef(0);
270
- // A failed lookup stores no status: the recipient is simply "not known to be encryptable" (fail open - see `encryptionRequirement.ts`), and
271
- // the lookup is retried in the background with the same backoff as the mailbox/policy load, without a word to the user.
272
- const lookupFailuresRef = useRef(new Map<string, number>());
273
- const lookupRetryTimersRef = useRef(new Set<ReturnType<typeof setTimeout>>());
274
- const [lookupRetryToken, setLookupRetryToken] = useState(0);
275
- // A send refused *before it left* because signing/encryption was asked for (or the loaded policy applies it) but can't happen right now
276
- // (keys locked, Bcc recipients on an encrypted message, a recipient without a key) - never a silent downgrade to plaintext; the user
277
- // has to explicitly pick the override.
278
- const [securityBlock, setSecurityBlock] = useState<SendBlock | null>(null);
279
- // The schedule time of the send that got blocked (undefined for an immediate send), so the banners'
280
- // override buttons replay the same kind of send the user originally asked for.
281
- const [blockedScheduleIso, setBlockedScheduleIso] = useState<string | undefined>();
282
- // Which crypto toggles were ever shown during this compose session (per sending mailbox). Keys that
283
- // lock after that point must block the send rather than quietly dropping the signature/encryption.
284
- const offeredCryptoRef = useRef({ sign: false, encrypt: false });
285
-
286
- // Draft autosave / discard bookkeeping.
287
- const [seededHtml, setSeededHtml] = useState<string | undefined>();
288
- const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved" | "error">("idle");
289
- const [closePrompt, setClosePrompt] = useState<ClosePrompt | null>(null);
290
- /** A Close (saving) or Discard (deleting) is on the wire - the window closes once it succeeds. */
291
- const [closing, setClosing] = useState(false);
292
- const [discardError, setDiscardError] = useState<string | null>(null);
293
- /** Why the last save failed, cleared by the next successful one. */
294
- const saveErrorRef = useRef<string | null>(null);
295
- /** `<draftUid>:<content key>` of the last successful save. */
296
- const lastSavedRef = useRef<string | null>(null);
297
- /** An edit is waiting on the autosave debounce - flushed if the window unmounts first. */
298
- const pendingSaveRef = useRef(false);
299
- /** Send was pressed and is being validated/handed over: a second press (a double click, the shortcut held or repeated) does nothing. */
300
- const submittingRef = useRef(false);
301
- /** Attachment/inline-image uploads on the wire, and who is waiting for them to finish (Send pressed meanwhile). */
302
- const uploadsInFlightRef = useRef(0);
303
- const uploadWaitersRef = useRef<(() => void)[]>([]);
304
- /** The latest save request, if any - each save is chained after the one before it. Always settles (never
305
- * rejects), to the saved message, or `undefined` when that save failed. */
306
- const saveInFlightRef = useRef<Promise<Message | undefined>>(Promise.resolve(undefined));
307
- /** Set once the window has been sent/closed/discarded - nothing more gets autosaved after that. */
308
- const finishedRef = useRef(false);
309
-
310
- // A mailbox with no keys enrolled yet just means sign/encrypt stay unavailable for this compose session -
311
- // encryption is optional and gradual by design (see `KeyEnrollmentGate`'s own doc comment).
312
- // The mailbox and the encryption policy load in the background and *nothing waits for them*: until both have loaded, the message is treated as
313
- // not encrypted - its draft saves, Close and Send work, and no message about it is shown (see `encryptionRequirement.ts`). A failed load is
314
- // retried silently with backoff (`cryptoRetryDelaysMs`); if it later turns out the message must be encrypted, `encryptionDecided` (below) starts
315
- // to apply - see the transition rules there.
316
-
317
- useEffect(() => {
318
- let cancelled = false;
319
- listMailboxes({ limit: 100 })
320
- .then((result) => {
321
- if (cancelled) {
322
- return;
323
- }
324
- // Listed with the caller's own (primary) mailbox first, and defaulted to below.
325
- const ordered = orderMailboxes(result, userUid);
326
- setMailboxes(ordered);
327
- // Never default to a mailbox already known to be view-only (see the effect below for one
328
- // that turns out to be).
329
- const candidates = ordered.filter((mb) => peekMailboxWritability(mb, userUid, trusted) !== false);
330
- setFromMailboxUid((current) => current ?? primaryMailboxUid(candidates, userUid));
331
- })
332
- .catch((err) => {
333
- // Only fatal when there's no mailbox to fall back on - a session that already names one just
334
- // loses the From picker.
335
- if (!cancelled && !session.mailboxUid) {
336
- setFolderError(err instanceof ApiRequestError ? err.message : "Could not load your mailboxes.");
337
- }
338
- });
339
- return () => {
340
- cancelled = true;
341
- };
342
- }, []);
343
-
344
- useEffect(() => {
345
- if (!mailboxUid) {
346
- return;
347
- }
348
- let cancelled = false;
349
- let timer: ReturnType<typeof setTimeout> | undefined;
350
- // A retry only fetches what's still missing.
351
- let mailboxLoaded = mailbox?.uid === mailboxUid;
352
- let policyLoaded = !!encryptionPolicy;
353
- let retries = 0;
354
- async function load() {
355
- await Promise.all([
356
- mailboxLoaded ||
357
- getMailbox(mailboxUid!).then(
358
- (result) => {
359
- mailboxLoaded = true;
360
- if (!cancelled) {
361
- setMailbox(result);
362
- }
363
- },
364
- () => undefined,
365
- ),
366
- policyLoaded ||
367
- getEncryptionPolicy().then(
368
- (result) => {
369
- policyLoaded = true;
370
- if (!cancelled) {
371
- setEncryptionPolicy(result);
372
- }
373
- },
374
- () => undefined,
375
- ),
376
- ]);
377
- if (!cancelled && (!mailboxLoaded || !policyLoaded) && retries < cryptoRetryDelaysMs.length) {
378
- timer = setTimeout(() => void load(), cryptoRetryDelaysMs[retries++]);
379
- }
380
- }
381
- void load();
382
- return () => {
383
- cancelled = true;
384
- clearTimeout(timer);
385
- };
386
- }, [mailboxUid]);
387
-
388
- useEffect(() => {
389
- if (!mailboxUid) {
390
- return;
391
- }
392
- // Cancellable so a slow response for a mailbox the user has since switched away from can't point
393
- // the new draft at the wrong mailbox's Drafts folder.
394
- let cancelled = false;
395
- listFolders(mailboxUid)
396
- .then((folders) => {
397
- if (!cancelled) {
398
- setDraftsFolderUid(folders.find((f) => f.type === "drafts")?.uid);
399
- }
400
- })
401
- .catch((err) => {
402
- if (!cancelled) {
403
- setFolderError(err instanceof ApiRequestError ? err.message : "Could not load your Drafts folder.");
404
- }
405
- });
406
- return () => {
407
- cancelled = true;
408
- };
409
- }, [mailboxUid]);
410
-
411
- /**
412
- * Runs discovery for whichever of `addresses` haven't already been looked up this compose session,
413
- * caching the result so the small per-recipient indicator below the recipient fields can update
414
- * without waiting for Send. Called from the To/Cc/Bcc fields' own `onBlur` - not on every keystroke,
415
- * and not the lookup the background send (`sendJob.ts`) performs again at send time (deliberately: this is a
416
- * best-effort UI hint, not something a stale value here should be trusted to skip at send time).
417
- * A mailbox/policy fetch that hasn't resolved yet just leaves that address with no indicator - the effect
418
- * below runs it again for every current recipient once both have loaded. A failed lookup leaves it without
419
- * a status too, and is retried silently after `cryptoRetryDelaysMs` (then only on blur).
420
- *
421
- * The statuses also drive `encryptionRequirement.ts`: only when every recipient has one, and the loaded policy
422
- * auto-encrypts for all of them, does the message turn into one that is never saved as a plaintext draft.
423
- */
424
- function checkRecipientDiscovery(addresses: ComposeRecipientInput[]) {
425
- if (!mailbox || !encryptionPolicy) {
426
- return;
427
- }
428
- const ownPrefersMutual = mailbox.encryptPreference?.preferEncrypt === "mutual";
429
- const generation = discoveryGenerationRef.current;
430
- const inFlight = lookupsInFlightRef.current;
431
- const unchecked = addresses.filter((r) => !(addressCacheKey(r.address) in recipientStatuses) && !inFlight.has(addressCacheKey(r.address)));
432
- for (const recipient of unchecked) {
433
- const key = addressCacheKey(recipient.address);
434
- inFlight.add(key);
435
- void lookupKeys(mailbox.uid, recipient.address)
436
- .then(
437
- (lookup) => ({ lookup }),
438
- () => null,
439
- )
440
- .then((result) => {
441
- inFlight.delete(key);
442
- if (generation !== discoveryGenerationRef.current) {
443
- return;
444
- }
445
- if (!result) {
446
- noteLookupFailed(key);
447
- return;
448
- }
449
- lookupFailuresRef.current.delete(key);
450
- const status = resolveRecipientEncryption(mailbox.primarySmtpAddress, ownPrefersMutual, encryptionPolicy, recipient.address, result.lookup);
451
- setRecipientStatuses((prev) => ({ ...prev, [key]: status }));
452
- });
453
- }
454
- }
455
-
456
- /** Schedules the next automatic, silent retry of a failed lookup (until the backoff has run out; a later blur tries again). */
457
- function noteLookupFailed(address: string) {
458
- const failures = (lookupFailuresRef.current.get(address) ?? 0) + 1;
459
- lookupFailuresRef.current.set(address, failures);
460
- if (failures > cryptoRetryDelaysMs.length) {
461
- return;
462
- }
463
- const timer = setTimeout(() => {
464
- lookupRetryTimersRef.current.delete(timer);
465
- setLookupRetryToken((n) => n + 1);
466
- }, cryptoRetryDelaysMs[failures - 1]);
467
- lookupRetryTimersRef.current.add(timer);
468
- }
469
-
470
- useEffect(
471
- () => () => {
472
- for (const timer of lookupRetryTimersRef.current) {
473
- clearTimeout(timer);
474
- }
475
- },
476
- [],
477
- );
478
-
479
- // Prefilled recipients (a reply's To/Cc) are never blurred, and a blur before the mailbox/policy loaded
480
- // was ignored - look every current recipient up as soon as both are available (and again on a lookup retry).
481
- useEffect(() => {
482
- checkRecipientDiscovery([...parseAddresses(to), ...parseAddresses(cc), ...parseAddresses(bcc)]);
483
- }, [mailbox, encryptionPolicy, lookupRetryToken]);
484
-
485
- // Resolves the mailbox's default signature (if any) for `signatureContext` and seeds `html` with it (not for a window re-opened around a composed message)
486
- // plus any quoted original message (laid out by `buildComposeBodyHtml()`: an empty first paragraph for the
487
- // caret, then the signature, then the quote), before `RichTextEditor` ever mounts (gated by `contentReady`
488
- // below) — `RichTextEditor`'s own doc comment is explicit that `value` only seeds its *initial*
489
- // content and never re-syncs from a later prop change, so this has to resolve before that first
490
- // mount, not after. A signature-list failure is best-effort, same as every other supplementary,
491
- // non-blocking fetch in this codebase (e.g. `ConversationList`'s own child-message fetch) — no
492
- // signature is a completely legitimate outcome, so this falls back to just the quoted content
493
- // (if any) rather than surfacing an error over what's a cosmetic nicety.
494
- //
495
- // A reply or forward opens before its quoted original has been fetched (`quotePending`, see
496
- // `OpenComposeInput.pending`). The body is seeded as soon as the signature is here, without the quote, so the editor is usable
497
- // at once however slow the original is to come; the quote is added at the end of the editor's document when it arrives
498
- // (`appendHtml` below) - the same place, under the signature, that a body seeded with it would have had it.
499
- const [defaultSignature, setDefaultSignature] = useState<{ html?: string } | undefined>();
500
- useEffect(() => {
501
- // Fetched once, for whichever mailbox is the sender when compose opens - switching From later must not
502
- // overwrite what the user has already written (the editor itself never re-syncs).
503
- if (!mailboxUid || contentReady || defaultSignature) {
504
- return;
505
- }
506
- listMailSignatures(mailboxUid)
507
- .then((signatures) => {
508
- const signature = signatures.find((s) =>
509
- signatureContext === "new" ? s.isDefaultForNewMessages : s.isDefaultForReplyForward,
510
- );
511
- setDefaultSignature({ html: signature?.contentHtml });
512
- })
513
- .catch(() => setDefaultSignature({}));
514
- }, [mailboxUid, signatureContext]);
515
- const [seededWithoutQuote, setSeededWithoutQuote] = useState(false);
516
- useEffect(() => {
517
- if (contentReady || !defaultSignature) {
518
- return;
519
- }
520
- const seeded = buildComposeBodyHtml(defaultSignature.html, quotePending ? undefined : initialQuotedHtml);
521
- setHtml(seeded);
522
- setSeededHtml(seeded);
523
- setSeededWithoutQuote(!!quotePending);
524
- setContentReady(true);
525
- markComposePhase(id, "body");
526
- }, [defaultSignature, quotePending, initialQuotedHtml]);
527
- /** What the editor adds to the end of its document once the quote a reply was opened without has arrived. */
528
- const lateQuoteHtml =
529
- seededWithoutQuote && !quotePending && initialQuotedHtml && defaultSignature
530
- ? buildComposeBodyHtml(defaultSignature.html, initialQuotedHtml).slice(buildComposeBodyHtml(defaultSignature.html) === "" ? "<p></p>".length : buildComposeBodyHtml(defaultSignature.html).length)
531
- : undefined;
532
-
533
- useEffect(() => {
534
- if (!mailboxUid || !draftsFolderUid || draft) {
535
- return;
536
- }
537
- let cancelled = false;
538
- // `session.threading` is what makes a reply a reply: the server writes it into the relayed MIME's
539
- // `In-Reply-To`/`References` and groups the message into the thread being answered. Recorded on
540
- // every draft this window creates, including the replacement one a From switch makes - the thread
541
- // doesn't change because the sending mailbox did.
542
- createDraft(mailboxUid, draftsFolderUid, session.threading)
543
- .then((created) => {
544
- if (cancelled) {
545
- // The sender changed while this was in flight - discard the now-orphaned draft.
546
- void deleteMessage(created.uid, created.version).catch(() => undefined);
547
- return;
548
- }
549
- setDraft(created);
550
- markComposePhase(id, "draft");
551
- // Only now that the replacement exists is it safe to discard the draft(s) a From switch
552
- // superseded - if creating this one had failed, the earlier draft is still there.
553
- for (const superseded of supersededDraftsRef.current.splice(0)) {
554
- void deleteSupersededDraft(superseded);
555
- }
556
- })
557
- .catch((err) => {
558
- if (!cancelled) {
559
- setDraftError(err instanceof ApiRequestError ? err.message : "Could not start a new draft.");
560
- }
561
- });
562
- return () => {
563
- cancelled = true;
564
- };
565
- }, [mailboxUid, draftsFolderUid, draft, session.threading]);
566
-
567
- // Drafts a From switch superseded are otherwise only deleted once their replacement exists - closing the
568
- // window (or sending, which closes it) first would orphan them.
569
- useEffect(
570
- () => () => {
571
- for (const superseded of supersededDraftsRef.current.splice(0)) {
572
- void deleteSupersededDraft(superseded);
573
- }
574
- },
575
- [],
576
- );
577
-
578
- /**
579
- * Deletes a draft a From switch replaced. An autosave of it may still be on the wire - it bumps the
580
- * draft's version (see `saveDraftNow()`, which keeps `superseded.version` current while it's queued), so
581
- * the delete waits for it and uses its version; a delete that still fails (e.g. another save of it landed
582
- * meanwhile) is retried once with the version the server currently holds - unless it's no longer a draft
583
- * (another window sent or scheduled it), which is left alone.
584
- * Best-effort, never rejects.
585
- */
586
- async function deleteSupersededDraft(superseded: Message): Promise<void> {
587
- const saved = await saveInFlightRef.current;
588
- // Once it's out of `supersededDraftsRef` a landing save can't update `superseded.version` any more.
589
- const version = saved?.uid === superseded.uid ? saved.version : superseded.version;
590
- try {
591
- await deleteMessage(superseded.uid, version);
592
- } catch {
593
- try {
594
- const fresh = await getMessage(superseded.uid);
595
- if (isStillDraft(fresh, superseded.folderUid)) {
596
- await deleteMessage(fresh.uid, fresh.version);
597
- }
598
- } catch {
599
- // Already gone, or the server is unreachable - nothing more to do from here.
600
- }
601
- }
602
- }
603
-
604
- // The From picker lists every mailbox straight away and drops view-only ones as each check answers - only
605
- // mailboxes the caller can create a draft in are worth offering.
606
- const writability = useMailboxWritability(mailboxes, userUid, trusted);
607
- const fromOptions = mailboxes.filter((mb) => mb.uid === mailboxUid || writability[mb.uid] !== false);
608
-
609
- // The sender turned out to be view-only (e.g. a reply to a message in a mailbox shared read-only, or a
610
- // first-listed shared mailbox): switch to one the caller can actually send from, preferring their own.
611
- const fromIsViewOnly = !!mailboxUid && writability[mailboxUid] === false;
612
- useEffect(() => {
613
- if (!fromIsViewOnly || hasUploads) {
614
- return;
615
- }
616
- const ordered = orderMailboxes(mailboxes, userUid);
617
- const alternative = ordered.find((mb) => writability[mb.uid] === true) ?? ordered.find((mb) => writability[mb.uid] === undefined);
618
- if (alternative) {
619
- handleFromChange(alternative.uid);
620
- }
621
- }, [fromIsViewOnly, writability]);
622
-
623
- /** Switches the sending mailbox: supersedes the current (unsent, upload-free) draft and resets the
624
- * per-mailbox state, so the effects above start a fresh draft and crypto context in the new mailbox -
625
- * the old draft is deleted only once the new one has been created. Recipients, subject, and body are
626
- * kept. */
627
- function handleFromChange(nextMailboxUid: string) {
628
- if (nextMailboxUid === mailboxUid || hasUploads) {
629
- return;
630
- }
631
- if (draft) {
632
- supersededDraftsRef.current.push(draft);
633
- }
634
- setDraft(null);
635
- setDraftsFolderUid(undefined);
636
- setDraftError(null);
637
- setFolderError(null);
638
- setMailbox(null);
639
- setRecipientStatuses({});
640
- discoveryGenerationRef.current += 1;
641
- lookupsInFlightRef.current = new Set();
642
- lookupFailuresRef.current = new Map();
643
- setEncryptRequested(!!initialEncrypt);
644
- setSecurityBlock(null);
645
- offeredCryptoRef.current = { sign: false, encrypt: false };
646
- setFromMailboxUid(nextMailboxUid);
647
- }
648
-
649
- /**
650
- * Click-and-drag resize, from the window's own top/left edges (and the top-left corner, for both
651
- * at once) — the window is anchored bottom-right (see `ComposeContext.tsx`'s stack), so growing it
652
- * always means extending up and/or left, never down/right. `onMove`/`onUp` are fresh closures
653
- * created per drag gesture (captured over this gesture's own start position/size) rather than
654
- * stable component-level functions, specifically so `removeEventListener` in `onUp` always removes
655
- * the exact listener `onMove`/`onUp` themselves just added — a version defined once per render and
656
- * reused across gestures would need extra ref-juggling to avoid removing a stale (already-replaced)
657
- * listener instead of the current one.
658
- */
659
- function handleResizeStart(edge: ResizeEdge) {
660
- return (e: React.PointerEvent) => {
661
- e.preventDefault();
662
- const rect = windowRef.current!.getBoundingClientRect();
663
- const startX = e.clientX;
664
- const startY = e.clientY;
665
- const startWidth = rect.width;
666
- const startHeight = rect.height;
667
-
668
- function onMove(ev: PointerEvent) {
669
- const maxWidth = window.innerWidth - VIEWPORT_MARGIN;
670
- const maxHeight = window.innerHeight - VIEWPORT_MARGIN;
671
- const width = edge === "top" ? startWidth : Math.min(Math.max(startWidth - (ev.clientX - startX), MIN_WIDTH), maxWidth);
672
- const height = edge === "left" ? startHeight : Math.min(Math.max(startHeight - (ev.clientY - startY), MIN_HEIGHT), maxHeight);
673
- setManualSize({ width, height });
674
- }
675
- function onUp() {
676
- window.removeEventListener("pointermove", onMove);
677
- window.removeEventListener("pointerup", onUp);
678
- }
679
- window.addEventListener("pointermove", onMove);
680
- window.addEventListener("pointerup", onUp);
681
- };
682
- }
683
-
684
- function toggleExpanded() {
685
- setExpanded((v) => !v);
686
- setManualSize(null);
687
- }
688
-
689
- /** Uploads `file` as an attachment on the current draft, resolving to a URL the editor can preview
690
- * it at immediately — see `BaseMailComposeRoute.rewriteInlineImageSources()`'s doc comment for how
691
- * that URL gets swapped for the message's real inline `cid:` reference at send time. Resolves to
692
- * `null` (surfacing `attachError` itself, reusing the same state "Attach files" already has) rather
693
- * than throwing: unlike "Attach files" (`disabled={!draft}`), "Insert image" in the formatting
694
- * toolbar is only gated on the *editor* being mounted, not on the draft existing yet — those two
695
- * things load in parallel, so a real (if narrow) window exists where the button is clickable before
696
- * `draft` resolves, and this needs to fail gracefully rather than crash on a null draft.
697
- */
698
- async function handleUploadImage(file: File): Promise<string | null> {
699
- if (!draft) {
700
- setAttachError("Please wait for the draft to finish loading before inserting an image.");
701
- return null;
702
- }
703
- uploadStarted();
704
- try {
705
- const attachment = await uploadAttachment(draft.uid, file);
706
- setHasUploads(true);
707
- void refreshDraftVersion(draft.uid);
708
- return attachmentContentUrl(attachment.uid);
709
- } catch (err) {
710
- setAttachError(err instanceof ApiRequestError ? err.message : "Could not upload image.");
711
- return null;
712
- } finally {
713
- uploadFinished();
714
- }
715
- }
716
-
717
- /** Send waits for every upload started before it: see `submit()`. */
718
- function uploadStarted() {
719
- uploadsInFlightRef.current += 1;
720
- }
721
- function uploadFinished() {
722
- uploadsInFlightRef.current -= 1;
723
- if (uploadsInFlightRef.current === 0) {
724
- for (const resolve of uploadWaitersRef.current.splice(0)) {
725
- resolve();
726
- }
727
- }
728
- }
729
-
730
- /** Uploading an attachment bumps the draft's version server-side (it records `hasAttachments`), so a later
731
- * Discard would otherwise send a stale `?version=`. Best-effort: Discard also retries with the server's
732
- * current version. */
733
- async function refreshDraftVersion(uid: string) {
734
- try {
735
- const fresh = await getMessage(uid);
736
- setDraft((prev) => (prev?.uid === fresh.uid && fresh.version > prev.version ? { ...prev, version: fresh.version } : prev));
737
- } catch {
738
- // Discard's own retry covers a version this couldn't refresh.
739
- }
740
- }
741
-
742
- // The "Attach files" input is itself `disabled` until `draft` resolves (see its `disabled={!draft}`
743
- // below), so this can only ever fire once `draft` is set — no defensive null check needed, matching
744
- // this codebase's established pattern for the same class of "always non-null by the time it's
745
- // called" value (e.g. `ComposeToolbar.run()`). No separate empty-`files` guard either: the loop
746
- // below is already a no-op when there's nothing to iterate.
747
- async function handleFilesSelected(e: ChangeEvent<HTMLInputElement>) {
748
- const files = Array.from(e.target.files ?? []);
749
- e.target.value = "";
750
- setAttachError(null);
751
- uploadStarted();
752
- try {
753
- for (const file of files) {
754
- try {
755
- const attachment = await uploadAttachment(draft!.uid, file);
756
- setHasUploads(true);
757
- setAttachments((prev) => [...prev, attachment]);
758
- void refreshDraftVersion(draft!.uid);
759
- } catch (err) {
760
- setAttachError(err instanceof ApiRequestError ? err.message : "Could not upload attachment.");
761
- }
762
- }
763
- } finally {
764
- uploadFinished();
765
- }
766
- }
767
-
768
- /**
769
- * Send (or, given `scheduledSendTimeIso`, Send later) - and get out of the way. The window is the place the message is *written*; nothing
770
- * about getting it to the server is waited for here.
771
- *
772
- * 1. **Validate synchronously**, from what the window already knows (no request): a recipient is required; and if the message is one
773
- * that must be signed or encrypted and can't be right now (keys locked, Bcc on an encrypted message, a recipient with no key, an
774
- * attachment that can't be signed) that is shown right here and the window stays open - the sender fixes it or picks the override.
775
- * An attachment still uploading is waited for, inline (Send says so), never left behind.
776
- * 2. **Close immediately** (`onClose()`): `startSend()` (see `sendJob.ts`) takes over with a snapshot of the message. From here the only
777
- * feedback is the Outbox indicator; a failure at any stage is a sticky pop-up with the reason and Retry / Open draft.
778
- *
779
- * Pressed twice (a double click, the shortcut repeated) it sends once: the first press sets `submittingRef` before any `await`, and
780
- * `startSend()` itself refuses a draft that is already being sent. `forcePlaintext` is the override buttons' choice.
781
- */
782
- async function submit(forcePlaintext: boolean, scheduledSendTimeIso?: string) {
783
- if (submittingRef.current || finishedRef.current) {
784
- return;
785
- }
786
- if (parseAddresses(latestRef.current.to).length === 0) {
787
- setSendError("At least one recipient is required.");
788
- return;
789
- }
790
- submittingRef.current = true;
791
- setSendError(null);
792
- setSecurityBlock(null);
793
- try {
794
- if (uploadsInFlightRef.current > 0) {
795
- setWaitingForUploads(true);
796
- await new Promise<void>((resolve) => uploadWaitersRef.current.push(resolve));
797
- // The editor puts an image it has just uploaded into the message a moment after the upload resolves: let the window catch up.
798
- await new Promise((resolve) => setTimeout(resolve, 0));
799
- setWaitingForUploads(false);
800
- }
801
- const current = latestRef.current;
802
- const request: SendRequest = {
803
- draft: current.draft!,
804
- mailboxUid: current.mailboxUid!,
805
- mailbox: current.mailbox ?? undefined,
806
- policy: current.encryptionPolicy ?? undefined,
807
- toText: current.to,
808
- ccText: current.cc,
809
- bccText: current.bcc,
810
- to: parseAddresses(current.to),
811
- cc: parseAddresses(current.cc),
812
- bcc: parseAddresses(current.bcc),
813
- subject: current.subject,
814
- html: current.html,
815
- attachments: current.attachments,
816
- requestReceipt: current.requestReceipt,
817
- scheduledSendTime: scheduledSendTimeIso,
818
- signEnabled: current.signEnabled,
819
- offeredSign: offeredCryptoRef.current.sign,
820
- offeredEncrypt: offeredCryptoRef.current.encrypt,
821
- encryptRequested: current.encryptRequested,
822
- forcePlaintext,
823
- saved: saveInFlightRef.current,
824
- threading: session.threading,
825
- };
826
- if (request.to.length === 0) {
827
- setSendError("At least one recipient is required.");
828
- return;
829
- }
830
- const early = decideSend(sendDecisionInput(request, request.mailbox, request.policy, current.statuses, false));
831
- if (early.action === "rejected") {
832
- setSendError(early.message);
833
- return;
834
- }
835
- if (early.action === "blocked") {
836
- setBlockedScheduleIso(scheduledSendTimeIso);
837
- setSecurityBlock(early.block);
838
- if (early.block.keysLocked && (hasEnrolledSigningKey || hasEnrolledEncryptionKey)) {
839
- void handleUnlockForCrypto();
840
- }
841
- return;
842
- }
843
- pendingSaveRef.current = false;
844
- finishedRef.current = true;
845
- if (!startSend(request)) {
846
- finishedRef.current = false;
847
- setSendError("This message is already being sent.");
848
- return;
849
- }
850
- onClose();
851
- } finally {
852
- submittingRef.current = false;
853
- setWaitingForUploads(false);
854
- }
855
- }
856
-
857
- function handleScheduleSend(scheduledSendTimeIso: string) {
858
- setSchedulePickerOpen(false);
859
- void submit(false, scheduledSendTimeIso);
860
- }
861
-
862
- async function handleUnlockForCrypto() {
863
- try {
864
- // Only reachable when hasEnrolledSigningKey/hasEnrolledEncryptionKey found a real enrolled key
865
- // in mailbox.keys (the unlock button below, or a blocked send()), so neither is empty/undefined here.
866
- await requestUnlock(mailbox!.uid, mailbox!.keys!);
867
- setUnlockRefresh((n) => n + 1);
868
- } catch {
869
- // User dismissed the unlock dialog - nothing to do, the toggles below simply stay hidden.
870
- }
871
- }
872
-
873
- /**
874
- * Saves the window's current recipients/subject/body onto its server draft via `assembleDraft()` (the
875
- * same plaintext assembly a normal send uses). Chained after any save already on the wire - two
876
- * overlapping assemblies of the same draft race on its version and the later one is rejected - and reads
877
- * `latestRef` only once it actually runs, so it saves what was last typed (skipping the request when the
878
- * save before it already stored exactly that). Whether a save may happen at all is re-checked at that same
879
- * moment: while it waited, the message may have become one that must not be stored as plaintext (Encrypt
880
- * turned on, a recipient that auto-encrypts), or the window may have been sent or finished - then it
881
- * resolves `{ skipped: true }` without a request (`message` then being the previous save's result). Never
882
- * rejects; `message` is `undefined` when the save failed.
883
- */
884
- function saveDraftNow(): Promise<{ message?: Message; skipped?: boolean }> {
885
- const target = latestRef.current.draft!;
886
- const previous = saveInFlightRef.current;
887
- pendingSaveRef.current = false;
888
- setSaveStatus("saving");
889
- const outcome = (async (): Promise<{ message?: Message; skipped?: boolean }> => {
890
- const before = await previous;
891
- const current = latestRef.current;
892
- if (current.autosaveSuppressed || finishedRef.current) {
893
- setSaveStatus("idle");
894
- // Still the newest copy the server holds, for the version a later delete needs.
895
- return { skipped: true, message: before };
896
- }
897
- const savedKey = `${target.uid}:${current.contentKey}`;
898
- if (before?.uid === target.uid && lastSavedRef.current === savedKey) {
899
- setSaveStatus("saved");
900
- return { message: before };
901
- }
902
- try {
903
- const saved = await assembleDraft(target.uid, {
904
- to: parseAddresses(current.to),
905
- cc: parseAddresses(current.cc),
906
- bcc: parseAddresses(current.bcc),
907
- subject: current.subject,
908
- html: current.html,
909
- });
910
- lastSavedRef.current = savedKey;
911
- saveErrorRef.current = null;
912
- // A From switch may have replaced the draft while this was in flight - never resurrect it,
913
- // but do keep its superseded copy's version current so its pending delete still matches.
914
- setDraft((prev) => (prev?.uid === saved.uid ? saved : prev));
915
- const superseded = supersededDraftsRef.current.find((d) => d.uid === saved.uid);
916
- if (superseded) {
917
- superseded.version = saved.version;
918
- }
919
- setSaveStatus("saved");
920
- return { message: saved };
921
- } catch (err) {
922
- saveErrorRef.current = err instanceof ApiRequestError ? err.message : "the server couldn't be reached";
923
- setSaveStatus("error");
924
- return {};
925
- }
926
- })();
927
- saveInFlightRef.current = outcome.then((result) => result.message);
928
- return outcome;
929
- }
930
-
931
- /** Keeps the window open after its content couldn't be saved, offering Discard or Keep editing. */
932
- function showSaveFailedPrompt() {
933
- setClosePrompt({
934
- title: "Couldn't save this draft",
935
- message: `It couldn't be saved (${saveErrorRef.current!.replace(/\.$/, "")}). Keep editing and try again, or discard it.`,
936
- });
937
- }
938
-
939
- /**
940
- * Deletes `current` (this window's server draft) once any save already on the wire has landed, so the delete
941
- * carries the draft's current version. A delete rejected for a stale version (404/409: e.g. an attachment
942
- * upload bumped it) is retried once with the version the server holds - and a draft the server no longer has
943
- * counts as deleted. The retry only happens while the server copy is still an unsent draft in the same folder.
944
- * Rejects when the draft couldn't be deleted.
945
- */
946
- async function deleteDraft(current: Message): Promise<void> {
947
- const saved = await saveInFlightRef.current;
948
- const version = Math.max(current.version, saved?.uid === current.uid ? saved.version : 0);
949
- try {
950
- await deleteMessage(current.uid, version);
951
- } catch (err) {
952
- if (!(err instanceof ApiRequestError) || (err.status !== 404 && err.status !== 409)) {
953
- throw err;
954
- }
955
- const fresh = await getMessage(current.uid).catch((getErr: unknown) => {
956
- if (getErr instanceof ApiRequestError && getErr.status === 404) {
957
- return null;
958
- }
959
- throw getErr;
960
- });
961
- if (!fresh) {
962
- return;
963
- }
964
- // The version changed because another window sent or scheduled it - that message isn't ours to delete.
965
- if (!isStillDraft(fresh, current.folderUid)) {
966
- throw new ApiRequestError(NO_LONGER_A_DRAFT_MESSAGE, 409);
967
- }
968
- await deleteMessage(fresh.uid, fresh.version);
969
- }
970
- }
971
-
972
- /**
973
- * Discards the window's draft and closes it. With nothing the user would lose (a blank draft) it closes
974
- * straight away and deletes the draft in the background; otherwise it closes only once the draft is
975
- * deleted, and a delete that fails keeps the window open with the error.
976
- */
977
- async function discardNow() {
978
- finishedRef.current = true;
979
- pendingSaveRef.current = false;
980
- setClosePrompt(null);
981
- setDiscardError(null);
982
- const current = draft;
983
- if (!current || !hasUserContent) {
984
- if (current) {
985
- void deleteDraft(current).catch(() => undefined);
986
- }
987
- onClose();
988
- return;
989
- }
990
- setClosing(true);
991
- try {
992
- await deleteDraft(current);
993
- } catch (err) {
994
- finishedRef.current = false;
995
- setClosing(false);
996
- setDiscardError(`Couldn't discard this draft: ${err instanceof ApiRequestError ? err.message : "the server couldn't be reached."}`);
997
- return;
998
- }
999
- onClose();
1000
- }
1001
-
1002
- /** "Discard draft": confirms first whenever there's anything the user would lose. */
1003
- function handleDiscard() {
1004
- if (hasUserContent) {
1005
- setClosePrompt({ title: DISCARD_TITLE, message: "This permanently deletes this draft and everything you've written in it." });
1006
- } else {
1007
- void discardNow();
1008
- }
1009
- }
1010
-
1011
- /** "Close": keeps the draft (saving any unsaved edits first, and closing only once that save succeeded) -
1012
- * unless there's nothing in it worth keeping, or it can't be saved because it's really headed for encryption
1013
- * (asked for, or applied by the loaded policy): that needs the same confirmation as a discard. Whatever is
1014
- * *unknown* (settings loading or failed, a lookup pending) is not a reason to hold the window: it is saved like any
1015
- * other message. A failed save keeps the window open with Discard / Keep editing. */
1016
- async function handleClose() {
1017
- if (!hasUserContent) {
1018
- void discardNow();
1019
- return;
1020
- }
1021
- if (encryptionDecided) {
1022
- setClosePrompt({ title: DISCARD_TITLE, message: ENCRYPTED_CLOSE_MESSAGE });
1023
- return;
1024
- }
1025
- if (!draft || !contentReady) {
1026
- saveErrorRef.current = draftError ?? "the draft hasn't been created yet";
1027
- showSaveFailedPrompt();
1028
- return;
1029
- }
1030
- if (lastSavedRef.current !== `${draft.uid}:${contentKey}`) {
1031
- setClosing(true);
1032
- const outcome = await saveDraftNow();
1033
- setClosing(false);
1034
- if (outcome.skipped) {
1035
- // It became a message that mustn't be saved as plaintext while waiting on an earlier save.
1036
- setClosePrompt({ title: DISCARD_TITLE, message: ENCRYPTED_CLOSE_MESSAGE });
1037
- return;
1038
- }
1039
- if (!outcome.message) {
1040
- showSaveFailedPrompt();
1041
- return;
1042
- }
1043
- }
1044
- finishedRef.current = true;
1045
- onClose();
1046
- }
1047
-
1048
- // A plain read from keySession.ts's module-level session store, not React state - see that module's
1049
- // own doc comment. Cheap enough to read fresh on every render rather than caching in state.
1050
- const unlockedKeys = mailboxUid ? getUnlockedKeys(mailboxUid) : undefined;
1051
- const hasEnrolledSigningKey = !!findActivePublicKey(mailbox?.keys ?? [], "sign");
1052
- const hasEnrolledEncryptionKey = !!findActivePublicKey(mailbox?.keys ?? [], "encrypt");
1053
- // This mailbox has a real signing/encryption key on file, but this session hasn't unlocked it yet -
1054
- // the sign/encrypt toggles below stay hidden until it has, so this is the only way to reach them
1055
- // without first stumbling into Mail generally (which no longer force-prompts on its own - see
1056
- // `MailShell`'s `blocking={false}`). `getUnlockedKeys()` is re-read as a plain module value above, so
1057
- // bumping `unlockRefresh` (after a successful unlock, or on any key-session event for this mailbox -
1058
- // see the `subscribeKeySession()` effect) is what makes this line (and the toggles it gates) reflect
1059
- // it on the next render.
1060
- const needsUnlockForCrypto = (hasEnrolledSigningKey || hasEnrolledEncryptionKey) && !unlockedKeys;
1061
-
1062
- // Keys locking (idle timeout, logout elsewhere, ...) or unlocking from another window must update the
1063
- // toggles/unlock affordance right away, not on whatever unrelated render happens next.
1064
- useEffect(() => subscribeKeySession((event) => {
1065
- if (event.mailboxUid === mailboxUid) {
1066
- setUnlockRefresh((n) => n + 1);
1067
- }
1068
- }), [mailboxUid]);
1069
-
1070
- useEffect(() => {
1071
- offeredCryptoRef.current = {
1072
- sign: offeredCryptoRef.current.sign || !!unlockedKeys?.signingPrivateKey,
1073
- encrypt: offeredCryptoRef.current.encrypt || !!unlockedKeys?.encryptionPrivateKey,
1074
- };
1075
- });
1076
-
1077
- // Autosave. "User content" is anything beyond what compose opened with (prefilled recipients/subject,
1078
- // seeded signature/quote) - an untouched window has nothing worth saving or confirming a discard of.
1079
- const contentKey = JSON.stringify([to, cc, bcc, subject, html]);
1080
- const baselineKey = JSON.stringify([baselineTo ?? "", baselineCc ?? "", "", initialSubject ?? "", seededHtml ?? ""]);
1081
- const hasUserContent = contentKey !== baselineKey || hasUploads;
1082
- // Whether this message is *really* headed for encryption - `encryptionRequirement.ts` decides, and it fails open: the message is plain (its
1083
- // draft saves, Close and Send work, nothing is shown) unless the user asked for encryption or the policy was loaded and applies it to every
1084
- // recipient (whose keys were all looked up). What has not loaded, or failed to, is not held against the message.
1085
- //
1086
- // Transitions, when a later load turns a plain message into an encrypted one (the policy arrives, a slow lookup answers, a recipient is
1087
- // added): (1) autosave stops at once (`autosaveSuppressed`); (2) a plaintext copy this window already saved is *replaced by an empty draft*
1088
- // (`scrubSavedDraft()` below) so the plaintext doesn't sit on the server; (3) Close asks first ("Encrypted messages aren't saved as drafts");
1089
- // (4) Send encrypts (or is refused, with the override, when it can't) - never silently plaintext. And back: when it stops being encrypted
1090
- // (a recipient removed) autosave simply resumes.
1091
- const currentAddresses = [...parseAddresses(to), ...parseAddresses(cc), ...parseAddresses(bcc)].map((r) => r.address);
1092
- const currentStatuses = currentAddresses.map((address) => recipientStatuses[addressCacheKey(address)]);
1093
- const hasEncryptionKey = !!unlockedKeys?.encryptionPrivateKey || hasEnrolledEncryptionKey || offeredCryptoRef.current.encrypt;
1094
- const requirement = evaluateEncryptionRequirement({
1095
- encryptRequested,
1096
- policy: encryptionPolicy ?? undefined,
1097
- mailboxLoaded: !!mailbox,
1098
- hasEncryptionKey,
1099
- recipients: currentStatuses,
1100
- });
1101
- const encryptionDecided = requirement.required;
1102
- const autosaveSuppressed = encryptionDecided;
1103
- const latestRef = useRef({
1104
- draft, mailboxUid, mailbox, encryptionPolicy, to, cc, bcc, subject, html, attachments, requestReceipt, signEnabled, encryptRequested,
1105
- statuses: currentStatuses, seededHtml, contentKey, saveStatus, hasUserContent, autosaveSuppressed, encryptionDecided,
1106
- });
1107
- latestRef.current = {
1108
- draft, mailboxUid, mailbox, encryptionPolicy, to, cc, bcc, subject, html, attachments, requestReceipt, signEnabled, encryptRequested,
1109
- statuses: currentStatuses, seededHtml, contentKey, saveStatus, hasUserContent, autosaveSuppressed, encryptionDecided,
1110
- };
1111
-
1112
- /** A message that turned out to need encryption after a plaintext copy of it was saved: the saved copy is replaced by an empty draft (the same
1113
- * uid, so attachments and the folder are undisturbed), chained after any save still on the wire. Best effort - a failure is reported once. */
1114
- function scrubSavedDraft(target: Message) {
1115
- lastSavedRef.current = null;
1116
- setSaveStatus("idle");
1117
- const previous = saveInFlightRef.current;
1118
- const scrub = (async (): Promise<Message | undefined> => {
1119
- await previous;
1120
- try {
1121
- // Its answer (the new version) is what a later delete waits for through `saveInFlightRef`, like any save's.
1122
- return await assembleDraft(target.uid, { to: [], cc: [], bcc: [], subject: "", html: "" });
1123
- } catch {
1124
- notify({
1125
- id: `scrub-draft:${target.uid}`,
1126
- kind: "warning",
1127
- title: "An earlier draft copy is still saved",
1128
- message: "This message needs encryption, but the copy saved before that was known couldn't be replaced. Discarding the draft removes it.",
1129
- });
1130
- return undefined;
1131
- }
1132
- })();
1133
- saveInFlightRef.current = scrub;
1134
- }
1135
- // Only a message that was really saved (`lastSavedRef` names its draft) has a plaintext copy to replace.
1136
- useEffect(() => {
1137
- if (encryptionDecided && draft && lastSavedRef.current?.startsWith(`${draft.uid}:`)) {
1138
- scrubSavedDraft(draft);
1139
- }
1140
- }, [encryptionDecided, draft?.uid]);
1141
-
1142
- // Recipients a reply could only work out after this window opened (Reply All: whoever the original's headers name)
1143
- // replace the ones it opened with - but only in a field the user hasn't touched, never over what they typed.
1144
- useEffect(() => {
1145
- if (!late) {
1146
- return;
1147
- }
1148
- const current = latestRef.current;
1149
- if (late.to !== undefined && current.to === (initialTo ?? "")) {
1150
- setTo(late.to);
1151
- }
1152
- if (late.cc !== undefined && current.cc === (initialCc ?? "")) {
1153
- setCc(late.cc);
1154
- setShowCcBcc((shown) => shown || late.cc !== "");
1155
- }
1156
- }, [late]);
1157
-
1158
- useEffect(() => {
1159
- const due =
1160
- !!draft &&
1161
- contentReady &&
1162
- !autosaveSuppressed &&
1163
- hasUserContent &&
1164
- lastSavedRef.current !== `${draft.uid}:${contentKey}`;
1165
- pendingSaveRef.current = due;
1166
- if (!due) {
1167
- return;
1168
- }
1169
- const timer = setTimeout(() => void saveDraftNow(), autosaveDelayMs);
1170
- return () => clearTimeout(timer);
1171
- }, [draft, contentReady, autosaveSuppressed, hasUserContent, contentKey]);
1172
-
1173
- // Unmounting with an edit still waiting on the debounce (e.g. the whole app shell unmounting) saves it
1174
- // right away rather than losing it.
1175
- useEffect(
1176
- () => () => {
1177
- if (pendingSaveRef.current && !finishedRef.current) {
1178
- void saveDraftNow();
1179
- }
1180
- },
1181
- [],
1182
- );
1183
-
1184
- /** Saves an edit still waiting on the debounce now, and resolves once that save - or one already on the
1185
- * wire - has settled, to whether the window's content is saved. A save that failed keeps the window open
1186
- * with Discard / Keep editing. A send clears `pendingSaveRef` before it starts, so this never saves mid-send. */
1187
- async function flushPendingSave(): Promise<boolean> {
1188
- if (pendingSaveRef.current && !finishedRef.current) {
1189
- const outcome = await saveDraftNow();
1190
- if (outcome.skipped) {
1191
- // Not saved, but not a failure either: it may be headed for encryption (or was sent/discarded meanwhile).
1192
- return finishedRef.current;
1193
- }
1194
- if (!outcome.message) {
1195
- showSaveFailedPrompt();
1196
- }
1197
- return !!outcome.message;
1198
- }
1199
- await saveInFlightRef.current;
1200
- const latest = latestRef.current;
1201
- if (finishedRef.current || !latest.hasUserContent || (!!latest.draft && lastSavedRef.current === `${latest.draft.uid}:${latest.contentKey}`)) {
1202
- return true;
1203
- }
1204
- // Unsaved because the last save failed (rather than, say, an encrypted message never being saved).
1205
- if (saveErrorRef.current) {
1206
- showSaveFailedPrompt();
1207
- }
1208
- return false;
1209
- }
1210
-
1211
- // Sign Out (AppShell) waits for this before ending the session.
1212
- useEffect(() => registerComposeFlush(flushPendingSave), []);
1213
-
1214
- // Leaving the page (reload, closing the tab, following a link) with anything not saved: start a save that's
1215
- // waiting on the debounce straight away and ask the browser to confirm, so the last couple of seconds of
1216
- // typing (or content that can't be saved as a draft, or failed to) aren't lost silently. Never while signing
1217
- // out - that navigation must not be cancellable.
1218
- useEffect(() => {
1219
- function handleBeforeUnload(event: BeforeUnloadEvent) {
1220
- if (finishedRef.current || isSigningOut()) {
1221
- return;
1222
- }
1223
- const latest = latestRef.current;
1224
- const unsaved =
1225
- pendingSaveRef.current ||
1226
- latest.saveStatus === "saving" ||
1227
- (latest.hasUserContent && lastSavedRef.current !== `${latest.draft?.uid}:${latest.contentKey}`);
1228
- if (!unsaved) {
1229
- return;
1230
- }
1231
- void flushPendingSave();
1232
- event.preventDefault();
1233
- event.returnValue = "";
1234
- }
1235
- window.addEventListener("beforeunload", handleBeforeUnload);
1236
- return () => window.removeEventListener("beforeunload", handleBeforeUnload);
1237
- }, []);
1238
-
1239
- // Where the caret starts, once per session: a reply/forward in the body (at its top), a new message in To - or,
1240
- // with To already filled in (e.g. Contacts' "Email"), in Subject. Minimizing unmounts the fields, so restoring a
1241
- // window must not move the caret there again.
1242
- const isReplyOrForward = initialQuotedHtml !== undefined || !!quotePending || !!resume;
1243
- const fieldsFocusedRef = useRef(false);
1244
- const bodyFocusedRef = useRef(false);
1245
- const focusToOnMount = !isReplyOrForward && !initialTo && !fieldsFocusedRef.current;
1246
- const focusSubjectOnMount = !isReplyOrForward && !!initialTo && !fieldsFocusedRef.current;
1247
- const focusBodyOnMount = isReplyOrForward && !bodyFocusedRef.current;
1248
-
1249
- // The editor serializes the seeded body its own way (see `RichTextEditor`'s `onInitialized`). While the body is
1250
- // still exactly what compose seeded, that serialization becomes the baseline - so an untouched reply or signature
1251
- // isn't mistaken for an edit (and autosaved) just because the editor was focused or clicked.
1252
- /** The quote has been added: unless the reader has typed something already, that is still exactly what compose seeded. */
1253
- function handleQuoteAppended(normalized: string) {
1254
- const latest = latestRef.current;
1255
- if (latest.html === latest.seededHtml) {
1256
- setHtml(normalized);
1257
- setSeededHtml(normalized);
1258
- }
1259
- }
1260
- function handleEditorInitialized(normalized: string) {
1261
- markComposePhase(id, "editor");
1262
- const latest = latestRef.current;
1263
- if (latest.html === latest.seededHtml && normalized !== latest.html) {
1264
- setHtml(normalized);
1265
- setSeededHtml(normalized);
1266
- }
1267
- }
1268
- useEffect(() => {
1269
- if (!minimized) {
1270
- fieldsFocusedRef.current = true;
1271
- bodyFocusedRef.current ||= contentReady;
1272
- }
1273
- }, [minimized, contentReady]);
1274
-
1275
- // Keyboard shortcuts, active while the focus is inside this window (`container`; the scope attribute on its root is what tells the
1276
- // dispatcher the focus is in a compose window at all). They do what the Send and Close buttons and autosave do, under the same conditions -
1277
- // a shortcut pressed while its button would be disabled is consumed and does nothing.
1278
- // Send never waits for the encryption settings to load (fail open, see `encryptionRequirement.ts`); it only needs the draft to exist. Pressed
1279
- // while an earlier press is still being handled it does nothing (`submit()` guards that itself).
1280
- const canSend = !!draft && !closing && !waitingForUploads;
1281
- useShortcut(SHORTCUTS.compose.send, () => void (canSend && submit(false)), { container: windowRef });
1282
- useShortcut(
1283
- SHORTCUTS.compose.saveDraft,
1284
- () => {
1285
- // Autosave's own conditions: never a draft that must not be stored as plaintext.
1286
- if (draft && contentReady && !closing && !autosaveSuppressed && hasUserContent) {
1287
- void saveDraftNow();
1288
- }
1289
- },
1290
- { container: windowRef },
1291
- );
1292
- useShortcut(
1293
- SHORTCUTS.compose.close,
1294
- () => {
1295
- if (!closing) {
1296
- void handleClose();
1297
- }
1298
- },
1299
- { container: windowRef },
1300
- );
1301
- useShortcut(SHORTCUTS.compose.create, () => openCompose({ mailboxUid }), { container: windowRef });
1302
-
1303
- const title = subject.trim() || "New Message";
1304
- const titleId = `compose-title-${id}`;
1305
-
1306
- const discardModal = (
1307
- <Modal open={closePrompt !== null} onClose={() => setClosePrompt(null)} title={closePrompt?.title ?? DISCARD_TITLE}>
1308
- <p className="text-sm text-text-muted mb-4">{closePrompt?.message}</p>
1309
- <div className="flex gap-3">
1310
- <Button type="button" onClick={() => void discardNow()} disabled={closing} className="!w-auto">
1311
- Discard
1312
- </Button>
1313
- <Button type="button" variant="secondary" onClick={() => setClosePrompt(null)} className="!w-auto">
1314
- Keep editing
1315
- </Button>
1316
- </div>
1317
- </Modal>
1318
- );
1319
-
1320
- if (minimized) {
1321
- return (
1322
- <>
1323
- <div role="dialog" aria-label={title} className="w-64 shrink-0 bg-surface border border-border border-b-0 rounded-t-md shadow-modal">
1324
- <div
1325
- className="h-10 flex items-center justify-between gap-2 px-3 rounded-t-md bg-primary-darker text-white cursor-pointer"
1326
- onClick={onToggleMinimize}
1327
- >
1328
- <span className="text-sm font-medium truncate">{title}</span>
1329
- <div className="flex items-center gap-0.5" onClick={(e) => e.stopPropagation()}>
1330
- <HeaderButton label="Restore" onClick={onToggleMinimize} icon={HiOutlineArrowsPointingOut} />
1331
- <HeaderButton label="Discard draft" onClick={handleDiscard} icon={HiOutlineXMark} disabled={closing} />
1332
- </div>
1333
- </div>
1334
- </div>
1335
- {discardModal}
1336
- </>
1337
- );
1338
- }
1339
-
1340
- return (
1341
- <>
1342
- <div
1343
- ref={windowRef}
1344
- role="dialog"
1345
- data-shortcut-scope="compose"
1346
- aria-labelledby={titleId}
1347
- style={!isMobile && manualSize ? { width: manualSize.width, height: manualSize.height } : undefined}
1348
- className={[
1349
- "shrink-0 flex flex-col bg-surface border border-border shadow-modal overflow-hidden",
1350
- // `fixed` and `relative` may not both be on the element: Tailwind emits `.relative` after `.fixed`, so it wins and the
1351
- // sheet sat in the flow of the little fixed container the windows are stacked in instead of covering the screen.
1352
- isMobile
1353
- ? "fixed inset-0 w-full h-full rounded-none border-0"
1354
- : ["relative border-b-0 rounded-t-md", manualSize ? "" : expanded ? "w-[720px] h-[85vh]" : "w-[480px] h-[520px]"].join(" "),
1355
- ].join(" ")}
1356
- >
1357
- {!isMobile && (
1358
- <>
1359
- <div
1360
- onPointerDown={handleResizeStart("top")}
1361
- aria-hidden="true"
1362
- className="absolute top-0 left-0 right-0 h-1.5 cursor-ns-resize z-20"
1363
- />
1364
- <div
1365
- onPointerDown={handleResizeStart("left")}
1366
- aria-hidden="true"
1367
- className="absolute top-0 left-0 bottom-0 w-1.5 cursor-ew-resize z-20"
1368
- />
1369
- <div
1370
- onPointerDown={handleResizeStart("corner")}
1371
- role="separator"
1372
- aria-label="Resize"
1373
- className="absolute top-0 left-0 w-3 h-3 cursor-nwse-resize z-30"
1374
- />
1375
- </>
1376
- )}
1377
-
1378
- <div
1379
- className="h-10 shrink-0 flex items-center justify-between gap-2 px-3 bg-primary-darker text-white cursor-pointer"
1380
- onClick={onToggleMinimize}
1381
- >
1382
- <span id={titleId} className="text-sm font-medium truncate">
1383
- {title}
1384
- </span>
1385
- <div className="flex items-center gap-0.5" onClick={(e) => e.stopPropagation()}>
1386
- <HeaderButton label="Minimize" onClick={onToggleMinimize} icon={HiOutlineMinus} />
1387
- {!isMobile && (
1388
- <HeaderButton
1389
- label={expanded ? "Collapse" : "Expand"}
1390
- onClick={toggleExpanded}
1391
- icon={expanded ? HiOutlineArrowsPointingIn : HiOutlineArrowsPointingOut}
1392
- />
1393
- )}
1394
- <HeaderButton label="Close" onClick={() => void handleClose()} icon={HiOutlineXMark} disabled={closing} shortcut={SHORTCUTS.compose.close} />
1395
- </div>
1396
- </div>
1397
-
1398
- <div className="flex-1 min-h-0 flex flex-col">
1399
- {(folderError || draftError || sendError || attachError || discardError) && (
1400
- // Scrolls inside the window when it is tall, instead of pushing the editor and the Send button out of the window's
1401
- // fixed height, where they can't be reached.
1402
- <div className="px-3 pt-2 shrink-0 max-h-[45%] overflow-y-auto">
1403
- {folderError && <Alert>{folderError}</Alert>}
1404
- {draftError && <Alert>{draftError}</Alert>}
1405
- {sendError && <Alert>{sendError}</Alert>}
1406
- {attachError && <Alert>{attachError}</Alert>}
1407
- {discardError && <Alert>{discardError}</Alert>}
1408
- </div>
1409
- )}
1410
-
1411
- {securityBlock && (
1412
- <div className="px-3 pt-2">
1413
- <Alert>
1414
- <p className="mb-2">{securityBlock.message}</p>
1415
- <Button type="button" onClick={() => void submit(true, blockedScheduleIso)}>
1416
- {securityBlock.overrideLabel}
1417
- </Button>
1418
- </Alert>
1419
- </div>
1420
- )}
1421
-
1422
- {fromOptions.length > 1 && (
1423
- <div className={FIELD_ROW}>
1424
- <label htmlFor={`compose-from-${id}`} className="text-xs text-text-muted shrink-0">
1425
- From
1426
- </label>
1427
- <select
1428
- id={`compose-from-${id}`}
1429
- className={`${FIELD_INPUT} disabled:opacity-55`}
1430
- // Two or more options only exist once the mailboxes have loaded, and the same answer that lets them list
1431
- // (one that isn't known to be view-only) is what picks the default sender, so a sender is always chosen by now.
1432
- value={mailboxUid}
1433
- disabled={hasUploads}
1434
- title={hasUploads ? "The sender can't be changed after adding attachments or images." : undefined}
1435
- onChange={(e) => handleFromChange(e.target.value)}
1436
- >
1437
- {fromOptions.map((mb) => (
1438
- <option key={mb.uid} value={mb.uid}>
1439
- {mb.displayName ? `${mb.displayName} <${mb.primarySmtpAddress}>` : mb.primarySmtpAddress}
1440
- {mb.ownerUserUid ? "" : " (shared)"}
1441
- </option>
1442
- ))}
1443
- </select>
1444
- </div>
1445
- )}
1446
-
1447
- <div className={FIELD_ROW}>
1448
- <label htmlFor={`compose-to-${id}`} className="text-xs text-text-muted shrink-0">
1449
- To
1450
- </label>
1451
- <RecipientInput
1452
- id={`compose-to-${id}`}
1453
- label="To"
1454
- value={to}
1455
- mailboxUid={mailboxUid}
1456
- onChange={setTo}
1457
- onBlur={(value) => checkRecipientDiscovery(parseAddresses(value))}
1458
- onCommit={(value) => checkRecipientDiscovery(parseAddresses(value))}
1459
- autoFocus={focusToOnMount}
1460
- />
1461
- {!showCcBcc && (
1462
- <button
1463
- type="button"
1464
- onClick={() => setShowCcBcc(true)}
1465
- className="text-xs text-text-muted hover:text-text shrink-0"
1466
- >
1467
- Cc Bcc
1468
- </button>
1469
- )}
1470
- </div>
1471
-
1472
- {showCcBcc && (
1473
- <>
1474
- <div className={FIELD_ROW}>
1475
- <label htmlFor={`compose-cc-${id}`} className="text-xs text-text-muted shrink-0">
1476
- Cc
1477
- </label>
1478
- <RecipientInput
1479
- id={`compose-cc-${id}`}
1480
- label="Cc"
1481
- value={cc}
1482
- mailboxUid={mailboxUid}
1483
- onChange={setCc}
1484
- onBlur={(value) => checkRecipientDiscovery(parseAddresses(value))}
1485
- onCommit={(value) => checkRecipientDiscovery(parseAddresses(value))}
1486
- />
1487
- </div>
1488
- <div className={FIELD_ROW}>
1489
- <label htmlFor={`compose-bcc-${id}`} className="text-xs text-text-muted shrink-0">
1490
- Bcc
1491
- </label>
1492
- <RecipientInput
1493
- id={`compose-bcc-${id}`}
1494
- label="Bcc"
1495
- value={bcc}
1496
- mailboxUid={mailboxUid}
1497
- onChange={setBcc}
1498
- onBlur={(value) => checkRecipientDiscovery(parseAddresses(value))}
1499
- onCommit={(value) => checkRecipientDiscovery(parseAddresses(value))}
1500
- />
1501
- </div>
1502
- </>
1503
- )}
1504
-
1505
- {(() => {
1506
- // De-duplicated by the same normalized key `recipientStatuses` itself is keyed by - two
1507
- // fields (or one field twice) naming the same mailbox in different casing now resolve to
1508
- // one shared status object (see `addressCacheKey()`'s own doc comment), so without this
1509
- // the list below would render - and React would warn about - two `<li key=...>`s sharing
1510
- // the exact same key.
1511
- const seenKeys = new Set<string>();
1512
- const knownRecipients = [...parseAddresses(to), ...parseAddresses(cc), ...parseAddresses(bcc)]
1513
- .filter((r) => {
1514
- const key = addressCacheKey(r.address);
1515
- if (seenKeys.has(key)) {
1516
- return false;
1517
- }
1518
- seenKeys.add(key);
1519
- return true;
1520
- })
1521
- .map((r) => recipientStatuses[addressCacheKey(r.address)])
1522
- .filter((status): status is RecipientEncryptionStatus => !!status);
1523
- if (knownRecipients.length === 0) {
1524
- return null;
1525
- }
1526
- return (
1527
- <ul className="flex flex-wrap gap-1.5 px-3 pt-1.5" aria-label="Recipient encryption availability">
1528
- {knownRecipients.map((status) => (
1529
- <li
1530
- key={status.address}
1531
- className={`text-xs font-medium py-0.5 px-2 rounded-pill ${
1532
- status.canEncrypt ? "bg-primary/10 text-primary-dark" : "bg-surface-alt text-text-muted"
1533
- }`}
1534
- >
1535
- {status.address} {status.canEncrypt ? "supports encryption" : "no encryption key found"}
1536
- </li>
1537
- ))}
1538
- </ul>
1539
- );
1540
- })()}
1541
-
1542
- <div className={FIELD_ROW}>
1543
- <input
1544
- aria-label="Subject"
1545
- type="text"
1546
- placeholder="Subject"
1547
- className={FIELD_INPUT}
1548
- value={subject}
1549
- autoFocus={focusSubjectOnMount}
1550
- onChange={(e) => setSubject(e.target.value)}
1551
- />
1552
- </div>
1553
-
1554
- <div className="flex-1 min-h-0 p-2">
1555
- {contentReady && (
1556
- <RichTextEditor
1557
- appendHtml={lateQuoteHtml}
1558
- onAppended={handleQuoteAppended}
1559
- value={html}
1560
- onChange={setHtml}
1561
- fill
1562
- onUploadImage={handleUploadImage}
1563
- autoFocusStart={focusBodyOnMount}
1564
- onInitialized={handleEditorInitialized}
1565
- />
1566
- )}
1567
- </div>
1568
-
1569
- {quotePending && (
1570
- <p role="status" className="px-3 pb-1 text-xs text-text-muted">
1571
- Loading the original message&hellip;
1572
- </p>
1573
- )}
1574
-
1575
- {attachments.length > 0 && (
1576
- <ul className="flex flex-wrap gap-2 px-3 pb-2">
1577
- {attachments.map((attachment) => (
1578
- <li key={attachment.uid} className="text-xs font-medium py-1 px-2.5 rounded-pill bg-surface-alt text-text-muted">
1579
- {attachment.filename}
1580
- </li>
1581
- ))}
1582
- </ul>
1583
- )}
1584
-
1585
- <label className="flex items-center gap-1.5 px-3 pb-1 text-xs text-text-muted">
1586
- <input type="checkbox" checked={requestReceipt} onChange={(e) => setRequestReceipt(e.target.checked)} />
1587
- Request a read receipt
1588
- </label>
1589
-
1590
- {needsUnlockForCrypto && (
1591
- <div className="px-3 pb-1">
1592
- <button
1593
- type="button"
1594
- onClick={handleUnlockForCrypto}
1595
- className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
1596
- >
1597
- <HiOutlineLockClosed size={12} aria-hidden="true" />
1598
- Unlock to sign or encrypt this message
1599
- </button>
1600
- </div>
1601
- )}
1602
-
1603
- {/* Only rendered once this session actually has a usable signing/encryption key - see
1604
- `sendJob.ts`'s signing path for why signing rarely shows today (no signing
1605
- certificate exists until RFC 8823 ACME enrollment lands). */}
1606
- {unlockedKeys?.signingPrivateKey && (
1607
- <label className="flex items-center gap-1.5 px-3 pb-1 text-xs text-text-muted">
1608
- <input type="checkbox" checked={signEnabled} onChange={(e) => setSignEnabled(e.target.checked)} />
1609
- Digitally sign this message
1610
- </label>
1611
- )}
1612
- {unlockedKeys?.encryptionPrivateKey && (
1613
- <label className="flex items-center gap-1.5 px-3 pb-1 text-xs text-text-muted">
1614
- <input type="checkbox" checked={encryptRequested} onChange={(e) => setEncryptRequested(e.target.checked)} />
1615
- Encrypt this message
1616
- </label>
1617
- )}
1618
-
1619
- <div className="shrink-0 flex items-center gap-1 px-3 py-2 border-t border-border">
1620
- <div className="flex items-center rounded-pill bg-primary text-white overflow-hidden">
1621
- <button
1622
- type="button"
1623
- onClick={() => void submit(false)}
1624
- title={withHint("Send", SHORTCUTS.compose.send, keyEnv)}
1625
- aria-keyshortcuts={ariaKeyShortcuts(SHORTCUTS.compose.send, keyEnv)}
1626
- disabled={!draft || closing || waitingForUploads}
1627
- className="py-1.5 pl-5 pr-3 font-semibold text-sm hover:not-disabled:bg-primary-dark disabled:opacity-55 disabled:cursor-not-allowed"
1628
- >
1629
- Send
1630
- </button>
1631
- <button
1632
- ref={scheduleButtonRef}
1633
- type="button"
1634
- aria-label="Send later"
1635
- aria-haspopup="true"
1636
- aria-expanded={schedulePickerOpen}
1637
- disabled={!draft || closing || waitingForUploads}
1638
- onClick={() => setSchedulePickerOpen((o) => !o)}
1639
- className="py-1.5 px-2 border-l border-white/30 hover:not-disabled:bg-primary-dark disabled:opacity-55 disabled:cursor-not-allowed"
1640
- >
1641
- <HiOutlineChevronDown size={14} />
1642
- </button>
1643
- </div>
1644
- {schedulePickerOpen && (
1645
- <ScheduleSendPicker
1646
- anchorRef={scheduleButtonRef}
1647
- onClose={() => setSchedulePickerOpen(false)}
1648
- onSchedule={handleScheduleSend}
1649
- />
1650
- )}
1651
-
1652
- <label
1653
- aria-label="Attach files"
1654
- title="Attach files"
1655
- className="w-8 h-8 flex items-center justify-center rounded-full text-text-muted hover:bg-surface-alt hover:text-text cursor-pointer has-[:disabled]:opacity-40 has-[:disabled]:cursor-not-allowed"
1656
- >
1657
- <HiOutlinePaperClip size={18} />
1658
- <input type="file" multiple disabled={!draft} onChange={handleFilesSelected} className="sr-only" />
1659
- </label>
1660
-
1661
- <span role="status" aria-live="polite" className="ml-auto text-xs text-text-muted">
1662
- {waitingForUploads ? "Waiting for attachments to finish uploading…" : SAVE_STATUS_LABEL[saveStatus]}
1663
- </span>
1664
-
1665
- <button
1666
- type="button"
1667
- aria-label="Discard draft"
1668
- title="Discard draft"
1669
- onClick={handleDiscard}
1670
- disabled={closing}
1671
- className="w-8 h-8 flex items-center justify-center rounded-full text-text-muted hover:bg-surface-alt hover:text-text disabled:opacity-40 disabled:cursor-not-allowed"
1672
- >
1673
- <HiOutlineTrash size={18} />
1674
- </button>
1675
- </div>
1676
- </div>
1677
- </div>
1678
- {discardModal}
1679
- </>
1680
- );
1681
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import React, { ChangeEvent, useEffect, useRef, useState } from "react";
6
+ import {
7
+ HiOutlineArrowsPointingIn,
8
+ HiOutlineArrowsPointingOut,
9
+ HiOutlineChevronDown,
10
+ HiOutlineLockClosed,
11
+ HiOutlineMinus,
12
+ HiOutlinePaperClip,
13
+ HiOutlineTrash,
14
+ HiOutlineXMark,
15
+ } from "react-icons/hi2";
16
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
17
+ import {
18
+ Attachment,
19
+ ComposeRecipientInput,
20
+ Mailbox,
21
+ Message,
22
+ assembleDraft,
23
+ attachmentContentUrl,
24
+ createDraft,
25
+ deleteMessage,
26
+ getMailbox,
27
+ getMessage,
28
+ listFolders,
29
+ listMailboxes,
30
+ uploadAttachment,
31
+ } from "@rapidmx/react-shared/mail/mailApi.js";
32
+ import { listMailSignatures } from "@rapidmx/react-shared/mail/mailSignaturesApi.js";
33
+ import { buildComposeBodyHtml } from "@rapidmx/react-shared/mail/compose/composeQuoting.js";
34
+ import { peekMailboxWritability, useMailboxWritability } from "../writableMailboxes.js";
35
+ import { orderMailboxes, primaryMailboxUid } from "../../../mail/primaryMailbox.js";
36
+ import { resolveRecipientEncryption, RecipientEncryptionStatus } from "@rapidmx/react-shared/crypto/composeSecurity.js";
37
+ import { getUnlockedKeys, subscribeKeySession } from "@rapidmx/react-shared/crypto/keySession.js";
38
+ import { EncryptionPolicy, findActivePublicKey, getEncryptionPolicy, lookupKeys } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
39
+ import { useUnlockPrompt } from "../../layout/UnlockPromptProvider.js";
40
+ import useIsMobile from "@rapidmx/react-shared/util/useIsMobile.js";
41
+ import { notify } from "../../../notifications/store.js";
42
+ import { evaluateEncryptionRequirement } from "./encryptionRequirement.js";
43
+ import { decideSend, SendBlock } from "../../../mail/outbox/sendDecision.js";
44
+ import { SendRequest, sendDecisionInput, startSend } from "../../../mail/outbox/sendJob.js";
45
+ import { useCompose, type ComposeSession } from "./ComposeContext.js";
46
+ import { ariaKeyShortcuts, withHint } from "../../../keyboard/format.js";
47
+ import { SHORTCUTS, ShortcutDef } from "../../../keyboard/keymap.js";
48
+ import { useKeyEnvironment } from "../../../keyboard/ShortcutProvider.js";
49
+ import { useShortcut } from "../../../keyboard/useShortcut.js";
50
+ import { isSigningOut, registerComposeFlush } from "./composeFlushRegistry.js";
51
+ import { markComposePhase } from "./composePerf.js";
52
+ import RecipientInput from "./RecipientInput.js";
53
+ import { parseRecipientList } from "./recipients.js";
54
+ import RichTextEditor from "./RichTextEditor.js";
55
+ import ScheduleSendPicker from "./ScheduleSendPicker.js";
56
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
57
+ import Button from "@rapidmx/react-shared/components/buttons/Button.js";
58
+ import Modal from "@rapidmx/react-shared/components/overlays/Modal.js";
59
+
60
+ export interface ComposeWindowProps {
61
+ session: ComposeSession;
62
+ onClose: () => void;
63
+ onToggleMinimize: () => void;
64
+ /** The signed-in user - identifies their own ("primary") mailbox, the default From when the session
65
+ * doesn't name a mailbox. */
66
+ userUid?: string;
67
+ /** The caller holds a trusted (admin) role - every mailbox is writable, so no per-mailbox access checks. */
68
+ trusted?: boolean;
69
+ /** How long (ms) after the last edit the draft is autosaved. Defaults to `DEFAULT_AUTOSAVE_DELAY_MS`;
70
+ * only overridden by tests. */
71
+ autosaveDelayMs?: number;
72
+ /** Backoff (ms) between automatic retries of a failed mailbox/encryption-policy load, one entry per retry.
73
+ * Defaults to `DEFAULT_CRYPTO_RETRY_DELAYS_MS`; only overridden by tests. */
74
+ cryptoRetryDelaysMs?: number[];
75
+ }
76
+
77
+ /** Debounce between the last edit and the draft autosave. */
78
+ export const DEFAULT_AUTOSAVE_DELAY_MS = 2000;
79
+
80
+ /** Automatic, silent retries of a failed mailbox/encryption-policy (or recipient key) load, one entry per retry - a flapping gateway is waited out
81
+ * in the background, without a word to the user. */
82
+ export const DEFAULT_CRYPTO_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000, 30000, 60000];
83
+
84
+ /** Thrown by `deleteDraft()` when the server copy is no longer this window's draft (sent or scheduled elsewhere). */
85
+ const NO_LONGER_A_DRAFT_MESSAGE = "This message was already sent or scheduled from another window, so it wasn't deleted.";
86
+
87
+ /** Whether `fresh` (a re-read of a draft) is still an unsent draft in `folderUid`: never delete a message another
88
+ * window has since sent, scheduled, or started sending. */
89
+ function isStillDraft(fresh: Message, folderUid: string): boolean {
90
+ return fresh.folderUid === folderUid && !fresh.scheduledSendTime && !fresh.scheduledSendLeaseExpiresAt && !fresh.scheduledSendRelayedAt;
91
+ }
92
+
93
+ const SAVE_STATUS_LABEL = { idle: "", saving: "Saving…", saved: "Draft saved", error: "Couldn't save draft" } as const;
94
+
95
+ const DISCARD_TITLE = "Discard this draft?";
96
+ /** Shown only for a message that is actually headed for encryption (asked for, or applied by the loaded policy) - see `encryptionRequirement.ts`. */
97
+ const ENCRYPTED_CLOSE_MESSAGE = "Encrypted messages aren't saved as drafts, so closing this window discards what you've written.";
98
+
99
+ /** The confirmation shown before a Close/Discard throws content away (or when a Close couldn't save it). */
100
+ interface ClosePrompt {
101
+ title: string;
102
+ message: string;
103
+ }
104
+
105
+ const FIELD_ROW = "flex items-center gap-2 px-3 py-1.5 border-b border-border";
106
+ const FIELD_INPUT = "flex-1 min-w-0 text-sm bg-transparent outline-none";
107
+
108
+ const MIN_WIDTH = 320;
109
+ const MIN_HEIGHT = 320;
110
+ // Kept well clear of the viewport edge, not flush against it — this is a resize *ceiling* (the drag
111
+ // handles below clamp to it), not the "expanded" preset's own size, which stays a plain `85vh`
112
+ // Tailwind class precisely so it never needs `window.innerHeight` at all: that'd have to be read at
113
+ // module-evaluation time to live alongside these other constants, and `window` doesn't exist yet
114
+ // during this app's SSR pass (see `ReactRoute`) — referencing it here would crash every page render,
115
+ // not just this component's.
116
+ const VIEWPORT_MARGIN = 24;
117
+
118
+ interface Size {
119
+ width: number;
120
+ height: number;
121
+ }
122
+
123
+ type ResizeEdge = "left" | "top" | "corner";
124
+
125
+ /** A To/Cc/Bcc field's recipients - see `recipients.ts` for the format. */
126
+ function parseAddresses(value: string): ComposeRecipientInput[] {
127
+ return parseRecipientList(value);
128
+ }
129
+
130
+ /**
131
+ * Normalizes an address into the key `recipientStatuses`/the in-flight and failure trackers below use -
132
+ * matching `classifyRecipientTier()`'s own lowercase-domain comparison (`@rapidmx/react-shared`'s
133
+ * `composeSecurity.ts`), but applied to the whole address rather than just the domain. Without this, the
134
+ * same mailbox typed with different casing across To/Cc/Bcc (plausible via autocomplete vs. a pasted
135
+ * signature block) is tracked as two independent recipients: if one lookup lags or fails while the other
136
+ * succeeds, `decideMessageEncryption()`'s all-or-nothing check sees a spurious unresolved recipient and
137
+ * denies auto-encryption even though every *real* recipient resolved fine. Only ever used as an internal
138
+ * cache key - `ComposeRecipientInput.address` itself (what is actually sent as the recipient) is untouched.
139
+ */
140
+ function addressCacheKey(address: string): string {
141
+ return address.trim().toLowerCase();
142
+ }
143
+
144
+ function HeaderButton({
145
+ label,
146
+ onClick,
147
+ icon: Icon,
148
+ disabled,
149
+ shortcut,
150
+ }: {
151
+ label: string;
152
+ onClick: () => void;
153
+ icon: React.ComponentType<{ size?: number }>;
154
+ disabled?: boolean;
155
+ /** The keyboard shortcut that does the same, named in the tooltip and `aria-keyshortcuts`. */
156
+ shortcut?: ShortcutDef;
157
+ }) {
158
+ const env = useKeyEnvironment();
159
+ return (
160
+ <button
161
+ type="button"
162
+ aria-label={label}
163
+ title={shortcut ? withHint(label, shortcut, env) : label}
164
+ aria-keyshortcuts={shortcut ? ariaKeyShortcuts(shortcut, env) : undefined}
165
+ onClick={onClick}
166
+ disabled={disabled}
167
+ className="w-6 h-6 flex items-center justify-center rounded-sm text-white/80 hover:bg-white/15 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed"
168
+ >
169
+ <Icon size={14} />
170
+ </button>
171
+ );
172
+ }
173
+
174
+ /**
175
+ * A floating, Gmail-style compose window — overlays whatever app is currently showing instead of
176
+ * navigating to a dedicated page (see `ComposeContext.tsx`'s doc comment for why: a full-page compose
177
+ * form meant losing your place in the inbox/calendar/contacts view behind it, and every navigation to
178
+ * `/compose` re-ran this whole app's full mailbox/folder resolution waterfall from scratch). Owns its
179
+ * own draft lifecycle end to end (unlike the old page, which read the Drafts folder from `MailShell`'s
180
+ * context — this window can be opened from apps that never mount `MailShell` at all, e.g. Contacts'
181
+ * "Email" action, so it resolves its own Drafts folder from just a `mailboxUid`).
182
+ *
183
+ * Below the `md` breakpoint, a non-minimized session instead renders as a full-screen sheet (there's no
184
+ * room for a floating window, and the click-drag resize handles below become meaningless full-screen) —
185
+ * see `ComposeContext.tsx`'s own doc comment for how that interacts with several sessions being open at
186
+ * once.
187
+ */
188
+ export default function ComposeWindow({
189
+ session,
190
+ onClose,
191
+ onToggleMinimize,
192
+ userUid,
193
+ trusted,
194
+ autosaveDelayMs = DEFAULT_AUTOSAVE_DELAY_MS,
195
+ cryptoRetryDelaysMs = DEFAULT_CRYPTO_RETRY_DELAYS_MS,
196
+ }: ComposeWindowProps) {
197
+ const { id, initialTo, initialCc, initialSubject, initialQuotedHtml, initialEncrypt, signatureContext, suppressSigning, minimized, quotePending, late, resume } = session;
198
+ // What a reply worked out after this window opened (see `OpenComposeInput.pending`): better recipients, applied below
199
+ // only to fields still exactly as they opened - so these, not `initialTo`/`initialCc`, are what "untouched" is measured against.
200
+ const baselineTo = late?.to ?? initialTo;
201
+ const baselineCc = late?.cc ?? initialCc;
202
+ useEffect(() => {
203
+ markComposePhase(id, "shell");
204
+ markComposePhase(id, "chunk");
205
+ }, []);
206
+ // The sending ("From") mailbox. A reply/forward session names the original message's mailbox; a fresh
207
+ // compose leaves it unset and defaults to the caller's own mailbox once `listMailboxes()` resolves.
208
+ // Everything mailbox-scoped below (Drafts folder, draft, signatures, crypto context) keys off this.
209
+ const [fromMailboxUid, setFromMailboxUid] = useState<string | undefined>(session.mailboxUid);
210
+ const mailboxUid = fromMailboxUid;
211
+ const [mailboxes, setMailboxes] = useState<Mailbox[]>([]);
212
+ // Attachments and inline images upload onto the current draft's uid, which lives in one mailbox's
213
+ // Drafts folder - so once anything has been uploaded the sender can no longer be switched.
214
+ const [hasUploads, setHasUploads] = useState(!!resume && resume.attachments.length > 0);
215
+ const isMobile = useIsMobile();
216
+ const { requestUnlock } = useUnlockPrompt();
217
+ const { openCompose } = useCompose();
218
+ const keyEnv = useKeyEnvironment();
219
+ // Bumped after a successful on-demand unlock to force a re-render - `getUnlockedKeys()` below is a
220
+ // plain read from a module-level store, not React state, so nothing else would pick up the change.
221
+ const [, setUnlockRefresh] = useState(0);
222
+
223
+ const windowRef = useRef<HTMLDivElement>(null);
224
+ const [draftsFolderUid, setDraftsFolderUid] = useState<string | undefined>();
225
+ const [folderError, setFolderError] = useState<string | null>(null);
226
+ // A window re-opened around a message that was already composed (a failed send's "Open draft") continues that server draft and starts with
227
+ // every field as it was typed; its body is not seeded from a signature or a quote.
228
+ const [draft, setDraft] = useState<Message | null>(resume?.draft ?? null);
229
+ // Drafts replaced by a From switch, awaiting deletion until their replacement has actually been created.
230
+ const supersededDraftsRef = useRef<Message[]>([]);
231
+ const [draftError, setDraftError] = useState<string | null>(null);
232
+ const [expanded, setExpanded] = useState(false);
233
+ const [manualSize, setManualSize] = useState<Size | null>(null);
234
+ const [to, setTo] = useState(resume?.to ?? initialTo ?? "");
235
+ const [cc, setCc] = useState(resume?.cc ?? initialCc ?? "");
236
+ const [bcc, setBcc] = useState(resume?.bcc ?? "");
237
+ const [showCcBcc, setShowCcBcc] = useState(!!(resume ? resume.cc || resume.bcc : initialCc));
238
+ const [subject, setSubject] = useState(resume?.subject ?? initialSubject ?? "");
239
+ const [html, setHtml] = useState(resume?.html ?? "");
240
+ const [contentReady, setContentReady] = useState(!!resume);
241
+ const [attachments, setAttachments] = useState<Attachment[]>(resume?.attachments ?? []);
242
+ const [attachError, setAttachError] = useState<string | null>(null);
243
+ // A problem with the message as composed (no recipient, an attachment that can't be signed): shown here, and the window stays open. What
244
+ // goes wrong after Send was accepted is a pop-up instead (see `sendJob.ts`).
245
+ const [sendError, setSendError] = useState<string | null>(null);
246
+ // Send was pressed while an attachment was still uploading: the window waits (and says so) rather than send without it.
247
+ const [waitingForUploads, setWaitingForUploads] = useState(false);
248
+ const [requestReceipt, setRequestReceipt] = useState(!!resume?.requestReceipt);
249
+ const [schedulePickerOpen, setSchedulePickerOpen] = useState(false);
250
+ const scheduleButtonRef = useRef<HTMLButtonElement>(null);
251
+ const [mailbox, setMailbox] = useState<Mailbox | null>(null);
252
+ const [encryptionPolicy, setEncryptionPolicy] = useState<EncryptionPolicy | null>(null);
253
+ // Defaults off when replying to a detected mailing list (spec's own "Mailing lists" note under
254
+ // Digital Signatures - a list that appends a footer after signing invalidates the signature) - see
255
+ // `MessageDetailPane.tsx`'s handleReply()/handleReplyAll() for where this is computed. The user can
256
+ // still turn it back on; this only changes the default.
257
+ const [signEnabled, setSignEnabled] = useState(resume ? resume.signEnabled : !suppressSigning);
258
+ // A reply to or forward of an encrypted message starts (and, after a From switch, restarts) with encryption
259
+ // requested - see `OpenComposeInput.encrypt`.
260
+ const [encryptRequested, setEncryptRequested] = useState(resume ? resume.encryptRequested : !!initialEncrypt);
261
+ // Compose-time discovery (spec: "Discovery occurs ... when the user addresses a new message to a
262
+ // recipient", never on receipt) - keyed by address so a recipient already looked up isn't re-fetched
263
+ // just because the user re-focuses the field. Only ever grows via `checkRecipientDiscovery()` below;
264
+ // never cleared, so switching focus between To/Cc/Bcc repeatedly doesn't re-trigger lookups.
265
+ const [recipientStatuses, setRecipientStatuses] = useState<Record<string, RecipientEncryptionStatus>>({});
266
+ // Addresses whose lookup is on the wire (so the blur handlers and the prefilled-recipient effect don't
267
+ // look one up twice), and a counter bumped by a From switch so a lookup for the previous sender is dropped.
268
+ const lookupsInFlightRef = useRef(new Set<string>());
269
+ const discoveryGenerationRef = useRef(0);
270
+ // A failed lookup stores no status: the recipient is simply "not known to be encryptable" (fail open - see `encryptionRequirement.ts`), and
271
+ // the lookup is retried in the background with the same backoff as the mailbox/policy load, without a word to the user.
272
+ const lookupFailuresRef = useRef(new Map<string, number>());
273
+ const lookupRetryTimersRef = useRef(new Set<ReturnType<typeof setTimeout>>());
274
+ const [lookupRetryToken, setLookupRetryToken] = useState(0);
275
+ // A send refused *before it left* because signing/encryption was asked for (or the loaded policy applies it) but can't happen right now
276
+ // (keys locked, Bcc recipients on an encrypted message, a recipient without a key) - never a silent downgrade to plaintext; the user
277
+ // has to explicitly pick the override.
278
+ const [securityBlock, setSecurityBlock] = useState<SendBlock | null>(null);
279
+ // The schedule time of the send that got blocked (undefined for an immediate send), so the banners'
280
+ // override buttons replay the same kind of send the user originally asked for.
281
+ const [blockedScheduleIso, setBlockedScheduleIso] = useState<string | undefined>();
282
+ // Which crypto toggles were ever shown during this compose session (per sending mailbox). Keys that
283
+ // lock after that point must block the send rather than quietly dropping the signature/encryption.
284
+ const offeredCryptoRef = useRef({ sign: false, encrypt: false });
285
+
286
+ // Draft autosave / discard bookkeeping.
287
+ const [seededHtml, setSeededHtml] = useState<string | undefined>();
288
+ const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved" | "error">("idle");
289
+ const [closePrompt, setClosePrompt] = useState<ClosePrompt | null>(null);
290
+ /** A Close (saving) or Discard (deleting) is on the wire - the window closes once it succeeds. */
291
+ const [closing, setClosing] = useState(false);
292
+ const [discardError, setDiscardError] = useState<string | null>(null);
293
+ /** Why the last save failed, cleared by the next successful one. */
294
+ const saveErrorRef = useRef<string | null>(null);
295
+ /** `<draftUid>:<content key>` of the last successful save. */
296
+ const lastSavedRef = useRef<string | null>(null);
297
+ /** An edit is waiting on the autosave debounce - flushed if the window unmounts first. */
298
+ const pendingSaveRef = useRef(false);
299
+ /** Send was pressed and is being validated/handed over: a second press (a double click, the shortcut held or repeated) does nothing. */
300
+ const submittingRef = useRef(false);
301
+ /** Attachment/inline-image uploads on the wire, and who is waiting for them to finish (Send pressed meanwhile). */
302
+ const uploadsInFlightRef = useRef(0);
303
+ const uploadWaitersRef = useRef<(() => void)[]>([]);
304
+ /** The latest save request, if any - each save is chained after the one before it. Always settles (never
305
+ * rejects), to the saved message, or `undefined` when that save failed. */
306
+ const saveInFlightRef = useRef<Promise<Message | undefined>>(Promise.resolve(undefined));
307
+ /** Set once the window has been sent/closed/discarded - nothing more gets autosaved after that. */
308
+ const finishedRef = useRef(false);
309
+
310
+ // A mailbox with no keys enrolled yet just means sign/encrypt stay unavailable for this compose session -
311
+ // encryption is optional and gradual by design (see `KeyEnrollmentGate`'s own doc comment).
312
+ // The mailbox and the encryption policy load in the background and *nothing waits for them*: until both have loaded, the message is treated as
313
+ // not encrypted - its draft saves, Close and Send work, and no message about it is shown (see `encryptionRequirement.ts`). A failed load is
314
+ // retried silently with backoff (`cryptoRetryDelaysMs`); if it later turns out the message must be encrypted, `encryptionDecided` (below) starts
315
+ // to apply - see the transition rules there.
316
+
317
+ useEffect(() => {
318
+ let cancelled = false;
319
+ listMailboxes({ limit: 100 })
320
+ .then((result) => {
321
+ if (cancelled) {
322
+ return;
323
+ }
324
+ // Listed with the caller's own (primary) mailbox first, and defaulted to below.
325
+ const ordered = orderMailboxes(result, userUid);
326
+ setMailboxes(ordered);
327
+ // Never default to a mailbox already known to be view-only (see the effect below for one
328
+ // that turns out to be).
329
+ const candidates = ordered.filter((mb) => peekMailboxWritability(mb, userUid, trusted) !== false);
330
+ setFromMailboxUid((current) => current ?? primaryMailboxUid(candidates, userUid));
331
+ })
332
+ .catch((err) => {
333
+ // Only fatal when there's no mailbox to fall back on - a session that already names one just
334
+ // loses the From picker.
335
+ if (!cancelled && !session.mailboxUid) {
336
+ setFolderError(err instanceof ApiRequestError ? err.message : "Could not load your mailboxes.");
337
+ }
338
+ });
339
+ return () => {
340
+ cancelled = true;
341
+ };
342
+ }, []);
343
+
344
+ useEffect(() => {
345
+ if (!mailboxUid) {
346
+ return;
347
+ }
348
+ let cancelled = false;
349
+ let timer: ReturnType<typeof setTimeout> | undefined;
350
+ // A retry only fetches what's still missing.
351
+ let mailboxLoaded = mailbox?.uid === mailboxUid;
352
+ let policyLoaded = !!encryptionPolicy;
353
+ let retries = 0;
354
+ async function load() {
355
+ await Promise.all([
356
+ mailboxLoaded ||
357
+ getMailbox(mailboxUid!).then(
358
+ (result) => {
359
+ mailboxLoaded = true;
360
+ if (!cancelled) {
361
+ setMailbox(result);
362
+ }
363
+ },
364
+ () => undefined,
365
+ ),
366
+ policyLoaded ||
367
+ getEncryptionPolicy().then(
368
+ (result) => {
369
+ policyLoaded = true;
370
+ if (!cancelled) {
371
+ setEncryptionPolicy(result);
372
+ }
373
+ },
374
+ () => undefined,
375
+ ),
376
+ ]);
377
+ if (!cancelled && (!mailboxLoaded || !policyLoaded) && retries < cryptoRetryDelaysMs.length) {
378
+ timer = setTimeout(() => void load(), cryptoRetryDelaysMs[retries++]);
379
+ }
380
+ }
381
+ void load();
382
+ return () => {
383
+ cancelled = true;
384
+ clearTimeout(timer);
385
+ };
386
+ }, [mailboxUid]);
387
+
388
+ useEffect(() => {
389
+ if (!mailboxUid) {
390
+ return;
391
+ }
392
+ // Cancellable so a slow response for a mailbox the user has since switched away from can't point
393
+ // the new draft at the wrong mailbox's Drafts folder.
394
+ let cancelled = false;
395
+ listFolders(mailboxUid)
396
+ .then((folders) => {
397
+ if (!cancelled) {
398
+ setDraftsFolderUid(folders.find((f) => f.type === "drafts")?.uid);
399
+ }
400
+ })
401
+ .catch((err) => {
402
+ if (!cancelled) {
403
+ setFolderError(err instanceof ApiRequestError ? err.message : "Could not load your Drafts folder.");
404
+ }
405
+ });
406
+ return () => {
407
+ cancelled = true;
408
+ };
409
+ }, [mailboxUid]);
410
+
411
+ /**
412
+ * Runs discovery for whichever of `addresses` haven't already been looked up this compose session,
413
+ * caching the result so the small per-recipient indicator below the recipient fields can update
414
+ * without waiting for Send. Called from the To/Cc/Bcc fields' own `onBlur` - not on every keystroke,
415
+ * and not the lookup the background send (`sendJob.ts`) performs again at send time (deliberately: this is a
416
+ * best-effort UI hint, not something a stale value here should be trusted to skip at send time).
417
+ * A mailbox/policy fetch that hasn't resolved yet just leaves that address with no indicator - the effect
418
+ * below runs it again for every current recipient once both have loaded. A failed lookup leaves it without
419
+ * a status too, and is retried silently after `cryptoRetryDelaysMs` (then only on blur).
420
+ *
421
+ * The statuses also drive `encryptionRequirement.ts`: only when every recipient has one, and the loaded policy
422
+ * auto-encrypts for all of them, does the message turn into one that is never saved as a plaintext draft.
423
+ */
424
+ function checkRecipientDiscovery(addresses: ComposeRecipientInput[]) {
425
+ if (!mailbox || !encryptionPolicy) {
426
+ return;
427
+ }
428
+ const ownPrefersMutual = mailbox.encryptPreference?.preferEncrypt === "mutual";
429
+ const generation = discoveryGenerationRef.current;
430
+ const inFlight = lookupsInFlightRef.current;
431
+ const unchecked = addresses.filter((r) => !(addressCacheKey(r.address) in recipientStatuses) && !inFlight.has(addressCacheKey(r.address)));
432
+ for (const recipient of unchecked) {
433
+ const key = addressCacheKey(recipient.address);
434
+ inFlight.add(key);
435
+ void lookupKeys(mailbox.uid, recipient.address)
436
+ .then(
437
+ (lookup) => ({ lookup }),
438
+ () => null,
439
+ )
440
+ .then((result) => {
441
+ inFlight.delete(key);
442
+ if (generation !== discoveryGenerationRef.current) {
443
+ return;
444
+ }
445
+ if (!result) {
446
+ noteLookupFailed(key);
447
+ return;
448
+ }
449
+ lookupFailuresRef.current.delete(key);
450
+ const status = resolveRecipientEncryption(mailbox.primarySmtpAddress, ownPrefersMutual, encryptionPolicy, recipient.address, result.lookup);
451
+ setRecipientStatuses((prev) => ({ ...prev, [key]: status }));
452
+ });
453
+ }
454
+ }
455
+
456
+ /** Schedules the next automatic, silent retry of a failed lookup (until the backoff has run out; a later blur tries again). */
457
+ function noteLookupFailed(address: string) {
458
+ const failures = (lookupFailuresRef.current.get(address) ?? 0) + 1;
459
+ lookupFailuresRef.current.set(address, failures);
460
+ if (failures > cryptoRetryDelaysMs.length) {
461
+ return;
462
+ }
463
+ const timer = setTimeout(() => {
464
+ lookupRetryTimersRef.current.delete(timer);
465
+ setLookupRetryToken((n) => n + 1);
466
+ }, cryptoRetryDelaysMs[failures - 1]);
467
+ lookupRetryTimersRef.current.add(timer);
468
+ }
469
+
470
+ useEffect(
471
+ () => () => {
472
+ for (const timer of lookupRetryTimersRef.current) {
473
+ clearTimeout(timer);
474
+ }
475
+ },
476
+ [],
477
+ );
478
+
479
+ // Prefilled recipients (a reply's To/Cc) are never blurred, and a blur before the mailbox/policy loaded
480
+ // was ignored - look every current recipient up as soon as both are available (and again on a lookup retry).
481
+ useEffect(() => {
482
+ checkRecipientDiscovery([...parseAddresses(to), ...parseAddresses(cc), ...parseAddresses(bcc)]);
483
+ }, [mailbox, encryptionPolicy, lookupRetryToken]);
484
+
485
+ // Resolves the mailbox's default signature (if any) for `signatureContext` and seeds `html` with it (not for a window re-opened around a composed message)
486
+ // plus any quoted original message (laid out by `buildComposeBodyHtml()`: an empty first paragraph for the
487
+ // caret, then the signature, then the quote), before `RichTextEditor` ever mounts (gated by `contentReady`
488
+ // below) — `RichTextEditor`'s own doc comment is explicit that `value` only seeds its *initial*
489
+ // content and never re-syncs from a later prop change, so this has to resolve before that first
490
+ // mount, not after. A signature-list failure is best-effort, same as every other supplementary,
491
+ // non-blocking fetch in this codebase (e.g. `ConversationList`'s own child-message fetch) — no
492
+ // signature is a completely legitimate outcome, so this falls back to just the quoted content
493
+ // (if any) rather than surfacing an error over what's a cosmetic nicety.
494
+ //
495
+ // A reply or forward opens before its quoted original has been fetched (`quotePending`, see
496
+ // `OpenComposeInput.pending`). The body is seeded as soon as the signature is here, without the quote, so the editor is usable
497
+ // at once however slow the original is to come; the quote is added at the end of the editor's document when it arrives
498
+ // (`appendHtml` below) - the same place, under the signature, that a body seeded with it would have had it.
499
+ const [defaultSignature, setDefaultSignature] = useState<{ html?: string } | undefined>();
500
+ useEffect(() => {
501
+ // Fetched once, for whichever mailbox is the sender when compose opens - switching From later must not
502
+ // overwrite what the user has already written (the editor itself never re-syncs).
503
+ if (!mailboxUid || contentReady || defaultSignature) {
504
+ return;
505
+ }
506
+ listMailSignatures(mailboxUid)
507
+ .then((signatures) => {
508
+ const signature = signatures.find((s) =>
509
+ signatureContext === "new" ? s.isDefaultForNewMessages : s.isDefaultForReplyForward,
510
+ );
511
+ setDefaultSignature({ html: signature?.contentHtml });
512
+ })
513
+ .catch(() => setDefaultSignature({}));
514
+ }, [mailboxUid, signatureContext]);
515
+ const [seededWithoutQuote, setSeededWithoutQuote] = useState(false);
516
+ useEffect(() => {
517
+ if (contentReady || !defaultSignature) {
518
+ return;
519
+ }
520
+ const seeded = buildComposeBodyHtml(defaultSignature.html, quotePending ? undefined : initialQuotedHtml);
521
+ setHtml(seeded);
522
+ setSeededHtml(seeded);
523
+ setSeededWithoutQuote(!!quotePending);
524
+ setContentReady(true);
525
+ markComposePhase(id, "body");
526
+ }, [defaultSignature, quotePending, initialQuotedHtml]);
527
+ /** What the editor adds to the end of its document once the quote a reply was opened without has arrived. */
528
+ const lateQuoteHtml =
529
+ seededWithoutQuote && !quotePending && initialQuotedHtml && defaultSignature
530
+ ? buildComposeBodyHtml(defaultSignature.html, initialQuotedHtml).slice(buildComposeBodyHtml(defaultSignature.html) === "" ? "<p></p>".length : buildComposeBodyHtml(defaultSignature.html).length)
531
+ : undefined;
532
+
533
+ useEffect(() => {
534
+ if (!mailboxUid || !draftsFolderUid || draft) {
535
+ return;
536
+ }
537
+ let cancelled = false;
538
+ // `session.threading` is what makes a reply a reply: the server writes it into the relayed MIME's
539
+ // `In-Reply-To`/`References` and groups the message into the thread being answered. Recorded on
540
+ // every draft this window creates, including the replacement one a From switch makes - the thread
541
+ // doesn't change because the sending mailbox did.
542
+ createDraft(mailboxUid, draftsFolderUid, session.threading)
543
+ .then((created) => {
544
+ if (cancelled) {
545
+ // The sender changed while this was in flight - discard the now-orphaned draft.
546
+ void deleteMessage(created.uid, created.version).catch(() => undefined);
547
+ return;
548
+ }
549
+ setDraft(created);
550
+ markComposePhase(id, "draft");
551
+ // Only now that the replacement exists is it safe to discard the draft(s) a From switch
552
+ // superseded - if creating this one had failed, the earlier draft is still there.
553
+ for (const superseded of supersededDraftsRef.current.splice(0)) {
554
+ void deleteSupersededDraft(superseded);
555
+ }
556
+ })
557
+ .catch((err) => {
558
+ if (!cancelled) {
559
+ setDraftError(err instanceof ApiRequestError ? err.message : "Could not start a new draft.");
560
+ }
561
+ });
562
+ return () => {
563
+ cancelled = true;
564
+ };
565
+ }, [mailboxUid, draftsFolderUid, draft, session.threading]);
566
+
567
+ // Drafts a From switch superseded are otherwise only deleted once their replacement exists - closing the
568
+ // window (or sending, which closes it) first would orphan them.
569
+ useEffect(
570
+ () => () => {
571
+ for (const superseded of supersededDraftsRef.current.splice(0)) {
572
+ void deleteSupersededDraft(superseded);
573
+ }
574
+ },
575
+ [],
576
+ );
577
+
578
+ /**
579
+ * Deletes a draft a From switch replaced. An autosave of it may still be on the wire - it bumps the
580
+ * draft's version (see `saveDraftNow()`, which keeps `superseded.version` current while it's queued), so
581
+ * the delete waits for it and uses its version; a delete that still fails (e.g. another save of it landed
582
+ * meanwhile) is retried once with the version the server currently holds - unless it's no longer a draft
583
+ * (another window sent or scheduled it), which is left alone.
584
+ * Best-effort, never rejects.
585
+ */
586
+ async function deleteSupersededDraft(superseded: Message): Promise<void> {
587
+ const saved = await saveInFlightRef.current;
588
+ // Once it's out of `supersededDraftsRef` a landing save can't update `superseded.version` any more.
589
+ const version = saved?.uid === superseded.uid ? saved.version : superseded.version;
590
+ try {
591
+ await deleteMessage(superseded.uid, version);
592
+ } catch {
593
+ try {
594
+ const fresh = await getMessage(superseded.uid);
595
+ if (isStillDraft(fresh, superseded.folderUid)) {
596
+ await deleteMessage(fresh.uid, fresh.version);
597
+ }
598
+ } catch {
599
+ // Already gone, or the server is unreachable - nothing more to do from here.
600
+ }
601
+ }
602
+ }
603
+
604
+ // The From picker lists every mailbox straight away and drops view-only ones as each check answers - only
605
+ // mailboxes the caller can create a draft in are worth offering.
606
+ const writability = useMailboxWritability(mailboxes, userUid, trusted);
607
+ const fromOptions = mailboxes.filter((mb) => mb.uid === mailboxUid || writability[mb.uid] !== false);
608
+
609
+ // The sender turned out to be view-only (e.g. a reply to a message in a mailbox shared read-only, or a
610
+ // first-listed shared mailbox): switch to one the caller can actually send from, preferring their own.
611
+ const fromIsViewOnly = !!mailboxUid && writability[mailboxUid] === false;
612
+ useEffect(() => {
613
+ if (!fromIsViewOnly || hasUploads) {
614
+ return;
615
+ }
616
+ const ordered = orderMailboxes(mailboxes, userUid);
617
+ const alternative = ordered.find((mb) => writability[mb.uid] === true) ?? ordered.find((mb) => writability[mb.uid] === undefined);
618
+ if (alternative) {
619
+ handleFromChange(alternative.uid);
620
+ }
621
+ }, [fromIsViewOnly, writability]);
622
+
623
+ /** Switches the sending mailbox: supersedes the current (unsent, upload-free) draft and resets the
624
+ * per-mailbox state, so the effects above start a fresh draft and crypto context in the new mailbox -
625
+ * the old draft is deleted only once the new one has been created. Recipients, subject, and body are
626
+ * kept. */
627
+ function handleFromChange(nextMailboxUid: string) {
628
+ if (nextMailboxUid === mailboxUid || hasUploads) {
629
+ return;
630
+ }
631
+ if (draft) {
632
+ supersededDraftsRef.current.push(draft);
633
+ }
634
+ setDraft(null);
635
+ setDraftsFolderUid(undefined);
636
+ setDraftError(null);
637
+ setFolderError(null);
638
+ setMailbox(null);
639
+ setRecipientStatuses({});
640
+ discoveryGenerationRef.current += 1;
641
+ lookupsInFlightRef.current = new Set();
642
+ lookupFailuresRef.current = new Map();
643
+ setEncryptRequested(!!initialEncrypt);
644
+ setSecurityBlock(null);
645
+ offeredCryptoRef.current = { sign: false, encrypt: false };
646
+ setFromMailboxUid(nextMailboxUid);
647
+ }
648
+
649
+ /**
650
+ * Click-and-drag resize, from the window's own top/left edges (and the top-left corner, for both
651
+ * at once) — the window is anchored bottom-right (see `ComposeContext.tsx`'s stack), so growing it
652
+ * always means extending up and/or left, never down/right. `onMove`/`onUp` are fresh closures
653
+ * created per drag gesture (captured over this gesture's own start position/size) rather than
654
+ * stable component-level functions, specifically so `removeEventListener` in `onUp` always removes
655
+ * the exact listener `onMove`/`onUp` themselves just added — a version defined once per render and
656
+ * reused across gestures would need extra ref-juggling to avoid removing a stale (already-replaced)
657
+ * listener instead of the current one.
658
+ */
659
+ function handleResizeStart(edge: ResizeEdge) {
660
+ return (e: React.PointerEvent) => {
661
+ e.preventDefault();
662
+ const rect = windowRef.current!.getBoundingClientRect();
663
+ const startX = e.clientX;
664
+ const startY = e.clientY;
665
+ const startWidth = rect.width;
666
+ const startHeight = rect.height;
667
+
668
+ function onMove(ev: PointerEvent) {
669
+ const maxWidth = window.innerWidth - VIEWPORT_MARGIN;
670
+ const maxHeight = window.innerHeight - VIEWPORT_MARGIN;
671
+ const width = edge === "top" ? startWidth : Math.min(Math.max(startWidth - (ev.clientX - startX), MIN_WIDTH), maxWidth);
672
+ const height = edge === "left" ? startHeight : Math.min(Math.max(startHeight - (ev.clientY - startY), MIN_HEIGHT), maxHeight);
673
+ setManualSize({ width, height });
674
+ }
675
+ function onUp() {
676
+ window.removeEventListener("pointermove", onMove);
677
+ window.removeEventListener("pointerup", onUp);
678
+ }
679
+ window.addEventListener("pointermove", onMove);
680
+ window.addEventListener("pointerup", onUp);
681
+ };
682
+ }
683
+
684
+ function toggleExpanded() {
685
+ setExpanded((v) => !v);
686
+ setManualSize(null);
687
+ }
688
+
689
+ /** Uploads `file` as an attachment on the current draft, resolving to a URL the editor can preview
690
+ * it at immediately — see `BaseMailComposeRoute.rewriteInlineImageSources()`'s doc comment for how
691
+ * that URL gets swapped for the message's real inline `cid:` reference at send time. Resolves to
692
+ * `null` (surfacing `attachError` itself, reusing the same state "Attach files" already has) rather
693
+ * than throwing: unlike "Attach files" (`disabled={!draft}`), "Insert image" in the formatting
694
+ * toolbar is only gated on the *editor* being mounted, not on the draft existing yet — those two
695
+ * things load in parallel, so a real (if narrow) window exists where the button is clickable before
696
+ * `draft` resolves, and this needs to fail gracefully rather than crash on a null draft.
697
+ */
698
+ async function handleUploadImage(file: File): Promise<string | null> {
699
+ if (!draft) {
700
+ setAttachError("Please wait for the draft to finish loading before inserting an image.");
701
+ return null;
702
+ }
703
+ uploadStarted();
704
+ try {
705
+ const attachment = await uploadAttachment(draft.uid, file);
706
+ setHasUploads(true);
707
+ void refreshDraftVersion(draft.uid);
708
+ return attachmentContentUrl(attachment.uid);
709
+ } catch (err) {
710
+ setAttachError(err instanceof ApiRequestError ? err.message : "Could not upload image.");
711
+ return null;
712
+ } finally {
713
+ uploadFinished();
714
+ }
715
+ }
716
+
717
+ /** Send waits for every upload started before it: see `submit()`. */
718
+ function uploadStarted() {
719
+ uploadsInFlightRef.current += 1;
720
+ }
721
+ function uploadFinished() {
722
+ uploadsInFlightRef.current -= 1;
723
+ if (uploadsInFlightRef.current === 0) {
724
+ for (const resolve of uploadWaitersRef.current.splice(0)) {
725
+ resolve();
726
+ }
727
+ }
728
+ }
729
+
730
+ /** Uploading an attachment bumps the draft's version server-side (it records `hasAttachments`), so a later
731
+ * Discard would otherwise send a stale `?version=`. Best-effort: Discard also retries with the server's
732
+ * current version. */
733
+ async function refreshDraftVersion(uid: string) {
734
+ try {
735
+ const fresh = await getMessage(uid);
736
+ setDraft((prev) => (prev?.uid === fresh.uid && fresh.version > prev.version ? { ...prev, version: fresh.version } : prev));
737
+ } catch {
738
+ // Discard's own retry covers a version this couldn't refresh.
739
+ }
740
+ }
741
+
742
+ // The "Attach files" input is itself `disabled` until `draft` resolves (see its `disabled={!draft}`
743
+ // below), so this can only ever fire once `draft` is set — no defensive null check needed, matching
744
+ // this codebase's established pattern for the same class of "always non-null by the time it's
745
+ // called" value (e.g. `ComposeToolbar.run()`). No separate empty-`files` guard either: the loop
746
+ // below is already a no-op when there's nothing to iterate.
747
+ async function handleFilesSelected(e: ChangeEvent<HTMLInputElement>) {
748
+ const files = Array.from(e.target.files ?? []);
749
+ e.target.value = "";
750
+ setAttachError(null);
751
+ uploadStarted();
752
+ try {
753
+ for (const file of files) {
754
+ try {
755
+ const attachment = await uploadAttachment(draft!.uid, file);
756
+ setHasUploads(true);
757
+ setAttachments((prev) => [...prev, attachment]);
758
+ void refreshDraftVersion(draft!.uid);
759
+ } catch (err) {
760
+ setAttachError(err instanceof ApiRequestError ? err.message : "Could not upload attachment.");
761
+ }
762
+ }
763
+ } finally {
764
+ uploadFinished();
765
+ }
766
+ }
767
+
768
+ /**
769
+ * Send (or, given `scheduledSendTimeIso`, Send later) - and get out of the way. The window is the place the message is *written*; nothing
770
+ * about getting it to the server is waited for here.
771
+ *
772
+ * 1. **Validate synchronously**, from what the window already knows (no request): a recipient is required; and if the message is one
773
+ * that must be signed or encrypted and can't be right now (keys locked, Bcc on an encrypted message, a recipient with no key, an
774
+ * attachment that can't be signed) that is shown right here and the window stays open - the sender fixes it or picks the override.
775
+ * An attachment still uploading is waited for, inline (Send says so), never left behind.
776
+ * 2. **Close immediately** (`onClose()`): `startSend()` (see `sendJob.ts`) takes over with a snapshot of the message. From here the only
777
+ * feedback is the Outbox indicator; a failure at any stage is a sticky pop-up with the reason and Retry / Open draft.
778
+ *
779
+ * Pressed twice (a double click, the shortcut repeated) it sends once: the first press sets `submittingRef` before any `await`, and
780
+ * `startSend()` itself refuses a draft that is already being sent. `forcePlaintext` is the override buttons' choice.
781
+ */
782
+ async function submit(forcePlaintext: boolean, scheduledSendTimeIso?: string) {
783
+ if (submittingRef.current || finishedRef.current) {
784
+ return;
785
+ }
786
+ if (parseAddresses(latestRef.current.to).length === 0) {
787
+ setSendError("At least one recipient is required.");
788
+ return;
789
+ }
790
+ submittingRef.current = true;
791
+ setSendError(null);
792
+ setSecurityBlock(null);
793
+ try {
794
+ if (uploadsInFlightRef.current > 0) {
795
+ setWaitingForUploads(true);
796
+ await new Promise<void>((resolve) => uploadWaitersRef.current.push(resolve));
797
+ // The editor puts an image it has just uploaded into the message a moment after the upload resolves: let the window catch up.
798
+ await new Promise((resolve) => setTimeout(resolve, 0));
799
+ setWaitingForUploads(false);
800
+ }
801
+ const current = latestRef.current;
802
+ const request: SendRequest = {
803
+ draft: current.draft!,
804
+ mailboxUid: current.mailboxUid!,
805
+ mailbox: current.mailbox ?? undefined,
806
+ policy: current.encryptionPolicy ?? undefined,
807
+ toText: current.to,
808
+ ccText: current.cc,
809
+ bccText: current.bcc,
810
+ to: parseAddresses(current.to),
811
+ cc: parseAddresses(current.cc),
812
+ bcc: parseAddresses(current.bcc),
813
+ subject: current.subject,
814
+ html: current.html,
815
+ attachments: current.attachments,
816
+ requestReceipt: current.requestReceipt,
817
+ scheduledSendTime: scheduledSendTimeIso,
818
+ signEnabled: current.signEnabled,
819
+ offeredSign: offeredCryptoRef.current.sign,
820
+ offeredEncrypt: offeredCryptoRef.current.encrypt,
821
+ encryptRequested: current.encryptRequested,
822
+ forcePlaintext,
823
+ saved: saveInFlightRef.current,
824
+ threading: session.threading,
825
+ };
826
+ if (request.to.length === 0) {
827
+ setSendError("At least one recipient is required.");
828
+ return;
829
+ }
830
+ const early = decideSend(sendDecisionInput(request, request.mailbox, request.policy, current.statuses, false));
831
+ if (early.action === "rejected") {
832
+ setSendError(early.message);
833
+ return;
834
+ }
835
+ if (early.action === "blocked") {
836
+ setBlockedScheduleIso(scheduledSendTimeIso);
837
+ setSecurityBlock(early.block);
838
+ if (early.block.keysLocked && (hasEnrolledSigningKey || hasEnrolledEncryptionKey)) {
839
+ void handleUnlockForCrypto();
840
+ }
841
+ return;
842
+ }
843
+ pendingSaveRef.current = false;
844
+ finishedRef.current = true;
845
+ if (!startSend(request)) {
846
+ finishedRef.current = false;
847
+ setSendError("This message is already being sent.");
848
+ return;
849
+ }
850
+ onClose();
851
+ } finally {
852
+ submittingRef.current = false;
853
+ setWaitingForUploads(false);
854
+ }
855
+ }
856
+
857
+ function handleScheduleSend(scheduledSendTimeIso: string) {
858
+ setSchedulePickerOpen(false);
859
+ void submit(false, scheduledSendTimeIso);
860
+ }
861
+
862
+ async function handleUnlockForCrypto() {
863
+ try {
864
+ // Only reachable when hasEnrolledSigningKey/hasEnrolledEncryptionKey found a real enrolled key
865
+ // in mailbox.keys (the unlock button below, or a blocked send()), so neither is empty/undefined here.
866
+ await requestUnlock(mailbox!.uid, mailbox!.keys!);
867
+ setUnlockRefresh((n) => n + 1);
868
+ } catch {
869
+ // User dismissed the unlock dialog - nothing to do, the toggles below simply stay hidden.
870
+ }
871
+ }
872
+
873
+ /**
874
+ * Saves the window's current recipients/subject/body onto its server draft via `assembleDraft()` (the
875
+ * same plaintext assembly a normal send uses). Chained after any save already on the wire - two
876
+ * overlapping assemblies of the same draft race on its version and the later one is rejected - and reads
877
+ * `latestRef` only once it actually runs, so it saves what was last typed (skipping the request when the
878
+ * save before it already stored exactly that). Whether a save may happen at all is re-checked at that same
879
+ * moment: while it waited, the message may have become one that must not be stored as plaintext (Encrypt
880
+ * turned on, a recipient that auto-encrypts), or the window may have been sent or finished - then it
881
+ * resolves `{ skipped: true }` without a request (`message` then being the previous save's result). Never
882
+ * rejects; `message` is `undefined` when the save failed.
883
+ */
884
+ function saveDraftNow(): Promise<{ message?: Message; skipped?: boolean }> {
885
+ const target = latestRef.current.draft!;
886
+ const previous = saveInFlightRef.current;
887
+ pendingSaveRef.current = false;
888
+ setSaveStatus("saving");
889
+ const outcome = (async (): Promise<{ message?: Message; skipped?: boolean }> => {
890
+ const before = await previous;
891
+ const current = latestRef.current;
892
+ if (current.autosaveSuppressed || finishedRef.current) {
893
+ setSaveStatus("idle");
894
+ // Still the newest copy the server holds, for the version a later delete needs.
895
+ return { skipped: true, message: before };
896
+ }
897
+ const savedKey = `${target.uid}:${current.contentKey}`;
898
+ if (before?.uid === target.uid && lastSavedRef.current === savedKey) {
899
+ setSaveStatus("saved");
900
+ return { message: before };
901
+ }
902
+ try {
903
+ const saved = await assembleDraft(target.uid, {
904
+ to: parseAddresses(current.to),
905
+ cc: parseAddresses(current.cc),
906
+ bcc: parseAddresses(current.bcc),
907
+ subject: current.subject,
908
+ html: current.html,
909
+ });
910
+ lastSavedRef.current = savedKey;
911
+ saveErrorRef.current = null;
912
+ // A From switch may have replaced the draft while this was in flight - never resurrect it,
913
+ // but do keep its superseded copy's version current so its pending delete still matches.
914
+ setDraft((prev) => (prev?.uid === saved.uid ? saved : prev));
915
+ const superseded = supersededDraftsRef.current.find((d) => d.uid === saved.uid);
916
+ if (superseded) {
917
+ superseded.version = saved.version;
918
+ }
919
+ setSaveStatus("saved");
920
+ return { message: saved };
921
+ } catch (err) {
922
+ saveErrorRef.current = err instanceof ApiRequestError ? err.message : "the server couldn't be reached";
923
+ setSaveStatus("error");
924
+ return {};
925
+ }
926
+ })();
927
+ saveInFlightRef.current = outcome.then((result) => result.message);
928
+ return outcome;
929
+ }
930
+
931
+ /** Keeps the window open after its content couldn't be saved, offering Discard or Keep editing. */
932
+ function showSaveFailedPrompt() {
933
+ setClosePrompt({
934
+ title: "Couldn't save this draft",
935
+ message: `It couldn't be saved (${saveErrorRef.current!.replace(/\.$/, "")}). Keep editing and try again, or discard it.`,
936
+ });
937
+ }
938
+
939
+ /**
940
+ * Deletes `current` (this window's server draft) once any save already on the wire has landed, so the delete
941
+ * carries the draft's current version. A delete rejected for a stale version (404/409: e.g. an attachment
942
+ * upload bumped it) is retried once with the version the server holds - and a draft the server no longer has
943
+ * counts as deleted. The retry only happens while the server copy is still an unsent draft in the same folder.
944
+ * Rejects when the draft couldn't be deleted.
945
+ */
946
+ async function deleteDraft(current: Message): Promise<void> {
947
+ const saved = await saveInFlightRef.current;
948
+ const version = Math.max(current.version, saved?.uid === current.uid ? saved.version : 0);
949
+ try {
950
+ await deleteMessage(current.uid, version);
951
+ } catch (err) {
952
+ if (!(err instanceof ApiRequestError) || (err.status !== 404 && err.status !== 409)) {
953
+ throw err;
954
+ }
955
+ const fresh = await getMessage(current.uid).catch((getErr: unknown) => {
956
+ if (getErr instanceof ApiRequestError && getErr.status === 404) {
957
+ return null;
958
+ }
959
+ throw getErr;
960
+ });
961
+ if (!fresh) {
962
+ return;
963
+ }
964
+ // The version changed because another window sent or scheduled it - that message isn't ours to delete.
965
+ if (!isStillDraft(fresh, current.folderUid)) {
966
+ throw new ApiRequestError(NO_LONGER_A_DRAFT_MESSAGE, 409);
967
+ }
968
+ await deleteMessage(fresh.uid, fresh.version);
969
+ }
970
+ }
971
+
972
+ /**
973
+ * Discards the window's draft and closes it. With nothing the user would lose (a blank draft) it closes
974
+ * straight away and deletes the draft in the background; otherwise it closes only once the draft is
975
+ * deleted, and a delete that fails keeps the window open with the error.
976
+ */
977
+ async function discardNow() {
978
+ finishedRef.current = true;
979
+ pendingSaveRef.current = false;
980
+ setClosePrompt(null);
981
+ setDiscardError(null);
982
+ const current = draft;
983
+ if (!current || !hasUserContent) {
984
+ if (current) {
985
+ void deleteDraft(current).catch(() => undefined);
986
+ }
987
+ onClose();
988
+ return;
989
+ }
990
+ setClosing(true);
991
+ try {
992
+ await deleteDraft(current);
993
+ } catch (err) {
994
+ finishedRef.current = false;
995
+ setClosing(false);
996
+ setDiscardError(`Couldn't discard this draft: ${err instanceof ApiRequestError ? err.message : "the server couldn't be reached."}`);
997
+ return;
998
+ }
999
+ onClose();
1000
+ }
1001
+
1002
+ /** "Discard draft": confirms first whenever there's anything the user would lose. */
1003
+ function handleDiscard() {
1004
+ if (hasUserContent) {
1005
+ setClosePrompt({ title: DISCARD_TITLE, message: "This permanently deletes this draft and everything you've written in it." });
1006
+ } else {
1007
+ void discardNow();
1008
+ }
1009
+ }
1010
+
1011
+ /** "Close": keeps the draft (saving any unsaved edits first, and closing only once that save succeeded) -
1012
+ * unless there's nothing in it worth keeping, or it can't be saved because it's really headed for encryption
1013
+ * (asked for, or applied by the loaded policy): that needs the same confirmation as a discard. Whatever is
1014
+ * *unknown* (settings loading or failed, a lookup pending) is not a reason to hold the window: it is saved like any
1015
+ * other message. A failed save keeps the window open with Discard / Keep editing. */
1016
+ async function handleClose() {
1017
+ if (!hasUserContent) {
1018
+ void discardNow();
1019
+ return;
1020
+ }
1021
+ if (encryptionDecided) {
1022
+ setClosePrompt({ title: DISCARD_TITLE, message: ENCRYPTED_CLOSE_MESSAGE });
1023
+ return;
1024
+ }
1025
+ if (!draft || !contentReady) {
1026
+ saveErrorRef.current = draftError ?? "the draft hasn't been created yet";
1027
+ showSaveFailedPrompt();
1028
+ return;
1029
+ }
1030
+ if (lastSavedRef.current !== `${draft.uid}:${contentKey}`) {
1031
+ setClosing(true);
1032
+ const outcome = await saveDraftNow();
1033
+ setClosing(false);
1034
+ if (outcome.skipped) {
1035
+ // It became a message that mustn't be saved as plaintext while waiting on an earlier save.
1036
+ setClosePrompt({ title: DISCARD_TITLE, message: ENCRYPTED_CLOSE_MESSAGE });
1037
+ return;
1038
+ }
1039
+ if (!outcome.message) {
1040
+ showSaveFailedPrompt();
1041
+ return;
1042
+ }
1043
+ }
1044
+ finishedRef.current = true;
1045
+ onClose();
1046
+ }
1047
+
1048
+ // A plain read from keySession.ts's module-level session store, not React state - see that module's
1049
+ // own doc comment. Cheap enough to read fresh on every render rather than caching in state.
1050
+ const unlockedKeys = mailboxUid ? getUnlockedKeys(mailboxUid) : undefined;
1051
+ const hasEnrolledSigningKey = !!findActivePublicKey(mailbox?.keys ?? [], "sign");
1052
+ const hasEnrolledEncryptionKey = !!findActivePublicKey(mailbox?.keys ?? [], "encrypt");
1053
+ // This mailbox has a real signing/encryption key on file, but this session hasn't unlocked it yet -
1054
+ // the sign/encrypt toggles below stay hidden until it has, so this is the only way to reach them
1055
+ // without first stumbling into Mail generally (which no longer force-prompts on its own - see
1056
+ // `MailShell`'s `blocking={false}`). `getUnlockedKeys()` is re-read as a plain module value above, so
1057
+ // bumping `unlockRefresh` (after a successful unlock, or on any key-session event for this mailbox -
1058
+ // see the `subscribeKeySession()` effect) is what makes this line (and the toggles it gates) reflect
1059
+ // it on the next render.
1060
+ const needsUnlockForCrypto = (hasEnrolledSigningKey || hasEnrolledEncryptionKey) && !unlockedKeys;
1061
+
1062
+ // Keys locking (idle timeout, logout elsewhere, ...) or unlocking from another window must update the
1063
+ // toggles/unlock affordance right away, not on whatever unrelated render happens next.
1064
+ useEffect(() => subscribeKeySession((event) => {
1065
+ if (event.mailboxUid === mailboxUid) {
1066
+ setUnlockRefresh((n) => n + 1);
1067
+ }
1068
+ }), [mailboxUid]);
1069
+
1070
+ useEffect(() => {
1071
+ offeredCryptoRef.current = {
1072
+ sign: offeredCryptoRef.current.sign || !!unlockedKeys?.signingPrivateKey,
1073
+ encrypt: offeredCryptoRef.current.encrypt || !!unlockedKeys?.encryptionPrivateKey,
1074
+ };
1075
+ });
1076
+
1077
+ // Autosave. "User content" is anything beyond what compose opened with (prefilled recipients/subject,
1078
+ // seeded signature/quote) - an untouched window has nothing worth saving or confirming a discard of.
1079
+ const contentKey = JSON.stringify([to, cc, bcc, subject, html]);
1080
+ const baselineKey = JSON.stringify([baselineTo ?? "", baselineCc ?? "", "", initialSubject ?? "", seededHtml ?? ""]);
1081
+ const hasUserContent = contentKey !== baselineKey || hasUploads;
1082
+ // Whether this message is *really* headed for encryption - `encryptionRequirement.ts` decides, and it fails open: the message is plain (its
1083
+ // draft saves, Close and Send work, nothing is shown) unless the user asked for encryption or the policy was loaded and applies it to every
1084
+ // recipient (whose keys were all looked up). What has not loaded, or failed to, is not held against the message.
1085
+ //
1086
+ // Transitions, when a later load turns a plain message into an encrypted one (the policy arrives, a slow lookup answers, a recipient is
1087
+ // added): (1) autosave stops at once (`autosaveSuppressed`); (2) a plaintext copy this window already saved is *replaced by an empty draft*
1088
+ // (`scrubSavedDraft()` below) so the plaintext doesn't sit on the server; (3) Close asks first ("Encrypted messages aren't saved as drafts");
1089
+ // (4) Send encrypts (or is refused, with the override, when it can't) - never silently plaintext. And back: when it stops being encrypted
1090
+ // (a recipient removed) autosave simply resumes.
1091
+ const currentAddresses = [...parseAddresses(to), ...parseAddresses(cc), ...parseAddresses(bcc)].map((r) => r.address);
1092
+ const currentStatuses = currentAddresses.map((address) => recipientStatuses[addressCacheKey(address)]);
1093
+ const hasEncryptionKey = !!unlockedKeys?.encryptionPrivateKey || hasEnrolledEncryptionKey || offeredCryptoRef.current.encrypt;
1094
+ const requirement = evaluateEncryptionRequirement({
1095
+ encryptRequested,
1096
+ policy: encryptionPolicy ?? undefined,
1097
+ mailboxLoaded: !!mailbox,
1098
+ hasEncryptionKey,
1099
+ recipients: currentStatuses,
1100
+ });
1101
+ const encryptionDecided = requirement.required;
1102
+ const autosaveSuppressed = encryptionDecided;
1103
+ const latestRef = useRef({
1104
+ draft, mailboxUid, mailbox, encryptionPolicy, to, cc, bcc, subject, html, attachments, requestReceipt, signEnabled, encryptRequested,
1105
+ statuses: currentStatuses, seededHtml, contentKey, saveStatus, hasUserContent, autosaveSuppressed, encryptionDecided,
1106
+ });
1107
+ latestRef.current = {
1108
+ draft, mailboxUid, mailbox, encryptionPolicy, to, cc, bcc, subject, html, attachments, requestReceipt, signEnabled, encryptRequested,
1109
+ statuses: currentStatuses, seededHtml, contentKey, saveStatus, hasUserContent, autosaveSuppressed, encryptionDecided,
1110
+ };
1111
+
1112
+ /** A message that turned out to need encryption after a plaintext copy of it was saved: the saved copy is replaced by an empty draft (the same
1113
+ * uid, so attachments and the folder are undisturbed), chained after any save still on the wire. Best effort - a failure is reported once. */
1114
+ function scrubSavedDraft(target: Message) {
1115
+ lastSavedRef.current = null;
1116
+ setSaveStatus("idle");
1117
+ const previous = saveInFlightRef.current;
1118
+ const scrub = (async (): Promise<Message | undefined> => {
1119
+ await previous;
1120
+ try {
1121
+ // Its answer (the new version) is what a later delete waits for through `saveInFlightRef`, like any save's.
1122
+ return await assembleDraft(target.uid, { to: [], cc: [], bcc: [], subject: "", html: "" });
1123
+ } catch {
1124
+ notify({
1125
+ id: `scrub-draft:${target.uid}`,
1126
+ kind: "warning",
1127
+ title: "An earlier draft copy is still saved",
1128
+ message: "This message needs encryption, but the copy saved before that was known couldn't be replaced. Discarding the draft removes it.",
1129
+ });
1130
+ return undefined;
1131
+ }
1132
+ })();
1133
+ saveInFlightRef.current = scrub;
1134
+ }
1135
+ // Only a message that was really saved (`lastSavedRef` names its draft) has a plaintext copy to replace.
1136
+ useEffect(() => {
1137
+ if (encryptionDecided && draft && lastSavedRef.current?.startsWith(`${draft.uid}:`)) {
1138
+ scrubSavedDraft(draft);
1139
+ }
1140
+ }, [encryptionDecided, draft?.uid]);
1141
+
1142
+ // Recipients a reply could only work out after this window opened (Reply All: whoever the original's headers name)
1143
+ // replace the ones it opened with - but only in a field the user hasn't touched, never over what they typed.
1144
+ useEffect(() => {
1145
+ if (!late) {
1146
+ return;
1147
+ }
1148
+ const current = latestRef.current;
1149
+ if (late.to !== undefined && current.to === (initialTo ?? "")) {
1150
+ setTo(late.to);
1151
+ }
1152
+ if (late.cc !== undefined && current.cc === (initialCc ?? "")) {
1153
+ setCc(late.cc);
1154
+ setShowCcBcc((shown) => shown || late.cc !== "");
1155
+ }
1156
+ }, [late]);
1157
+
1158
+ useEffect(() => {
1159
+ const due =
1160
+ !!draft &&
1161
+ contentReady &&
1162
+ !autosaveSuppressed &&
1163
+ hasUserContent &&
1164
+ lastSavedRef.current !== `${draft.uid}:${contentKey}`;
1165
+ pendingSaveRef.current = due;
1166
+ if (!due) {
1167
+ return;
1168
+ }
1169
+ const timer = setTimeout(() => void saveDraftNow(), autosaveDelayMs);
1170
+ return () => clearTimeout(timer);
1171
+ }, [draft, contentReady, autosaveSuppressed, hasUserContent, contentKey]);
1172
+
1173
+ // Unmounting with an edit still waiting on the debounce (e.g. the whole app shell unmounting) saves it
1174
+ // right away rather than losing it.
1175
+ useEffect(
1176
+ () => () => {
1177
+ if (pendingSaveRef.current && !finishedRef.current) {
1178
+ void saveDraftNow();
1179
+ }
1180
+ },
1181
+ [],
1182
+ );
1183
+
1184
+ /** Saves an edit still waiting on the debounce now, and resolves once that save - or one already on the
1185
+ * wire - has settled, to whether the window's content is saved. A save that failed keeps the window open
1186
+ * with Discard / Keep editing. A send clears `pendingSaveRef` before it starts, so this never saves mid-send. */
1187
+ async function flushPendingSave(): Promise<boolean> {
1188
+ if (pendingSaveRef.current && !finishedRef.current) {
1189
+ const outcome = await saveDraftNow();
1190
+ if (outcome.skipped) {
1191
+ // Not saved, but not a failure either: it may be headed for encryption (or was sent/discarded meanwhile).
1192
+ return finishedRef.current;
1193
+ }
1194
+ if (!outcome.message) {
1195
+ showSaveFailedPrompt();
1196
+ }
1197
+ return !!outcome.message;
1198
+ }
1199
+ await saveInFlightRef.current;
1200
+ const latest = latestRef.current;
1201
+ if (finishedRef.current || !latest.hasUserContent || (!!latest.draft && lastSavedRef.current === `${latest.draft.uid}:${latest.contentKey}`)) {
1202
+ return true;
1203
+ }
1204
+ // Unsaved because the last save failed (rather than, say, an encrypted message never being saved).
1205
+ if (saveErrorRef.current) {
1206
+ showSaveFailedPrompt();
1207
+ }
1208
+ return false;
1209
+ }
1210
+
1211
+ // Sign Out (AppShell) waits for this before ending the session.
1212
+ useEffect(() => registerComposeFlush(flushPendingSave), []);
1213
+
1214
+ // Leaving the page (reload, closing the tab, following a link) with anything not saved: start a save that's
1215
+ // waiting on the debounce straight away and ask the browser to confirm, so the last couple of seconds of
1216
+ // typing (or content that can't be saved as a draft, or failed to) aren't lost silently. Never while signing
1217
+ // out - that navigation must not be cancellable.
1218
+ useEffect(() => {
1219
+ function handleBeforeUnload(event: BeforeUnloadEvent) {
1220
+ if (finishedRef.current || isSigningOut()) {
1221
+ return;
1222
+ }
1223
+ const latest = latestRef.current;
1224
+ const unsaved =
1225
+ pendingSaveRef.current ||
1226
+ latest.saveStatus === "saving" ||
1227
+ (latest.hasUserContent && lastSavedRef.current !== `${latest.draft?.uid}:${latest.contentKey}`);
1228
+ if (!unsaved) {
1229
+ return;
1230
+ }
1231
+ void flushPendingSave();
1232
+ event.preventDefault();
1233
+ event.returnValue = "";
1234
+ }
1235
+ window.addEventListener("beforeunload", handleBeforeUnload);
1236
+ return () => window.removeEventListener("beforeunload", handleBeforeUnload);
1237
+ }, []);
1238
+
1239
+ // Where the caret starts, once per session: a reply/forward in the body (at its top), a new message in To - or,
1240
+ // with To already filled in (e.g. Contacts' "Email"), in Subject. Minimizing unmounts the fields, so restoring a
1241
+ // window must not move the caret there again.
1242
+ const isReplyOrForward = initialQuotedHtml !== undefined || !!quotePending || !!resume;
1243
+ const fieldsFocusedRef = useRef(false);
1244
+ const bodyFocusedRef = useRef(false);
1245
+ const focusToOnMount = !isReplyOrForward && !initialTo && !fieldsFocusedRef.current;
1246
+ const focusSubjectOnMount = !isReplyOrForward && !!initialTo && !fieldsFocusedRef.current;
1247
+ const focusBodyOnMount = isReplyOrForward && !bodyFocusedRef.current;
1248
+
1249
+ // The editor serializes the seeded body its own way (see `RichTextEditor`'s `onInitialized`). While the body is
1250
+ // still exactly what compose seeded, that serialization becomes the baseline - so an untouched reply or signature
1251
+ // isn't mistaken for an edit (and autosaved) just because the editor was focused or clicked.
1252
+ /** The quote has been added: unless the reader has typed something already, that is still exactly what compose seeded. */
1253
+ function handleQuoteAppended(normalized: string) {
1254
+ const latest = latestRef.current;
1255
+ if (latest.html === latest.seededHtml) {
1256
+ setHtml(normalized);
1257
+ setSeededHtml(normalized);
1258
+ }
1259
+ }
1260
+ function handleEditorInitialized(normalized: string) {
1261
+ markComposePhase(id, "editor");
1262
+ const latest = latestRef.current;
1263
+ if (latest.html === latest.seededHtml && normalized !== latest.html) {
1264
+ setHtml(normalized);
1265
+ setSeededHtml(normalized);
1266
+ }
1267
+ }
1268
+ useEffect(() => {
1269
+ if (!minimized) {
1270
+ fieldsFocusedRef.current = true;
1271
+ bodyFocusedRef.current ||= contentReady;
1272
+ }
1273
+ }, [minimized, contentReady]);
1274
+
1275
+ // Keyboard shortcuts, active while the focus is inside this window (`container`; the scope attribute on its root is what tells the
1276
+ // dispatcher the focus is in a compose window at all). They do what the Send and Close buttons and autosave do, under the same conditions -
1277
+ // a shortcut pressed while its button would be disabled is consumed and does nothing.
1278
+ // Send never waits for the encryption settings to load (fail open, see `encryptionRequirement.ts`); it only needs the draft to exist. Pressed
1279
+ // while an earlier press is still being handled it does nothing (`submit()` guards that itself).
1280
+ const canSend = !!draft && !closing && !waitingForUploads;
1281
+ useShortcut(SHORTCUTS.compose.send, () => void (canSend && submit(false)), { container: windowRef });
1282
+ useShortcut(
1283
+ SHORTCUTS.compose.saveDraft,
1284
+ () => {
1285
+ // Autosave's own conditions: never a draft that must not be stored as plaintext.
1286
+ if (draft && contentReady && !closing && !autosaveSuppressed && hasUserContent) {
1287
+ void saveDraftNow();
1288
+ }
1289
+ },
1290
+ { container: windowRef },
1291
+ );
1292
+ useShortcut(
1293
+ SHORTCUTS.compose.close,
1294
+ () => {
1295
+ if (!closing) {
1296
+ void handleClose();
1297
+ }
1298
+ },
1299
+ { container: windowRef },
1300
+ );
1301
+ useShortcut(SHORTCUTS.compose.create, () => openCompose({ mailboxUid }), { container: windowRef });
1302
+
1303
+ const title = subject.trim() || "New Message";
1304
+ const titleId = `compose-title-${id}`;
1305
+
1306
+ const discardModal = (
1307
+ <Modal open={closePrompt !== null} onClose={() => setClosePrompt(null)} title={closePrompt?.title ?? DISCARD_TITLE}>
1308
+ <p className="text-sm text-text-muted mb-4">{closePrompt?.message}</p>
1309
+ <div className="flex gap-3">
1310
+ <Button type="button" onClick={() => void discardNow()} disabled={closing} className="!w-auto">
1311
+ Discard
1312
+ </Button>
1313
+ <Button type="button" variant="secondary" onClick={() => setClosePrompt(null)} className="!w-auto">
1314
+ Keep editing
1315
+ </Button>
1316
+ </div>
1317
+ </Modal>
1318
+ );
1319
+
1320
+ if (minimized) {
1321
+ return (
1322
+ <>
1323
+ <div role="dialog" aria-label={title} className="w-64 shrink-0 bg-surface border border-border border-b-0 rounded-t-md shadow-modal">
1324
+ <div
1325
+ className="h-10 flex items-center justify-between gap-2 px-3 rounded-t-md bg-primary-darker text-white cursor-pointer"
1326
+ onClick={onToggleMinimize}
1327
+ >
1328
+ <span className="text-sm font-medium truncate">{title}</span>
1329
+ <div className="flex items-center gap-0.5" onClick={(e) => e.stopPropagation()}>
1330
+ <HeaderButton label="Restore" onClick={onToggleMinimize} icon={HiOutlineArrowsPointingOut} />
1331
+ <HeaderButton label="Discard draft" onClick={handleDiscard} icon={HiOutlineXMark} disabled={closing} />
1332
+ </div>
1333
+ </div>
1334
+ </div>
1335
+ {discardModal}
1336
+ </>
1337
+ );
1338
+ }
1339
+
1340
+ return (
1341
+ <>
1342
+ <div
1343
+ ref={windowRef}
1344
+ role="dialog"
1345
+ data-shortcut-scope="compose"
1346
+ aria-labelledby={titleId}
1347
+ style={!isMobile && manualSize ? { width: manualSize.width, height: manualSize.height } : undefined}
1348
+ className={[
1349
+ "shrink-0 flex flex-col bg-surface border border-border shadow-modal overflow-hidden",
1350
+ // `fixed` and `relative` may not both be on the element: Tailwind emits `.relative` after `.fixed`, so it wins and the
1351
+ // sheet sat in the flow of the little fixed container the windows are stacked in instead of covering the screen.
1352
+ isMobile
1353
+ ? "fixed inset-0 w-full h-full rounded-none border-0"
1354
+ : ["relative border-b-0 rounded-t-md", manualSize ? "" : expanded ? "w-[720px] h-[85vh]" : "w-[480px] h-[520px]"].join(" "),
1355
+ ].join(" ")}
1356
+ >
1357
+ {!isMobile && (
1358
+ <>
1359
+ <div
1360
+ onPointerDown={handleResizeStart("top")}
1361
+ aria-hidden="true"
1362
+ className="absolute top-0 left-0 right-0 h-1.5 cursor-ns-resize z-20"
1363
+ />
1364
+ <div
1365
+ onPointerDown={handleResizeStart("left")}
1366
+ aria-hidden="true"
1367
+ className="absolute top-0 left-0 bottom-0 w-1.5 cursor-ew-resize z-20"
1368
+ />
1369
+ <div
1370
+ onPointerDown={handleResizeStart("corner")}
1371
+ role="separator"
1372
+ aria-label="Resize"
1373
+ className="absolute top-0 left-0 w-3 h-3 cursor-nwse-resize z-30"
1374
+ />
1375
+ </>
1376
+ )}
1377
+
1378
+ <div
1379
+ className="h-10 shrink-0 flex items-center justify-between gap-2 px-3 bg-primary-darker text-white cursor-pointer"
1380
+ onClick={onToggleMinimize}
1381
+ >
1382
+ <span id={titleId} className="text-sm font-medium truncate">
1383
+ {title}
1384
+ </span>
1385
+ <div className="flex items-center gap-0.5" onClick={(e) => e.stopPropagation()}>
1386
+ <HeaderButton label="Minimize" onClick={onToggleMinimize} icon={HiOutlineMinus} />
1387
+ {!isMobile && (
1388
+ <HeaderButton
1389
+ label={expanded ? "Collapse" : "Expand"}
1390
+ onClick={toggleExpanded}
1391
+ icon={expanded ? HiOutlineArrowsPointingIn : HiOutlineArrowsPointingOut}
1392
+ />
1393
+ )}
1394
+ <HeaderButton label="Close" onClick={() => void handleClose()} icon={HiOutlineXMark} disabled={closing} shortcut={SHORTCUTS.compose.close} />
1395
+ </div>
1396
+ </div>
1397
+
1398
+ <div className="flex-1 min-h-0 flex flex-col">
1399
+ {(folderError || draftError || sendError || attachError || discardError) && (
1400
+ // Scrolls inside the window when it is tall, instead of pushing the editor and the Send button out of the window's
1401
+ // fixed height, where they can't be reached.
1402
+ <div className="px-3 pt-2 shrink-0 max-h-[45%] overflow-y-auto">
1403
+ {folderError && <Alert>{folderError}</Alert>}
1404
+ {draftError && <Alert>{draftError}</Alert>}
1405
+ {sendError && <Alert>{sendError}</Alert>}
1406
+ {attachError && <Alert>{attachError}</Alert>}
1407
+ {discardError && <Alert>{discardError}</Alert>}
1408
+ </div>
1409
+ )}
1410
+
1411
+ {securityBlock && (
1412
+ <div className="px-3 pt-2">
1413
+ <Alert>
1414
+ <p className="mb-2">{securityBlock.message}</p>
1415
+ <Button type="button" onClick={() => void submit(true, blockedScheduleIso)}>
1416
+ {securityBlock.overrideLabel}
1417
+ </Button>
1418
+ </Alert>
1419
+ </div>
1420
+ )}
1421
+
1422
+ {fromOptions.length > 1 && (
1423
+ <div className={FIELD_ROW}>
1424
+ <label htmlFor={`compose-from-${id}`} className="text-xs text-text-muted shrink-0">
1425
+ From
1426
+ </label>
1427
+ <select
1428
+ id={`compose-from-${id}`}
1429
+ className={`${FIELD_INPUT} disabled:opacity-55`}
1430
+ // Two or more options only exist once the mailboxes have loaded, and the same answer that lets them list
1431
+ // (one that isn't known to be view-only) is what picks the default sender, so a sender is always chosen by now.
1432
+ value={mailboxUid}
1433
+ disabled={hasUploads}
1434
+ title={hasUploads ? "The sender can't be changed after adding attachments or images." : undefined}
1435
+ onChange={(e) => handleFromChange(e.target.value)}
1436
+ >
1437
+ {fromOptions.map((mb) => (
1438
+ <option key={mb.uid} value={mb.uid}>
1439
+ {mb.displayName ? `${mb.displayName} <${mb.primarySmtpAddress}>` : mb.primarySmtpAddress}
1440
+ {mb.ownerUserUid ? "" : " (shared)"}
1441
+ </option>
1442
+ ))}
1443
+ </select>
1444
+ </div>
1445
+ )}
1446
+
1447
+ <div className={FIELD_ROW}>
1448
+ <label htmlFor={`compose-to-${id}`} className="text-xs text-text-muted shrink-0">
1449
+ To
1450
+ </label>
1451
+ <RecipientInput
1452
+ id={`compose-to-${id}`}
1453
+ label="To"
1454
+ value={to}
1455
+ mailboxUid={mailboxUid}
1456
+ onChange={setTo}
1457
+ onBlur={(value) => checkRecipientDiscovery(parseAddresses(value))}
1458
+ onCommit={(value) => checkRecipientDiscovery(parseAddresses(value))}
1459
+ autoFocus={focusToOnMount}
1460
+ />
1461
+ {!showCcBcc && (
1462
+ <button
1463
+ type="button"
1464
+ onClick={() => setShowCcBcc(true)}
1465
+ className="text-xs text-text-muted hover:text-text shrink-0"
1466
+ >
1467
+ Cc Bcc
1468
+ </button>
1469
+ )}
1470
+ </div>
1471
+
1472
+ {showCcBcc && (
1473
+ <>
1474
+ <div className={FIELD_ROW}>
1475
+ <label htmlFor={`compose-cc-${id}`} className="text-xs text-text-muted shrink-0">
1476
+ Cc
1477
+ </label>
1478
+ <RecipientInput
1479
+ id={`compose-cc-${id}`}
1480
+ label="Cc"
1481
+ value={cc}
1482
+ mailboxUid={mailboxUid}
1483
+ onChange={setCc}
1484
+ onBlur={(value) => checkRecipientDiscovery(parseAddresses(value))}
1485
+ onCommit={(value) => checkRecipientDiscovery(parseAddresses(value))}
1486
+ />
1487
+ </div>
1488
+ <div className={FIELD_ROW}>
1489
+ <label htmlFor={`compose-bcc-${id}`} className="text-xs text-text-muted shrink-0">
1490
+ Bcc
1491
+ </label>
1492
+ <RecipientInput
1493
+ id={`compose-bcc-${id}`}
1494
+ label="Bcc"
1495
+ value={bcc}
1496
+ mailboxUid={mailboxUid}
1497
+ onChange={setBcc}
1498
+ onBlur={(value) => checkRecipientDiscovery(parseAddresses(value))}
1499
+ onCommit={(value) => checkRecipientDiscovery(parseAddresses(value))}
1500
+ />
1501
+ </div>
1502
+ </>
1503
+ )}
1504
+
1505
+ {(() => {
1506
+ // De-duplicated by the same normalized key `recipientStatuses` itself is keyed by - two
1507
+ // fields (or one field twice) naming the same mailbox in different casing now resolve to
1508
+ // one shared status object (see `addressCacheKey()`'s own doc comment), so without this
1509
+ // the list below would render - and React would warn about - two `<li key=...>`s sharing
1510
+ // the exact same key.
1511
+ const seenKeys = new Set<string>();
1512
+ const knownRecipients = [...parseAddresses(to), ...parseAddresses(cc), ...parseAddresses(bcc)]
1513
+ .filter((r) => {
1514
+ const key = addressCacheKey(r.address);
1515
+ if (seenKeys.has(key)) {
1516
+ return false;
1517
+ }
1518
+ seenKeys.add(key);
1519
+ return true;
1520
+ })
1521
+ .map((r) => recipientStatuses[addressCacheKey(r.address)])
1522
+ .filter((status): status is RecipientEncryptionStatus => !!status);
1523
+ if (knownRecipients.length === 0) {
1524
+ return null;
1525
+ }
1526
+ return (
1527
+ <ul className="flex flex-wrap gap-1.5 px-3 pt-1.5" aria-label="Recipient encryption availability">
1528
+ {knownRecipients.map((status) => (
1529
+ <li
1530
+ key={status.address}
1531
+ className={`text-xs font-medium py-0.5 px-2 rounded-pill ${
1532
+ status.canEncrypt ? "bg-primary/10 text-primary-dark" : "bg-surface-alt text-text-muted"
1533
+ }`}
1534
+ >
1535
+ {status.address} {status.canEncrypt ? "supports encryption" : "no encryption key found"}
1536
+ </li>
1537
+ ))}
1538
+ </ul>
1539
+ );
1540
+ })()}
1541
+
1542
+ <div className={FIELD_ROW}>
1543
+ <input
1544
+ aria-label="Subject"
1545
+ type="text"
1546
+ placeholder="Subject"
1547
+ className={FIELD_INPUT}
1548
+ value={subject}
1549
+ autoFocus={focusSubjectOnMount}
1550
+ onChange={(e) => setSubject(e.target.value)}
1551
+ />
1552
+ </div>
1553
+
1554
+ <div className="flex-1 min-h-0 p-2">
1555
+ {contentReady && (
1556
+ <RichTextEditor
1557
+ appendHtml={lateQuoteHtml}
1558
+ onAppended={handleQuoteAppended}
1559
+ value={html}
1560
+ onChange={setHtml}
1561
+ fill
1562
+ onUploadImage={handleUploadImage}
1563
+ autoFocusStart={focusBodyOnMount}
1564
+ onInitialized={handleEditorInitialized}
1565
+ />
1566
+ )}
1567
+ </div>
1568
+
1569
+ {quotePending && (
1570
+ <p role="status" className="px-3 pb-1 text-xs text-text-muted">
1571
+ Loading the original message&hellip;
1572
+ </p>
1573
+ )}
1574
+
1575
+ {attachments.length > 0 && (
1576
+ <ul className="flex flex-wrap gap-2 px-3 pb-2">
1577
+ {attachments.map((attachment) => (
1578
+ <li key={attachment.uid} className="text-xs font-medium py-1 px-2.5 rounded-pill bg-surface-alt text-text-muted">
1579
+ {attachment.filename}
1580
+ </li>
1581
+ ))}
1582
+ </ul>
1583
+ )}
1584
+
1585
+ <label className="flex items-center gap-1.5 px-3 pb-1 text-xs text-text-muted">
1586
+ <input type="checkbox" checked={requestReceipt} onChange={(e) => setRequestReceipt(e.target.checked)} />
1587
+ Request a read receipt
1588
+ </label>
1589
+
1590
+ {needsUnlockForCrypto && (
1591
+ <div className="px-3 pb-1">
1592
+ <button
1593
+ type="button"
1594
+ onClick={handleUnlockForCrypto}
1595
+ className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
1596
+ >
1597
+ <HiOutlineLockClosed size={12} aria-hidden="true" />
1598
+ Unlock to sign or encrypt this message
1599
+ </button>
1600
+ </div>
1601
+ )}
1602
+
1603
+ {/* Only rendered once this session actually has a usable signing/encryption key - see
1604
+ `sendJob.ts`'s signing path for why signing rarely shows today (no signing
1605
+ certificate exists until RFC 8823 ACME enrollment lands). */}
1606
+ {unlockedKeys?.signingPrivateKey && (
1607
+ <label className="flex items-center gap-1.5 px-3 pb-1 text-xs text-text-muted">
1608
+ <input type="checkbox" checked={signEnabled} onChange={(e) => setSignEnabled(e.target.checked)} />
1609
+ Digitally sign this message
1610
+ </label>
1611
+ )}
1612
+ {unlockedKeys?.encryptionPrivateKey && (
1613
+ <label className="flex items-center gap-1.5 px-3 pb-1 text-xs text-text-muted">
1614
+ <input type="checkbox" checked={encryptRequested} onChange={(e) => setEncryptRequested(e.target.checked)} />
1615
+ Encrypt this message
1616
+ </label>
1617
+ )}
1618
+
1619
+ <div className="shrink-0 flex items-center gap-1 px-3 py-2 border-t border-border">
1620
+ <div className="flex items-center rounded-pill bg-primary text-white overflow-hidden">
1621
+ <button
1622
+ type="button"
1623
+ onClick={() => void submit(false)}
1624
+ title={withHint("Send", SHORTCUTS.compose.send, keyEnv)}
1625
+ aria-keyshortcuts={ariaKeyShortcuts(SHORTCUTS.compose.send, keyEnv)}
1626
+ disabled={!draft || closing || waitingForUploads}
1627
+ className="py-1.5 pl-5 pr-3 font-semibold text-sm hover:not-disabled:bg-primary-dark disabled:opacity-55 disabled:cursor-not-allowed"
1628
+ >
1629
+ Send
1630
+ </button>
1631
+ <button
1632
+ ref={scheduleButtonRef}
1633
+ type="button"
1634
+ aria-label="Send later"
1635
+ aria-haspopup="true"
1636
+ aria-expanded={schedulePickerOpen}
1637
+ disabled={!draft || closing || waitingForUploads}
1638
+ onClick={() => setSchedulePickerOpen((o) => !o)}
1639
+ className="py-1.5 px-2 border-l border-white/30 hover:not-disabled:bg-primary-dark disabled:opacity-55 disabled:cursor-not-allowed"
1640
+ >
1641
+ <HiOutlineChevronDown size={14} />
1642
+ </button>
1643
+ </div>
1644
+ {schedulePickerOpen && (
1645
+ <ScheduleSendPicker
1646
+ anchorRef={scheduleButtonRef}
1647
+ onClose={() => setSchedulePickerOpen(false)}
1648
+ onSchedule={handleScheduleSend}
1649
+ />
1650
+ )}
1651
+
1652
+ <label
1653
+ aria-label="Attach files"
1654
+ title="Attach files"
1655
+ className="w-8 h-8 flex items-center justify-center rounded-full text-text-muted hover:bg-surface-alt hover:text-text cursor-pointer has-[:disabled]:opacity-40 has-[:disabled]:cursor-not-allowed"
1656
+ >
1657
+ <HiOutlinePaperClip size={18} />
1658
+ <input type="file" multiple disabled={!draft} onChange={handleFilesSelected} className="sr-only" />
1659
+ </label>
1660
+
1661
+ <span role="status" aria-live="polite" className="ml-auto text-xs text-text-muted">
1662
+ {waitingForUploads ? "Waiting for attachments to finish uploading…" : SAVE_STATUS_LABEL[saveStatus]}
1663
+ </span>
1664
+
1665
+ <button
1666
+ type="button"
1667
+ aria-label="Discard draft"
1668
+ title="Discard draft"
1669
+ onClick={handleDiscard}
1670
+ disabled={closing}
1671
+ className="w-8 h-8 flex items-center justify-center rounded-full text-text-muted hover:bg-surface-alt hover:text-text disabled:opacity-40 disabled:cursor-not-allowed"
1672
+ >
1673
+ <HiOutlineTrash size={18} />
1674
+ </button>
1675
+ </div>
1676
+ </div>
1677
+ </div>
1678
+ {discardModal}
1679
+ </>
1680
+ );
1681
+ }