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