@open-workspace/email 0.4.1 → 0.5.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 (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -1,12 +1,16 @@
1
+ import {
2
+ Dialog,
3
+ DialogPopup,
4
+ DialogPortal,
5
+ useConfirm,
6
+ } from "@open-workspace/core/ui";
1
7
  import {
2
8
  useEffect,
3
9
  useEffectEvent,
4
- useMemo,
5
10
  useRef,
6
11
  useState,
7
12
  useSyncExternalStore,
8
13
  } from "react";
9
- import type { DragEvent, RefObject } from "react";
10
14
  import { toast } from "sonner";
11
15
 
12
16
  import { forwardSubject } from "../../shared/mail";
@@ -18,29 +22,36 @@ import {
18
22
  } from "./compose-window-chrome";
19
23
  import { ComposerAttachmentList } from "./composer-attachment-list";
20
24
  import { ComposerEditor } from "./composer-editor";
21
- import type { ComposerContent, ComposerEditorHandle } from "./composer-editor";
25
+ import type { ComposerContent } from "./composer-editor";
26
+ import { sentBody } from "./composer-editor-document";
22
27
  import { ComposerRecipientFields } from "./composer-recipient-fields";
23
- import { validateComposerRecipients } from "./composer-recipients";
28
+ import {
29
+ draftRecipientAddresses,
30
+ recipientField,
31
+ validateComposerRecipients,
32
+ } from "./composer-recipients";
24
33
  import type { RecipientFieldValue } from "./composer-recipients";
25
- import { useComposerSession } from "./composer-session";
26
- import { isInlineComposerImage } from "./composer-upload-client";
34
+ import { notifyOutboundResult } from "./outbound-notification";
27
35
  import { ReplyToWarning } from "./reply-to-warning";
28
- import type { Mailbox, MessageDetail } from "./types";
29
- import { useComposeSubmission } from "./use-compose-submission";
36
+ import type { Mailbox } from "./types";
30
37
  import { useComposerAttachmentPreflight } from "./use-composer-attachment-preflight";
38
+ import { useComposerCore } from "./use-composer-core";
39
+ import {
40
+ useComposerLeaveCheck,
41
+ warnBeforeClosing,
42
+ } from "./use-composer-navigation";
43
+ import {
44
+ hasContentToSend,
45
+ useComposerSubmission,
46
+ } from "./use-composer-submission";
47
+ import { useDraftAutosave } from "./use-draft-autosave";
48
+ import type { DraftContent, ForwardSource, SavedDraft } from "./use-drafts";
31
49
 
32
50
  const EMPTY_RECIPIENT_FIELD: RecipientFieldValue = {
33
51
  recipients: [],
34
52
  input: "",
35
53
  };
36
54
 
37
- const EMPTY_CONTENT: ComposerContent = {
38
- bodyHtml: "",
39
- bodyText: "",
40
- inlineAssetIds: [],
41
- linkedAssetIds: [],
42
- };
43
-
44
55
  /** Below Tailwind's `sm`, the composer covers the screen. */
45
56
  const PHONE_QUERY = "(max-width: 639.98px)";
46
57
 
@@ -58,149 +69,97 @@ function usePhoneLayout() {
58
69
  }
59
70
 
60
71
  /**
61
- * Makes everything outside `element` inert: each sibling of the element and
62
- * of its ancestors up to <body>. Returns the undo. Elements that were inert
63
- * already are left alone.
72
+ * Where focus goes when the composer closes: what opened it, else a New
73
+ * message button on screen.
64
74
  */
65
- function inertOutside(element: HTMLElement) {
66
- const changed: HTMLElement[] = [];
67
-
68
- for (
69
- let node: HTMLElement | null = element;
70
- node && node !== document.body;
71
- node = node.parentElement
72
- ) {
73
- for (const sibling of node.parentElement?.children ?? []) {
74
- if (
75
- sibling === node ||
76
- !(sibling instanceof HTMLElement) ||
77
- sibling.inert
78
- ) {
79
- continue;
80
- }
81
-
82
- if (
83
- sibling instanceof HTMLScriptElement ||
84
- sibling instanceof HTMLStyleElement
85
- ) {
86
- continue;
87
- }
88
-
89
- sibling.inert = true;
90
- changed.push(sibling);
91
- }
92
- }
93
-
94
- return () => {
95
- for (const sibling of changed) sibling.inert = false;
96
- };
97
- }
98
-
99
- /**
100
- * On a phone the composer is a full-screen modal: the page behind is inert,
101
- * focus starts inside, Escape closes it (unless a list or popup inside is
102
- * open and takes the key), and focus goes back to what opened it. The
103
- * floating desktop window stays non-modal.
104
- */
105
- function useFullScreenComposer(
106
- section: RefObject<HTMLElement | null>,
107
- active: boolean,
108
- onEscape: () => void
109
- ) {
110
- const escape = useEffectEvent(onEscape);
111
- // What had focus before the composer opened, to go back to when it closes.
112
- const opener = useRef(document.activeElement);
113
- useEffect(() => {
114
- const element = section.current;
115
-
116
- if (!active || !element) return;
117
- const undo = inertOutside(element);
118
-
119
- if (!element.contains(document.activeElement)) element.focus();
120
-
121
- const onKeyDown = (event: KeyboardEvent) => {
122
- if (event.key !== "Escape" || event.defaultPrevented) return;
123
-
124
- if (
125
- event.target instanceof Element &&
126
- event.target.closest('[aria-expanded="true"]')
127
- ) {
128
- return;
129
- }
130
-
131
- event.preventDefault();
132
- escape();
133
- };
134
-
135
- element.addEventListener("keydown", onKeyDown);
136
-
137
- return () => {
138
- element.removeEventListener("keydown", onKeyDown);
139
- undo();
140
- // Once the composer is gone, focus would fall to <body>.
141
- const { current: returnTo } = opener;
142
-
143
- requestAnimationFrame(() => {
144
- const current = document.activeElement;
145
-
146
- if (
147
- (!current || current === document.body) &&
148
- returnTo instanceof HTMLElement &&
149
- returnTo.isConnected
150
- ) {
151
- returnTo.focus();
152
- }
153
- });
154
- };
155
- }, [section, active]);
75
+ function composerOpener(opener: Element | null) {
76
+ return [opener, ...document.querySelectorAll("[data-compose-opener]")].find(
77
+ (element): element is HTMLElement =>
78
+ element instanceof HTMLElement && element.checkVisibility()
79
+ );
156
80
  }
157
81
 
158
82
  export function ComposeWindow({
159
83
  mailbox,
160
84
  forwardedMessage,
85
+ draft,
86
+ draftId,
87
+ discarded,
161
88
  onClose,
162
89
  }: {
163
90
  mailbox: Mailbox;
164
- forwardedMessage?: Pick<
165
- MessageDetail,
166
- | "id"
167
- | "subject"
168
- | "fromAddress"
169
- | "fromName"
170
- | "preview"
171
- | "attachments"
172
- | "security"
173
- >;
174
- onClose: () => void;
91
+ forwardedMessage?: ForwardSource;
92
+ /** A saved draft to reopen. */
93
+ draft?: SavedDraft;
94
+ /** The id this composer's draft is saved under. */
95
+ draftId: string;
96
+ /** Its draft was discarded from the Drafts list. */
97
+ discarded: boolean;
98
+ /** It closed; `ended` when its draft is gone (sent or discarded), not just put away. */
99
+ onClose: (ended?: boolean) => void;
175
100
  }) {
176
- const form = useRef<HTMLFormElement>(null);
177
- const editor = useRef<ComposerEditorHandle>(null);
178
- const fileInput = useRef<HTMLInputElement>(null);
179
- const inlineFileInput = useRef<HTMLInputElement>(null);
180
- const [to, setTo] = useState<RecipientFieldValue>(EMPTY_RECIPIENT_FIELD);
181
- const [cc, setCc] = useState<RecipientFieldValue>(EMPTY_RECIPIENT_FIELD);
182
- const [bcc, setBcc] = useState<RecipientFieldValue>(EMPTY_RECIPIENT_FIELD);
183
- const [replyTo, setReplyTo] = useState("");
184
-
185
- const [subject, setSubject] = useState(() =>
186
- forwardedMessage ? forwardSubject(forwardedMessage.subject) : ""
101
+ const [to, setTo] = useState<RecipientFieldValue>(() =>
102
+ draft ? recipientField(draft.to) : EMPTY_RECIPIENT_FIELD
103
+ );
104
+
105
+ const [cc, setCc] = useState<RecipientFieldValue>(() =>
106
+ draft ? recipientField(draft.cc) : EMPTY_RECIPIENT_FIELD
107
+ );
108
+
109
+ const [bcc, setBcc] = useState<RecipientFieldValue>(() =>
110
+ draft ? recipientField(draft.bcc) : EMPTY_RECIPIENT_FIELD
111
+ );
112
+
113
+ const [replyTo, setReplyTo] = useState(draft?.replyTo ?? "");
114
+
115
+ const [subject, setSubject] = useState(
116
+ () =>
117
+ draft?.subject ??
118
+ (forwardedMessage ? forwardSubject(forwardedMessage.subject) : "")
187
119
  );
188
120
 
189
- const [content, setContent] = useState<ComposerContent>(EMPTY_CONTENT);
190
- const [documentAssetIds, setDocumentAssetIds] = useState<string[]>([]);
191
121
  const [minimized, setMinimized] = useState(false);
192
- const [dragging, setDragging] = useState(false);
193
- const section = useRef<HTMLElement>(null);
122
+ const section = useRef<HTMLDivElement>(null);
194
123
  const minimizeButton = useRef<HTMLButtonElement>(null);
195
124
  const restoreButton = useRef<HTMLButtonElement>(null);
196
- // Minimizing moves focus to Restore, and restoring back to Minimize.
197
- const focusAfterToggle = useRef(false);
125
+ // What had focus as the composer opened, to go back to when it closes.
126
+ const opener = useRef(document.activeElement);
198
127
  const phone = usePhoneLayout();
199
128
 
200
- const { session, snapshot } = useComposerSession(
201
- mailbox.id,
202
- forwardedMessage?.attachments
203
- );
129
+ const core = useComposerCore({
130
+ mailbox,
131
+ draft,
132
+ signature: forwardedMessage ? "reply" : "new",
133
+ forwardedAttachments: forwardedMessage?.attachments.filter(
134
+ (file) =>
135
+ !draft?.forwardedAttachmentIds ||
136
+ draft.forwardedAttachmentIds.includes(file.id)
137
+ ),
138
+ });
139
+
140
+ const {
141
+ session,
142
+ snapshot,
143
+ editor,
144
+ activeAssets,
145
+ dropProps,
146
+ addFiles,
147
+ statusError,
148
+ attachmentListProps,
149
+ content: reportedContent,
150
+ editorProps,
151
+ fileInput,
152
+ form,
153
+ holdsOnlyOpening,
154
+ inlineFileInput,
155
+ keptAttachments,
156
+ limitError,
157
+ readContent,
158
+ uploadsError,
159
+ closeUploadError,
160
+ uploadsFailed,
161
+ uploadsPending,
162
+ } = core;
204
163
 
205
164
  const recipients = validateComposerRecipients({
206
165
  to,
@@ -209,112 +168,170 @@ export function ComposeWindow({
209
168
  replyTo,
210
169
  });
211
170
 
212
- const recipientCount = recipients.count;
213
-
214
- const documentAssetIdSet = useMemo(
215
- () => new Set(documentAssetIds),
216
- [documentAssetIds]
217
- );
171
+ const forwardedAttachmentIds = forwardedMessage
172
+ ? snapshot.forwardedAttachments.map((file) => file.id)
173
+ : undefined;
218
174
 
219
- const activeAssets = useMemo(
220
- () => snapshot.assets.filter((asset) => documentAssetIdSet.has(asset.id)),
221
- [documentAssetIdSet, snapshot.assets]
222
- );
223
-
224
- useComposerAttachmentPreflight(
225
- session,
175
+ const preflightContext = (content: ComposerContent) =>
226
176
  forwardedMessage
227
177
  ? {
228
- kind: "forward",
178
+ kind: "forward" as const,
229
179
  mailboxId: mailbox.id,
230
180
  sourceEmailId: forwardedMessage.id,
231
- bodyText: content.bodyText,
232
- bodyHtml: content.bodyHtml || undefined,
181
+ forwardedAttachmentIds,
182
+ ...sentBody(content),
233
183
  }
234
184
  : {
235
- kind: "compose",
185
+ kind: "compose" as const,
236
186
  mailboxId: mailbox.id,
237
187
  subject,
238
- bodyText: content.bodyText,
239
- bodyHtml: content.bodyHtml || undefined,
240
- },
188
+ ...sentBody(content),
189
+ };
190
+
191
+ useComposerAttachmentPreflight(
192
+ session,
193
+ preflightContext(reportedContent),
241
194
  activeAssets,
242
195
  snapshot.phase === "editing"
243
196
  );
244
- const linkedIds = snapshot.linkedAssetIds;
245
- const attachmentError = session.limitError();
246
197
 
247
- const uploadsPending = activeAssets.some(
248
- (asset) => asset.status === "uploading"
249
- );
198
+ const draftContent = (
199
+ body: ComposerContent,
200
+ attachments: DraftContent["attachments"]
201
+ ) =>
202
+ ({
203
+ kind: forwardedMessage ? "forward" : "compose",
204
+ // A mail app's reply kept here still names the message it answers.
205
+ sourceEmailId: forwardedMessage?.id ?? draft?.sourceEmailId ?? null,
206
+ forwardedAttachmentIds,
207
+ conversationId: forwardedMessage?.conversationId ?? null,
208
+ to: draftRecipientAddresses(to),
209
+ cc: draftRecipientAddresses(cc),
210
+ bcc: draftRecipientAddresses(bcc),
211
+ replyTo: replyTo.trim() || null,
212
+ subject,
213
+ bodyText: body.bodyText,
214
+ bodyHtml: body.bodyHtml,
215
+ // The editor's HTML, so the reopened editor puts the files back in place.
216
+ editorHtml: body.editorHtml,
217
+ attachments,
218
+ storedImages: body.storedImages,
219
+ }) satisfies DraftContent;
220
+
221
+ // The body holds only what it opened with (e.g. the signature), no files.
222
+ const untouched = (saved: Pick<DraftContent, "bodyText" | "attachments">) =>
223
+ !draft && holdsOnlyOpening(saved);
224
+
225
+ const autosave = useDraftAutosave({
226
+ mailboxId: mailbox.id,
227
+ session,
228
+ draftId,
229
+ restored: draft,
230
+ content: draftContent(reportedContent, keptAttachments()),
231
+ current: () => draftContent(readContent(), keptAttachments()),
232
+ blank: (saved) =>
233
+ !saved.to?.length &&
234
+ !saved.cc?.length &&
235
+ !saved.bcc?.length &&
236
+ (Boolean(forwardedMessage) || !subject.trim()) &&
237
+ snapshot.forwardedAttachments.length ===
238
+ (forwardedMessage?.attachments.length ?? 0) &&
239
+ untouched(saved),
240
+ editing: snapshot.phase === "editing" && mailbox.canSend,
241
+ });
250
242
 
251
- const uploadsFailed = activeAssets.some((asset) => asset.status === "error");
243
+ useComposerLeaveCheck(
244
+ "new",
245
+ () => core.closeUploadError ?? autosave.beforeLeave()
246
+ );
252
247
 
253
- const submission = useComposeSubmission({
248
+ const submission = useComposerSubmission({
254
249
  session,
255
250
  phase: snapshot.phase,
256
- mailbox,
257
- forwardedMessage,
258
- recipients,
259
- subject,
260
- content,
261
251
  editor,
262
- activeAssets,
263
- uploadLimitError: attachmentError,
264
- uploadsPending,
265
- uploadsFailed,
266
- onClose,
267
- });
252
+ validate: () => {
253
+ if (recipients.error) return recipients.error;
268
254
 
269
- const { busy } = submission;
270
- // Sending takes over the window: no drop target while it is busy.
271
- const dropTarget = dragging && !busy;
255
+ return (
256
+ uploadsError ?? (mailbox.canSend ? null : "This mailbox is read-only")
257
+ );
258
+ },
259
+ // A forward can go without a note.
260
+ missingText: (content) => {
261
+ const attachments = keptAttachments();
262
+
263
+ return forwardedMessage ||
264
+ hasContentToSend(content, attachments, () =>
265
+ untouched({ bodyText: content.bodyText, attachments })
266
+ )
267
+ ? null
268
+ : "Add text or a file to the message before sending";
269
+ },
270
+ context: preflightContext,
271
+ command: (content, uploadedAttachments) => {
272
+ const common = {
273
+ mailboxId: mailbox.id,
274
+ ...sentBody(content),
275
+ uploadedAttachments,
276
+ to: recipients.to,
277
+ cc: recipients.cc,
278
+ bcc: recipients.bcc,
279
+ replyTo: recipients.replyTo,
280
+ };
281
+
282
+ return forwardedMessage
283
+ ? {
284
+ ...common,
285
+ kind: "forward",
286
+ sourceEmailId: forwardedMessage.id,
287
+ forwardedAttachmentIds,
288
+ }
289
+ : { ...common, kind: "compose", subject };
290
+ },
291
+ draftForSubmission: autosave.forSubmission,
292
+ failureLabel: "Could not send message",
293
+ onSuccess: (result) => {
294
+ notifyOutboundResult(result, "message");
295
+ // Sent: the server deleted the draft.
296
+ autosave.ended();
297
+ onClose(true);
298
+ },
299
+ });
272
300
 
273
- function addInlineFiles(files: File[], position?: number) {
274
- const assets = session.addFiles(files, "inline");
301
+ // Discarded from the list, it closes with nothing left to save.
302
+ const closeDiscarded = useEffectEvent(() => {
303
+ autosave.ended();
304
+ session.close();
305
+ onClose(true);
306
+ });
275
307
 
276
- if (!assets) return;
277
- editor.current?.insertAssets(assets, position);
278
- }
308
+ useEffect(() => {
309
+ if (discarded) closeDiscarded();
310
+ }, [discarded]);
279
311
 
280
- function addAttachmentFiles(files: File[], position?: number) {
281
- const assets = session.addFiles(files, "attachment");
312
+ const { confirm, dialog: confirmDialog } = useConfirm();
313
+ const { busy } = submission;
282
314
 
283
- if (!assets) return;
284
- editor.current?.insertAssets(assets, position);
285
- }
315
+ const [closing, setClosing] = useState(false);
286
316
 
287
- function handleComposerDrop(event: DragEvent<HTMLFormElement>) {
288
- if (!event.dataTransfer.types.includes("Files")) return;
289
- event.preventDefault();
290
- setDragging(false);
317
+ async function closeComposer() {
318
+ if (closing) return;
291
319
 
292
- if (busy) return;
320
+ if (busy) {
321
+ toast.error("Wait for the message to finish sending");
293
322
 
294
- // ProseMirror owns editor-body drops so it can preserve the insertion
295
- // position. The form catches files dropped on every other composer area.
296
- if (
297
- event.target instanceof Element &&
298
- event.target.closest("[data-composer-editor-content]")
299
- ) {
300
323
  return;
301
324
  }
302
325
 
303
- const inline: File[] = [];
304
- const attachments: File[] = [];
326
+ if (warnBeforeClosing(closeUploadError)) return;
305
327
 
306
- for (const file of Array.from(event.dataTransfer.files)) {
307
- (isInlineComposerImage(file) ? inline : attachments).push(file);
308
- }
328
+ setClosing(true);
329
+ const saved = await autosave.flush();
309
330
 
310
- if (inline.length) addInlineFiles(inline);
331
+ if (!section.current) return;
311
332
 
312
- if (attachments.length) addAttachmentFiles(attachments);
313
- }
314
-
315
- function closeComposer() {
316
- if (busy) {
317
- toast.error("Wait for the message to finish sending");
333
+ if (!saved) {
334
+ setClosing(false);
318
335
 
319
336
  return;
320
337
  }
@@ -323,164 +340,169 @@ export function ComposeWindow({
323
340
  onClose();
324
341
  }
325
342
 
326
- function toggleMinimized(next: boolean) {
327
- focusAfterToggle.current = true;
328
- setMinimized(next);
329
- }
343
+ async function discardDraft() {
344
+ if (busy) return;
330
345
 
331
- useEffect(() => {
332
- if (!focusAfterToggle.current) return;
333
- focusAfterToggle.current = false;
334
- (minimized ? restoreButton : minimizeButton).current?.focus();
335
- }, [minimized]);
336
-
337
- useFullScreenComposer(section, phone && !minimized, closeComposer);
338
-
339
- if (minimized) {
340
- return (
341
- <MinimizedComposer
342
- subject={subject}
343
- restoreRef={restoreButton}
344
- onRestore={() => toggleMinimized(false)}
345
- onClose={closeComposer}
346
- />
347
- );
346
+ if (
347
+ !(await confirm({
348
+ title: "Discard this draft?",
349
+ description: "The message you wrote and its attachments are deleted.",
350
+ action: "Discard draft",
351
+ destructive: true,
352
+ }))
353
+ ) {
354
+ return;
355
+ }
356
+
357
+ try {
358
+ await autosave.discard();
359
+ } catch (error) {
360
+ toast.error(
361
+ error instanceof Error ? error.message : "Could not discard the draft"
362
+ );
363
+
364
+ return;
365
+ }
366
+
367
+ session.close();
368
+ onClose(true);
348
369
  }
349
370
 
371
+ // On a phone the composer covers the screen as a modal dialog; the
372
+ // desktop corner window is non-modal, and stays open as focus or clicks
373
+ // go elsewhere. Minimized, the dialog is closed but kept mounted (only
374
+ // hidden): its editor keeps what was typed (rebuilt, it would start from
375
+ // the draft as first opened). Restoring focuses Minimize (on opening, the
376
+ // To field has focus already); minimizing focuses Restore, and closing
377
+ // goes back to what opened the composer.
350
378
  return (
351
- <section
352
- ref={section}
353
- role="dialog"
354
- aria-label="New message"
355
- aria-modal={phone || undefined}
356
- tabIndex={-1}
357
- className="animate-rise bg-surface ring-border fixed inset-0 z-50 flex flex-col shadow-2xl ring-1 outline-none sm:inset-auto sm:right-6 sm:bottom-6 sm:h-[min(600px,calc(100dvh-3rem))] sm:w-[min(560px,calc(100vw-2.5rem))] sm:rounded-xl"
358
- >
359
- {/* oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- files can be dropped anywhere on the form */}
360
- <form
361
- ref={form}
362
- className="flex min-h-0 flex-1 flex-col"
363
- aria-busy={busy}
364
- onSubmit={submission.submit}
365
- onDragEnter={(event) => {
366
- if (!event.dataTransfer.types.includes("Files")) return;
367
- event.preventDefault();
368
-
369
- if (!busy) setDragging(true);
370
- }}
371
- onDragOver={(event) => {
372
- if (!event.dataTransfer.types.includes("Files")) return;
373
- event.preventDefault();
374
- event.dataTransfer.dropEffect = busy ? "none" : "copy";
375
- }}
376
- onDragLeave={(event) => {
377
- if (
378
- !(
379
- event.relatedTarget instanceof Node &&
380
- event.currentTarget.contains(event.relatedTarget)
381
- )
382
- ) {
383
- setDragging(false);
384
- }
385
- }}
386
- onDragEnd={() => setDragging(false)}
387
- onDrop={handleComposerDrop}
388
- >
389
- <ComposeWindowHeader
390
- from={mailbox.address}
391
- minimizeRef={minimizeButton}
392
- onMinimize={() => toggleMinimized(true)}
393
- onClose={closeComposer}
394
- />
395
-
396
- <ComposerRecipientFields
397
- mailboxId={mailbox.id}
398
- to={to}
399
- cc={cc}
400
- bcc={bcc}
401
- replyTo={replyTo}
379
+ <>
380
+ {minimized ? (
381
+ <MinimizedComposer
402
382
  subject={subject}
403
- subjectReadOnly={Boolean(forwardedMessage)}
404
- disabled={busy}
405
- onToChange={setTo}
406
- onCcChange={setCc}
407
- onBccChange={setBcc}
408
- onReplyToChange={setReplyTo}
409
- onSubjectChange={setSubject}
410
- />
411
-
412
- {forwardedMessage ? (
413
- <>
414
- <ForwardedMessageNotice message={forwardedMessage} />
415
- <ReplyToWarning
416
- message={forwardedMessage}
417
- recipients={[
418
- ...recipients.to,
419
- ...recipients.cc,
420
- ...recipients.bcc,
421
- ]}
422
- />
423
- </>
424
- ) : null}
425
-
426
- <ComposerEditor
427
- ref={editor}
428
- session={session}
429
- onChange={setContent}
430
- onAssetsChange={setDocumentAssetIds}
431
- onAddInlineFiles={(files, position) => {
432
- addInlineFiles(files, position);
433
- }}
434
- onAddAttachmentFiles={(files, position) => {
435
- addAttachmentFiles(files, position);
436
- }}
437
- onChooseInlineImage={() => inlineFileInput.current?.click()}
438
- onSubmitShortcut={() => form.current?.requestSubmit()}
439
- dragging={dropTarget}
440
- disabled={busy}
383
+ restoreRef={restoreButton}
384
+ onRestore={() => setMinimized(false)}
385
+ onClose={closeComposer}
441
386
  />
387
+ ) : null}
388
+ <Dialog
389
+ open={!minimized}
390
+ modal={phone}
391
+ disablePointerDismissal
392
+ onOpenChange={(open, details) => {
393
+ // Only Escape asks to close: in the window, not on the page beside it.
394
+ if (open) return;
442
395
 
443
- <ComposerAttachmentList
444
- uploads={activeAssets.filter(
445
- (asset) => !linkedIds.has(asset.id) || asset.status !== "uploaded"
446
- )}
447
- linkedIds={linkedIds}
448
- progress={session.progress}
449
- disabled={busy}
450
- onRemove={(asset) => {
451
- if (editor.current?.removeAsset(asset.id)) return;
452
- session.remove(asset.id);
453
- }}
454
- onRetry={(asset) => {
455
- void session.retry(asset.id);
456
- }}
457
- />
396
+ if (
397
+ !(details.event.target instanceof Node) ||
398
+ !section.current?.contains(details.event.target)
399
+ ) {
400
+ details.cancel();
458
401
 
459
- <ComposeWindowFooter
460
- fileInput={fileInput}
461
- inlineFileInput={inlineFileInput}
462
- uploads={activeAssets}
463
- error={
464
- attachmentError ??
465
- (activeAssets.length > 0 && snapshot.planError
466
- ? "Could not check attachment delivery"
467
- : null)
402
+ return;
468
403
  }
469
- sending={busy}
470
- sendDisabled={
471
- busy ||
472
- recipientCount === 0 ||
473
- !mailbox.canSend ||
474
- Boolean(attachmentError) ||
475
- uploadsPending ||
476
- uploadsFailed
477
- }
478
- onAddAttachments={addAttachmentFiles}
479
- onAddInlineImages={(files) => {
480
- addInlineFiles(files);
481
- }}
482
- />
483
- </form>
484
- </section>
404
+
405
+ void closeComposer();
406
+ }}
407
+ >
408
+ <DialogPortal keepMounted>
409
+ <DialogPopup
410
+ ref={section}
411
+ aria-label="New message"
412
+ aria-modal={phone || undefined}
413
+ initialFocus={minimizeButton}
414
+ finalFocus={() =>
415
+ minimized ? restoreButton.current : composerOpener(opener.current)
416
+ }
417
+ className="animate-rise bg-surface ring-border fixed inset-0 z-50 flex flex-col shadow-2xl ring-1 outline-none sm:inset-auto sm:right-6 sm:bottom-6 sm:h-[min(600px,calc(100dvh-3rem))] sm:w-[min(560px,calc(100vw-2.5rem))] sm:rounded-xl"
418
+ >
419
+ {confirmDialog}
420
+ {/* oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- files can be dropped anywhere on the form */}
421
+ <form
422
+ ref={form}
423
+ className="flex min-h-0 flex-1 flex-col"
424
+ inert={closing}
425
+ aria-busy={busy || closing}
426
+ onSubmit={(event) => {
427
+ event.preventDefault();
428
+ void submission.submit();
429
+ }}
430
+ onDragEnter={dropProps.onDragEnter}
431
+ onDragOver={dropProps.onDragOver}
432
+ onDragLeave={dropProps.onDragLeave}
433
+ onDragEnd={dropProps.onDragEnd}
434
+ onDrop={dropProps.onDrop}
435
+ >
436
+ <ComposeWindowHeader
437
+ from={draft?.fromAddress ?? mailbox.address}
438
+ minimizeRef={minimizeButton}
439
+ onMinimize={() => setMinimized(true)}
440
+ onDiscard={() => void discardDraft()}
441
+ onClose={closeComposer}
442
+ />
443
+
444
+ <ComposerRecipientFields
445
+ mailboxId={mailbox.id}
446
+ to={to}
447
+ cc={cc}
448
+ bcc={bcc}
449
+ replyToInvalid={recipients.issue === "replyTo"}
450
+ replyTo={replyTo}
451
+ subject={subject}
452
+ subjectReadOnly={Boolean(forwardedMessage)}
453
+ disabled={busy}
454
+ onToChange={setTo}
455
+ onCcChange={setCc}
456
+ onBccChange={setBcc}
457
+ onReplyToChange={setReplyTo}
458
+ onSubjectChange={setSubject}
459
+ />
460
+
461
+ {forwardedMessage ? (
462
+ <>
463
+ <ForwardedMessageNotice message={forwardedMessage} />
464
+ <ReplyToWarning
465
+ message={forwardedMessage}
466
+ recipients={[
467
+ ...recipients.to,
468
+ ...recipients.cc,
469
+ ...recipients.bcc,
470
+ ]}
471
+ />
472
+ </>
473
+ ) : null}
474
+
475
+ <ComposerEditor ref={editor} {...editorProps} />
476
+
477
+ <ComposerAttachmentList
478
+ {...attachmentListProps}
479
+ forwarded={snapshot.forwardedAttachments}
480
+ onRemoveForwarded={(id) =>
481
+ session.removeForwardedAttachment(id)
482
+ }
483
+ />
484
+
485
+ <ComposeWindowFooter
486
+ fileInput={fileInput}
487
+ inlineFileInput={inlineFileInput}
488
+ files={[...activeAssets, ...snapshot.forwardedAttachments]}
489
+ error={recipients.feedback ?? statusError}
490
+ sending={busy}
491
+ sendDisabled={
492
+ busy ||
493
+ Boolean(recipients.error) ||
494
+ !mailbox.canSend ||
495
+ Boolean(limitError) ||
496
+ uploadsPending ||
497
+ uploadsFailed
498
+ }
499
+ onAddAttachments={(files) => addFiles(files, "attachment")}
500
+ onAddInlineImages={(files) => addFiles(files, "inline")}
501
+ />
502
+ </form>
503
+ </DialogPopup>
504
+ </DialogPortal>
505
+ </Dialog>
506
+ </>
485
507
  );
486
508
  }