@open-workspace/email 0.4.2 → 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 (266) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,394 @@
1
+ import { ApiError } from "@open-workspace/core/ui";
2
+ import { useMutation, useQueryClient } from "@tanstack/react-query";
3
+ import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
4
+ import { toast } from "sonner";
5
+
6
+ import { composerBodyLimitError } from "../../shared/mail";
7
+ import type { ComposerSession } from "./composer-session";
8
+ import { applyMailboxChange } from "./mail-query-cache";
9
+ import { deleteDraft, forgetDrafts, putDraft } from "./use-drafts";
10
+ import type { DraftContent, SavedDraft } from "./use-drafts";
11
+
12
+ const CONFLICT_MESSAGE =
13
+ "This draft changed in another window. Copy your edits or discard this copy.";
14
+
15
+ const AUTOSAVE_DELAY_MS = 2000;
16
+
17
+ /**
18
+ * Saves a composer as a draft about two seconds after it stops changing, at
19
+ * once when it unmounts while still editing (closing, switching mailbox,
20
+ * leaving the conversation), and with `keepalive` when the page is hidden or
21
+ * goes away (closing the tab, reloading, locking the screen). While a change
22
+ * is unsaved or the last save failed, leaving the page asks first. Saves
23
+ * carry the version they were based on, so a second window on the same draft
24
+ * gets a conflict instead of overwriting it; after one, this composer stops
25
+ * saving.
26
+ */
27
+ export function useDraftAutosave({
28
+ mailboxId,
29
+ session,
30
+ draftId,
31
+ restored,
32
+ content,
33
+ current,
34
+ blank,
35
+ editing,
36
+ onSaved,
37
+ }: {
38
+ mailboxId: string;
39
+ /** Kept from discarding its uploads on close while a draft holds them. */
40
+ session: ComposerSession;
41
+ draftId: string;
42
+ /** The draft this composer reopened. */
43
+ restored?: Pick<SavedDraft, "version">;
44
+ /** What the composer holds as of its last reported change; a change starts the timer. */
45
+ content: DraftContent;
46
+ /**
47
+ * What the composer holds right now, read when saving: the editor reports
48
+ * changes after a short pause, so `content` can be behind it.
49
+ */
50
+ current: () => DraftContent;
51
+ /**
52
+ * Nothing worth keeping (an untouched composer, or one holding only the
53
+ * signature it opened with): it creates no draft.
54
+ */
55
+ blank: (content: DraftContent) => boolean;
56
+ /** True while the composer is editable and permitted to save. */
57
+ editing: boolean;
58
+ /** The draft was first saved: it now exists under `draftId`. */
59
+ onSaved?: (draftId: string) => void;
60
+ }) {
61
+ const client = useQueryClient();
62
+ const key = JSON.stringify(content);
63
+
64
+ const uncertain = useRef<DraftContent | null>(null);
65
+
66
+ const saved = useRef({
67
+ key,
68
+ version: restored?.version ?? 0,
69
+ stopped: false,
70
+ discarding: false,
71
+ submittedContent: "",
72
+ failed: false,
73
+ /** The last save started; saves of a draft run one after another. */
74
+ lastSave: Promise.resolve(),
75
+ });
76
+
77
+ // Saves read this render's values; the timer, page events and unmount run later.
78
+ const latest = useRef({
79
+ mailboxId,
80
+ content,
81
+ current,
82
+ key,
83
+ blank,
84
+ editing,
85
+ onSaved,
86
+ });
87
+
88
+ useLayoutEffect(() => {
89
+ latest.current = {
90
+ mailboxId,
91
+ content,
92
+ current,
93
+ key,
94
+ blank,
95
+ editing,
96
+ onSaved,
97
+ };
98
+ });
99
+
100
+ // Replay a write with an unknown outcome before using its version for the
101
+ // next edit, send or discard. A genuinely different revision still conflicts.
102
+ const persist = useCallback(
103
+ async (json: DraftContent, keepalive: boolean) => {
104
+ const state = saved.current;
105
+
106
+ async function write(attempt: DraftContent) {
107
+ const created = state.version === 0;
108
+ uncertain.current = attempt;
109
+ state.version = await putDraft(
110
+ client,
111
+ mailboxId,
112
+ draftId,
113
+ {
114
+ ...attempt,
115
+ expectedVersion: state.version,
116
+ },
117
+ keepalive
118
+ );
119
+ uncertain.current = null;
120
+
121
+ if (created) latest.current.onSaved?.(draftId);
122
+ }
123
+
124
+ try {
125
+ const previous = uncertain.current;
126
+
127
+ if (previous) await write(previous);
128
+
129
+ if (!previous || JSON.stringify(previous) !== JSON.stringify(json)) {
130
+ await write(json);
131
+ }
132
+
133
+ state.failed = false;
134
+ } catch (error) {
135
+ state.key = "";
136
+ state.failed = true;
137
+
138
+ if (error instanceof ApiError && error.status < 500) {
139
+ uncertain.current = null;
140
+
141
+ if (error.code === "DRAFT_CHANGED") state.stopped = true;
142
+ }
143
+
144
+ throw error;
145
+ }
146
+ },
147
+ [client, draftId, mailboxId]
148
+ );
149
+
150
+ // Saves of this draft run one at a time, in order (`scope`): each reads
151
+ // the version the one before it returned.
152
+ const { mutateAsync: autosave } = useMutation({
153
+ mutationKey: ["draft", draftId],
154
+ scope: { id: `draft:${draftId}` },
155
+ // Offline, a save fails and says so rather than waiting unseen.
156
+ networkMode: "always",
157
+ mutationFn: async ({
158
+ json,
159
+ keepalive,
160
+ }: {
161
+ json: DraftContent;
162
+ keepalive: boolean;
163
+ }) => {
164
+ if (!saved.current.stopped) await persist(json, keepalive);
165
+ },
166
+ onError: (error) =>
167
+ toast.error(
168
+ saved.current.stopped
169
+ ? "This draft was changed in another window, so it is no longer saved here"
170
+ : error instanceof ApiError
171
+ ? error.message
172
+ : "Could not save the draft"
173
+ ),
174
+ });
175
+
176
+ const saving = useCallback(
177
+ () => client.isMutating({ mutationKey: ["draft", draftId] }) > 0,
178
+ [client, draftId]
179
+ );
180
+
181
+ const save = useCallback(
182
+ (keepalive = false, closing = false) => {
183
+ const state = saved.current;
184
+ const { blank: isBlank } = latest.current;
185
+ const json = latest.current.current();
186
+ // Unmount can follow upload completion before the editor reports its new
187
+ // contents. Keep the files this write will copy until the Worker has them.
188
+ session.setRetainUploads(
189
+ Boolean(json.attachments?.length) && !state.stopped && !state.discarding
190
+ );
191
+ const jsonKey = JSON.stringify(json);
192
+
193
+ const { phase } = session.getSnapshot();
194
+
195
+ // Closing cancels preflight before a POST can start. Once submitting,
196
+ // only the delivery result can decide whether this draft should exist.
197
+ const canSave =
198
+ (latest.current.editing && phase === "editing") ||
199
+ (closing && phase === "preflighting");
200
+
201
+ if (
202
+ !canSave ||
203
+ state.stopped ||
204
+ state.discarding ||
205
+ (session.hasUnconfirmedSubmission() &&
206
+ jsonKey === state.submittedContent) ||
207
+ jsonKey === state.key ||
208
+ (!state.version && !saving() && !uncertain.current && isBlank(json))
209
+ ) {
210
+ return;
211
+ }
212
+
213
+ const limitError = composerBodyLimitError(json);
214
+
215
+ if (limitError) return limitError;
216
+
217
+ // Preflight waits for this save before it reads the version to send.
218
+ state.key = jsonKey;
219
+ state.lastSave = autosave({ json, keepalive }).catch(() => {});
220
+ },
221
+ [autosave, saving, session]
222
+ );
223
+
224
+ useEffect(() => {
225
+ if (!editing || key === saved.current.key) return;
226
+ const timer = setTimeout(() => save(), AUTOSAVE_DELAY_MS);
227
+
228
+ return () => clearTimeout(timer);
229
+ }, [key, editing, save]);
230
+
231
+ // The page going away or out of sight saves what the timer had not yet.
232
+ useEffect(() => {
233
+ function saveNow() {
234
+ if (latest.current.editing) save(true);
235
+ }
236
+
237
+ function saveIfHidden() {
238
+ if (document.visibilityState === "hidden") saveNow();
239
+ }
240
+
241
+ function confirmLeaving(event: BeforeUnloadEvent) {
242
+ const state = saved.current;
243
+
244
+ const unsaved =
245
+ latest.current.editing &&
246
+ (!state.stopped || state.failed) &&
247
+ (session
248
+ .documentAssets()
249
+ .some((asset) => asset.status !== "uploaded") ||
250
+ saving() ||
251
+ state.failed ||
252
+ (latest.current.key !== state.key &&
253
+ !(
254
+ state.version === 0 &&
255
+ latest.current.blank(latest.current.content)
256
+ )));
257
+
258
+ if (unsaved) event.preventDefault();
259
+ }
260
+
261
+ document.addEventListener("visibilitychange", saveIfHidden);
262
+ window.addEventListener("pagehide", saveNow);
263
+ window.addEventListener("beforeunload", confirmLeaving);
264
+
265
+ return () => {
266
+ document.removeEventListener("visibilitychange", saveIfHidden);
267
+ window.removeEventListener("pagehide", saveNow);
268
+ window.removeEventListener("beforeunload", confirmLeaving);
269
+ };
270
+ }, [save, saving, session]);
271
+
272
+ // Unmounting mid-edit saves what the timer had not yet; keepalive lets the
273
+ // request outlive a page that is closing.
274
+ useEffect(
275
+ () => () => {
276
+ save(true, true);
277
+ },
278
+ [save]
279
+ );
280
+
281
+ return {
282
+ beforeLeave() {
283
+ const state = saved.current;
284
+
285
+ if (state.stopped) return state.failed ? CONFLICT_MESSAGE : null;
286
+
287
+ const limitError = save();
288
+
289
+ if (limitError) return limitError;
290
+
291
+ return saving() ? state.lastSave.then(() => !state.failed) : null;
292
+ },
293
+ async forSubmission() {
294
+ const state = saved.current;
295
+ await state.lastSave;
296
+
297
+ if (uncertain.current) await persist(uncertain.current, false);
298
+
299
+ if (state.stopped) {
300
+ throw new Error("This draft changed. Reopen it before sending.");
301
+ }
302
+
303
+ const snapshot = latest.current.current();
304
+ const limitError = composerBodyLimitError(snapshot);
305
+
306
+ if (limitError) throw new Error(limitError);
307
+
308
+ if (state.failed) {
309
+ throw new Error("Could not confirm the last draft save. Try again.");
310
+ }
311
+
312
+ // A lost response may already have consumed the draft. An unchanged retry
313
+ // must reuse that attempt before an autosave can create another version.
314
+ state.submittedContent = JSON.stringify(snapshot);
315
+ const { version } = state;
316
+
317
+ return {
318
+ identity: version ? { draftId, draftVersion: version } : {},
319
+ recover: () =>
320
+ putDraft(client, mailboxId, draftId, {
321
+ ...snapshot,
322
+ expectedVersion: version,
323
+ }),
324
+ };
325
+ },
326
+ /** An explicit close must keep the editor open until its last write succeeds. */
327
+ async flush() {
328
+ const state = saved.current;
329
+
330
+ if (state.stopped) {
331
+ toast.error(CONFLICT_MESSAGE);
332
+
333
+ return false;
334
+ }
335
+
336
+ const limitError = save();
337
+
338
+ if (limitError) {
339
+ toast.error(limitError);
340
+
341
+ return false;
342
+ }
343
+
344
+ await state.lastSave;
345
+
346
+ return !state.failed && !state.stopped;
347
+ },
348
+ /** Stops saving and deletes the draft, if one was saved. */
349
+ discard: async () => {
350
+ const state = saved.current;
351
+ state.discarding = true;
352
+
353
+ await state.lastSave;
354
+
355
+ if (uncertain.current) {
356
+ try {
357
+ await persist(uncertain.current, false);
358
+ } catch (error) {
359
+ state.discarding = false;
360
+ throw error;
361
+ }
362
+ }
363
+
364
+ // Discarding a conflicted local copy leaves the other editor's revision intact.
365
+ if (state.stopped) {
366
+ session.setRetainUploads(false);
367
+ applyMailboxChange(client, mailboxId);
368
+
369
+ return;
370
+ }
371
+
372
+ try {
373
+ if (state.version) await deleteDraft(mailboxId, draftId, state.version);
374
+ } catch (error) {
375
+ state.discarding = false;
376
+
377
+ if (error instanceof ApiError && error.status === 409) {
378
+ state.stopped = true;
379
+ }
380
+
381
+ throw error;
382
+ }
383
+
384
+ state.stopped = true;
385
+ session.setRetainUploads(false);
386
+ forgetDrafts(client, mailboxId, [draftId]);
387
+ },
388
+ /** Stops saving once the draft is gone: sent (the server deleted it), or discarded from the list. */
389
+ ended: () => {
390
+ saved.current.stopped = true;
391
+ forgetDrafts(client, latest.current.mailboxId, [draftId]);
392
+ },
393
+ };
394
+ }
@@ -0,0 +1,194 @@
1
+ import { responseJson } from "@open-workspace/core/ui";
2
+ import type { SuccessfulResponse } from "@open-workspace/core/ui";
3
+ import { useMutation, useQueryClient } from "@tanstack/react-query";
4
+ import type { InfiniteData, QueryClient } from "@tanstack/react-query";
5
+
6
+ import { DRAFTS_FOLDER_ID } from "../../shared/folder-order";
7
+ import { mailApi } from "../lib/mail-api";
8
+ import { conversationQuery } from "./mail-queries";
9
+ import { applyMailboxChange } from "./mail-query-cache";
10
+
11
+ export type SavedDraft = SuccessfulResponse<
12
+ Awaited<ReturnType<(typeof mailApi.api.mail.drafts)[":id"]["$get"]>>
13
+ >["draft"];
14
+
15
+ /** What a composer saves: everything but the draft's identity and version. */
16
+ export type DraftContent = Omit<
17
+ Parameters<(typeof mailApi.api.mail.drafts)[":id"]["$put"]>[0]["json"],
18
+ "expectedVersion"
19
+ >;
20
+
21
+ /**
22
+ * Browsers refuse a keepalive request whose body is over 64 KiB; a larger
23
+ * draft is sent as an ordinary request, which a closing page may cut off.
24
+ */
25
+ const KEEPALIVE_MAX_BYTES = 60_000;
26
+
27
+ /** A new draft's id, chosen by the composer so its first save can be retried. */
28
+ export function newDraftId() {
29
+ return `drf_${crypto.randomUUID()}`;
30
+ }
31
+
32
+ export async function deleteDraft(
33
+ mailboxId: string,
34
+ draftId: string,
35
+ version: number
36
+ ) {
37
+ await responseJson(
38
+ await mailApi.api.mail.drafts[":id"].$delete({
39
+ param: { id: draftId },
40
+ query: { mailboxId, version: version.toString() },
41
+ })
42
+ );
43
+ }
44
+
45
+ /** Writes the frozen editor contents to its original mailbox and refreshes draft lists. */
46
+ export async function putDraft(
47
+ client: QueryClient,
48
+ mailboxId: string,
49
+ draftId: string,
50
+ body: DraftContent & { expectedVersion: number },
51
+ keepalive = false
52
+ ) {
53
+ const response = await mailApi.api.mail.drafts[":id"].$put(
54
+ { param: { id: draftId }, query: { mailboxId }, json: body },
55
+ {
56
+ init: {
57
+ keepalive:
58
+ keepalive &&
59
+ new TextEncoder().encode(JSON.stringify(body)).byteLength <
60
+ KEEPALIVE_MAX_BYTES,
61
+ },
62
+ }
63
+ );
64
+
65
+ const { draft } = await responseJson(response);
66
+
67
+ if (draft.kind === "reply" && draft.conversationId) {
68
+ const key = conversationQuery(mailboxId, draft.conversationId).queryKey;
69
+ client.setQueryData(
70
+ key,
71
+ (data) =>
72
+ data && {
73
+ ...data,
74
+ pages: data.pages.map((page, index) =>
75
+ index === 0 ? { ...page, replyDraft: draft } : page
76
+ ),
77
+ }
78
+ );
79
+ }
80
+
81
+ void client.invalidateQueries({
82
+ queryKey: ["conversations", mailboxId, DRAFTS_FOLDER_ID],
83
+ });
84
+
85
+ return draft.version;
86
+ }
87
+
88
+ /** Drops drafts from what this client shows, then refreshes the mailbox. */
89
+ export function forgetDrafts(
90
+ client: QueryClient,
91
+ mailboxId: string,
92
+ draftIds: readonly string[]
93
+ ) {
94
+ client.setQueriesData<InfiniteData<{ replyDraft: SavedDraft | null }>>(
95
+ { queryKey: ["conversation", mailboxId] },
96
+ (data) => {
97
+ const draft = data?.pages[0]?.replyDraft;
98
+
99
+ if (!data || !draft || !draftIds.includes(draft.id)) return undefined;
100
+
101
+ return {
102
+ ...data,
103
+ pages: data.pages.map((page, index) =>
104
+ index === 0 ? { ...page, replyDraft: null } : page
105
+ ),
106
+ };
107
+ }
108
+ );
109
+ applyMailboxChange(client, mailboxId);
110
+ }
111
+
112
+ /** Deletes drafts, e.g. those selected in Drafts. */
113
+ export function useDiscardDrafts() {
114
+ const client = useQueryClient();
115
+
116
+ return useMutation({
117
+ mutationFn: async ({
118
+ mailboxId,
119
+ drafts,
120
+ }: {
121
+ mailboxId: string;
122
+ drafts: Pick<SavedDraft, "id" | "version">[];
123
+ }) =>
124
+ responseJson(
125
+ await mailApi.api.mail.drafts.discard.$post({
126
+ query: { mailboxId },
127
+ json: { drafts },
128
+ })
129
+ ),
130
+ onSuccess: ({ discarded }, { mailboxId }) =>
131
+ forgetDrafts(client, mailboxId, discarded),
132
+ });
133
+ }
134
+
135
+ /** Deletes one draft, e.g. a conversation's reply draft being replaced. */
136
+ export function useDiscardDraft() {
137
+ const client = useQueryClient();
138
+
139
+ return async (mailboxId: string, draftId: string, version: number) => {
140
+ await deleteDraft(mailboxId, draftId, version);
141
+ forgetDrafts(client, mailboxId, [draftId]);
142
+ };
143
+ }
144
+
145
+ /** The source can move between conversations after a forward was saved. */
146
+ async function findDraftSource(
147
+ mailboxId: string,
148
+ draft: Pick<SavedDraft, "sourceEmailId">,
149
+ signal: AbortSignal
150
+ ) {
151
+ if (!draft.sourceEmailId) return undefined;
152
+
153
+ const response = await mailApi.api.mail.messages[":id"][
154
+ "forward-source"
155
+ ].$get(
156
+ {
157
+ param: { id: draft.sourceEmailId },
158
+ query: { mailboxId },
159
+ },
160
+ { init: { signal } }
161
+ );
162
+
163
+ if (response.status === 404) return undefined;
164
+
165
+ return (await responseJson(response)).message;
166
+ }
167
+
168
+ export type ForwardSource = NonNullable<
169
+ Awaited<ReturnType<typeof findDraftSource>>
170
+ >;
171
+
172
+ /** Read a fresh revision on each opening. A forwarded draft also needs its source message. */
173
+ export async function loadComposerDraft(
174
+ mailboxId: string,
175
+ id: string,
176
+ signal: AbortSignal
177
+ ) {
178
+ const response = await mailApi.api.mail.drafts[":id"].$get(
179
+ { param: { id }, query: { mailboxId } },
180
+ { init: { signal } }
181
+ );
182
+
183
+ if (response.status === 404) return null;
184
+ const { draft } = await responseJson(response);
185
+
186
+ if (draft.kind !== "forward") return { draft };
187
+ const forwarded = await findDraftSource(mailboxId, draft, signal);
188
+
189
+ if (!forwarded) {
190
+ throw new Error("The forwarded message is no longer available");
191
+ }
192
+
193
+ return { draft, forwarded };
194
+ }