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