@open-workspace/email 0.4.2 → 0.5.1

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 (268) 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-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,120 @@
1
+ import {
2
+ createContext,
3
+ useContext,
4
+ useEffect,
5
+ useLayoutEffect,
6
+ useRef,
7
+ } from "react";
8
+ import { useBlocker } from "react-router";
9
+ import { toast } from "sonner";
10
+
11
+ import { parseMailPath } from "../../shared/mail-path";
12
+ import { composeDraftId } from "./mail-search-params";
13
+
14
+ type Editor = "new" | "reply";
15
+
16
+ type LeaveCheck = () => string | Promise<boolean> | null;
17
+
18
+ type RegisterCheck = (editor: Editor, check: LeaveCheck | null) => void;
19
+
20
+ export const ComposerLeaveChecks = createContext<RegisterCheck | null>(null);
21
+
22
+ export function useComposerLeaveCheck(editor: Editor, check: LeaveCheck) {
23
+ const register = useContext(ComposerLeaveChecks);
24
+
25
+ useLayoutEffect(() => {
26
+ register?.(editor, check);
27
+
28
+ return () => register?.(editor, null);
29
+ }, [editor, check, register]);
30
+ }
31
+
32
+ export function warnBeforeClosing(error: string | null) {
33
+ if (!error) return false;
34
+ toast.error(error);
35
+
36
+ return true;
37
+ }
38
+
39
+ // Recheck after a write: the user can keep typing or attach a file while it runs.
40
+ const readyToLeave: (checks: LeaveCheck[]) => boolean | Promise<boolean> = (
41
+ checks
42
+ ) => {
43
+ const results = checks.map((check) => check());
44
+
45
+ for (const result of results) {
46
+ if (!(result instanceof Promise) && warnBeforeClosing(result)) return false;
47
+ }
48
+
49
+ if (results.some((result) => result instanceof Promise)) {
50
+ return Promise.all(results).then(
51
+ (saved) =>
52
+ saved.every((result) => result !== false) && readyToLeave(checks)
53
+ );
54
+ }
55
+
56
+ return true;
57
+ };
58
+
59
+ /** A reply and a compose window can be open together. React Router takes one blocker. */
60
+ export function useComposerNavigation(
61
+ mailboxId: string | undefined,
62
+ draftId: string | undefined
63
+ ) {
64
+ const checks = useRef<Record<Editor, LeaveCheck | null>>({
65
+ new: null,
66
+ reply: null,
67
+ });
68
+
69
+ const register: RegisterCheck = (editor, check) => {
70
+ checks.current[editor] = check;
71
+ };
72
+
73
+ const pending = useRef<Promise<boolean> | null>(null);
74
+
75
+ const blocker = useBlocker(({ currentLocation, nextLocation }) => {
76
+ const target = parseMailPath(nextLocation.pathname);
77
+ const nextDraft = new URLSearchParams(nextLocation.search).get("compose");
78
+
79
+ const keepsWindow =
80
+ target?.mailboxId === mailboxId && composeDraftId(nextDraft) === draftId;
81
+
82
+ const leaving: LeaveCheck[] = [];
83
+
84
+ if (currentLocation.pathname !== nextLocation.pathname) {
85
+ leaving.push(() => checks.current.reply?.() ?? null);
86
+ }
87
+
88
+ if (!keepsWindow) {
89
+ leaving.push(() => checks.current.new?.() ?? null);
90
+ }
91
+
92
+ const ready = readyToLeave(leaving);
93
+ pending.current = ready === true ? null : Promise.resolve(ready);
94
+
95
+ return pending.current !== null;
96
+ });
97
+
98
+ useEffect(() => {
99
+ if (blocker.state !== "blocked") return;
100
+ const attempt = pending.current;
101
+ let active = true;
102
+ void attempt?.then((ready) => {
103
+ if (!active || pending.current !== attempt) return;
104
+ pending.current = null;
105
+
106
+ if (ready) blocker.proceed();
107
+ else blocker.reset();
108
+ });
109
+
110
+ return () => {
111
+ active = false;
112
+ };
113
+ }, [blocker]);
114
+
115
+ return {
116
+ register,
117
+ canReplaceWindow: () =>
118
+ readyToLeave([() => checks.current.new?.() ?? null]),
119
+ };
120
+ }
@@ -1,27 +1,105 @@
1
1
  import { ApiError } from "@open-workspace/core/ui";
2
2
  import { useEffect, useRef } from "react";
3
+ import type { RefObject } from "react";
3
4
  import { toast } from "sonner";
4
5
 
5
- import { isComposerSessionBusy } from "./composer-session";
6
+ import { composerBodyLimitError } from "../../shared/mail";
7
+ import type { ComposerContent, ComposerEditorHandle } from "./composer-editor";
8
+ import { hasMessageBody } from "./composer-editor-document";
9
+ import { isComposerSessionBusy, isUploadedAsset } from "./composer-session";
6
10
  import type { ComposerSession, ComposerSessionPhase } from "./composer-session";
11
+ import { resolveComposerAttachmentPlan } from "./use-composer-attachment-preflight";
12
+ import type { PreflightContext } from "./use-composer-attachment-preflight";
7
13
  import { useMailSend, withMailSendRequestId } from "./use-mail-send";
8
14
  import type { MailSendDraft, SubmittedMessage } from "./use-mail-send";
9
15
 
10
- export type PreparedComposerSubmission = {
11
- assetIds: string[];
12
- command: MailSendDraft;
13
- submissionKey: string;
14
- };
16
+ type UploadedAttachment = NonNullable<
17
+ MailSendDraft["uploadedAttachments"]
18
+ >[number];
15
19
 
16
20
  /**
17
- * Owns the shared preflight -> submit -> release/complete transition. Draft
18
- * preparation remains composer-specific, but transport ownership has one path.
21
+ * Whether a message has something to send, the one rule every composer
22
+ * follows: text, an image or a file, beyond what it opened with (a
23
+ * signature on its own is nothing). `unchanged` says whether it holds only
24
+ * that opening.
25
+ */
26
+ export function hasContentToSend(
27
+ content: ComposerContent,
28
+ attachments: readonly unknown[],
29
+ unchanged: () => boolean
30
+ ) {
31
+ return (hasMessageBody(content) || attachments.length > 0) && !unchanged();
32
+ }
33
+
34
+ /**
35
+ * The body and files a message sends. With files, the delivery plan is
36
+ * settled first (which go as links), and the body is read again with the
37
+ * link cards that plan chose, so what is sent is what the person sees.
38
+ */
39
+ async function settledMessage(
40
+ session: ComposerSession,
41
+ editor: ComposerEditorHandle,
42
+ context: (content: ComposerContent) => PreflightContext,
43
+ signal: AbortSignal
44
+ ) {
45
+ let content = editor.content();
46
+ const assets = session.documentAssets();
47
+
48
+ if (assets.length) {
49
+ await resolveComposerAttachmentPlan(
50
+ session,
51
+ context(content),
52
+ assets,
53
+ signal
54
+ );
55
+ editor.reconcileAssets();
56
+ content = editor.content();
57
+ }
58
+
59
+ const linked = new Set(content.linkedAssetIds);
60
+ const submitted = session.documentAssets().filter(isUploadedAsset);
61
+
62
+ const uploadedAttachments: UploadedAttachment[] = submitted.map((asset) => {
63
+ // A linked inline image goes as a plain attachment, without its content ID.
64
+ const linkedInline = asset.intent === "inline" && linked.has(asset.id);
65
+
66
+ return {
67
+ uploadId: asset.uploadId,
68
+ disposition: linkedInline ? "attachment" : asset.intent,
69
+ // JSON leaves an undefined one out.
70
+ contentId: (!linkedInline && asset.contentId) || undefined,
71
+ };
72
+ });
73
+
74
+ return {
75
+ content,
76
+ assetIds: submitted.map((asset) => asset.id),
77
+ uploadedAttachments,
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Sends a composer's message: checks it, settles its files' delivery, sends
83
+ * it once (retries of the same message reuse its request id), and hands the
84
+ * uploads to the Worker or back to the composer.
19
85
  */
20
86
  export function useComposerSubmission(input: {
21
87
  session: ComposerSession;
22
88
  phase: ComposerSessionPhase;
89
+ editor: RefObject<ComposerEditorHandle | null>;
90
+ /** Why the message can't be sent as it is, if it can't. */
23
91
  validate: () => string | null;
24
- prepare: (signal: AbortSignal) => Promise<PreparedComposerSubmission>;
92
+ /** Why the body can't be sent as it is (nothing written), if it can't. */
93
+ missingText: (content: ComposerContent) => string | null;
94
+ context: (content: ComposerContent) => PreflightContext;
95
+ command: (
96
+ content: ComposerContent,
97
+ uploadedAttachments: UploadedAttachment[]
98
+ ) => MailSendDraft;
99
+ draftForSubmission: () => Promise<{
100
+ identity: { draftId?: string; draftVersion?: number };
101
+ recover: () => Promise<number>;
102
+ }>;
25
103
  failureLabel: string;
26
104
  onSuccess: (result: SubmittedMessage) => void;
27
105
  }) {
@@ -38,8 +116,45 @@ export function useComposerSubmission(input: {
38
116
  };
39
117
  }, []);
40
118
 
119
+ async function prepare(signal: AbortSignal) {
120
+ const editor = input.editor.current;
121
+
122
+ if (!editor) throw new Error(input.failureLabel);
123
+
124
+ const message = await settledMessage(
125
+ input.session,
126
+ editor,
127
+ input.context,
128
+ signal
129
+ );
130
+
131
+ const error = input.missingText(message.content);
132
+
133
+ if (error) throw new Error(error);
134
+
135
+ const { identity, recover } = await input.draftForSubmission();
136
+
137
+ const command = {
138
+ ...input.command(message.content, message.uploadedAttachments),
139
+ ...identity,
140
+ };
141
+
142
+ return {
143
+ assetIds: message.assetIds,
144
+ recover,
145
+ command,
146
+ submissionKey: JSON.stringify(command),
147
+ };
148
+ }
149
+
41
150
  async function submit() {
42
- const validationError = input.validate();
151
+ const content = input.editor.current?.content();
152
+
153
+ const validationError =
154
+ input.validate() ??
155
+ (content
156
+ ? (composerBodyLimitError(content) ?? input.missingText(content))
157
+ : input.failureLabel);
43
158
 
44
159
  if (validationError) {
45
160
  toast.error(validationError);
@@ -52,7 +167,7 @@ export function useComposerSubmission(input: {
52
167
  const controller = new AbortController();
53
168
  preflightRequest.current = controller;
54
169
 
55
- const preparation = await input.prepare(controller.signal).then(
170
+ const preparation = await prepare(controller.signal).then(
56
171
  (prepared) => ({ prepared }),
57
172
  (cause: unknown) => ({ cause })
58
173
  );
@@ -93,14 +208,34 @@ export function useComposerSubmission(input: {
93
208
  withMailSendRequestId(prepared.command, requestId)
94
209
  );
95
210
  } catch (error) {
96
- // The continuation can outlive React after a mailbox switch. Session
97
- // ownership still has to be released even when no UI remains.
98
- input.session.releaseSubmission(
99
- !(error instanceof ApiError) || error.status >= 500
100
- );
101
-
102
- if (!mounted.current) return;
103
- toast.error(error instanceof Error ? error.message : input.failureLabel);
211
+ const unconfirmed = !(error instanceof ApiError) || error.status >= 500;
212
+
213
+ const message =
214
+ error instanceof Error ? error.message : input.failureLabel;
215
+
216
+ if (!mounted.current && !unconfirmed) {
217
+ // Closing keeps submitted uploads alive until the draft has copied them.
218
+ await prepared.recover().then(
219
+ () =>
220
+ toast.error(message, { description: "Message saved in Drafts." }),
221
+ (cause: unknown) =>
222
+ toast.error(message, {
223
+ description:
224
+ cause instanceof Error
225
+ ? `Could not save the draft: ${cause.message}`
226
+ : "Could not save the draft.",
227
+ })
228
+ );
229
+ } else {
230
+ toast.error(message, {
231
+ description:
232
+ unconfirmed && !mounted.current
233
+ ? "Delivery could not be confirmed. Check Sent before sending again."
234
+ : undefined,
235
+ });
236
+ }
237
+
238
+ input.session.releaseSubmission(unconfirmed);
104
239
 
105
240
  return;
106
241
  }
@@ -0,0 +1,292 @@
1
+ import { useMutation, useQueryClient } from "@tanstack/react-query";
2
+ import { toast } from "sonner";
3
+
4
+ import type { ConversationPlace } from "../../shared/mail";
5
+ import {
6
+ applyMailboxChange,
7
+ beginOwnChange,
8
+ captureUndo,
9
+ expectedPlaces,
10
+ ownChangeDone,
11
+ ownChangeFailed,
12
+ ownChangeKey,
13
+ ownChangeSettled,
14
+ } from "./mail-query-cache";
15
+ import type { OwnChange, UndoSnapshot } from "./mail-query-cache";
16
+ import { bulkOwnChange, useBulkConversationAction } from "./use-mail-data";
17
+ import type {
18
+ BulkConversationAction,
19
+ BulkConversationInput,
20
+ } from "./use-mail-data";
21
+ import { undoSpamDecision } from "./use-mail-safety";
22
+
23
+ /** What the person is told: done, done for only some, or done for none. */
24
+ type ActionMessages = {
25
+ /** Said at once, as the change shows; nothing said when absent. */
26
+ done?: (count: number) => string;
27
+ /** None changed (they moved meanwhile, or the action doesn't apply). */
28
+ unchanged: string;
29
+ /** Some changed; the done message, as a warning, when absent. */
30
+ partial?: (changed: number, requested: number) => string;
31
+ /** The mail went back into the thread it was kept out of (Not spam). */
32
+ rejoined?: string;
33
+ };
34
+
35
+ /**
36
+ * Follows the change's expected places at once and returns how to follow
37
+ * the server's (`null` when it failed) where they differ.
38
+ */
39
+ export type FollowChange = (
40
+ expected: readonly ConversationPlace[]
41
+ ) => (actual: readonly ConversationPlace[] | null) => void;
42
+
43
+ type Update = Extract<BulkConversationAction, { type: "update" }>["update"];
44
+
45
+ /** How long a toast offers Undo. */
46
+ const UNDO_TOAST_MS = 8000;
47
+
48
+ /**
49
+ * Moving, deleting, reporting and marking conversations, the one way the
50
+ * open conversation and a selection do. It shows at once: rows leave, the
51
+ * open conversation closes (`follow`), the person hears it, with Undo for
52
+ * moves. The request names the folder they were in, so a stale view can't
53
+ * undo a newer move; the server's answer corrects what it didn't expect.
54
+ */
55
+ export function useConversationActions(scope: {
56
+ mailboxId: string | undefined;
57
+ folderId: string;
58
+ follow: FollowChange;
59
+ }) {
60
+ const client = useQueryClient();
61
+ const mutation = useBulkConversationAction(scope);
62
+
63
+ // Undo of a spam verdict puts back what it moved and who it trusted.
64
+ const undoSpam = useMutation({
65
+ mutationKey: ownChangeKey(scope.mailboxId),
66
+ mutationFn: ({
67
+ mailboxId,
68
+ undoId,
69
+ }: {
70
+ mailboxId: string;
71
+ undoId: string;
72
+ changes: OwnChange[];
73
+ }) => undoSpamDecision(mailboxId, undoId),
74
+ onMutate: ({ mailboxId, changes }) =>
75
+ beginOwnChange(client, mailboxId, ...changes),
76
+ onError: (_error, input, change) =>
77
+ ownChangeFailed(client, input.mailboxId, change),
78
+ onSuccess: (_result, { mailboxId, changes }, change) => {
79
+ ownChangeDone(client, mailboxId, change);
80
+
81
+ if (!changes.length) applyMailboxChange(client, mailboxId);
82
+
83
+ for (const key of ["recipient-suggestions", "blocked-senders"]) {
84
+ void client.invalidateQueries({ queryKey: [key, mailboxId] });
85
+ }
86
+ },
87
+ onSettled: (_result, _error, input) =>
88
+ ownChangeSettled(client, input.mailboxId),
89
+ });
90
+
91
+ /**
92
+ * Puts the conversations an action moved back where they were, once its
93
+ * answer says where they went: as an action of its own, shown at once.
94
+ */
95
+ async function undo(
96
+ input: BulkConversationInput,
97
+ answer: Promise<{ places: ConversationPlace[]; undoId?: string }>,
98
+ saved: UndoSnapshot
99
+ ) {
100
+ let places: ConversationPlace[];
101
+
102
+ let undoId: string | undefined;
103
+
104
+ try {
105
+ ({ places, undoId } = await answer);
106
+ } catch {
107
+ // It failed, and was put back already.
108
+ return;
109
+ }
110
+
111
+ const groups = new Map<
112
+ string,
113
+ { sourceFolderId: string; update: Update; conversationIds: string[] }
114
+ >();
115
+
116
+ for (const place of places) {
117
+ // Mail that rejoined a thread can't be taken out of it again; mail
118
+ // reported off a thread can, as Not spam brings it back.
119
+ const reported = input.action.type === "report";
120
+
121
+ if ((!place.left && !undoId) || !place.folder) continue;
122
+
123
+ if (place.conversationId !== place.from && !reported) continue;
124
+ const sourceFolderId = place.folder;
125
+ const back = place.previous;
126
+
127
+ if (!back) continue;
128
+ const key = `${sourceFolderId}\0${JSON.stringify(back)}`;
129
+
130
+ const group = groups.get(key) ?? {
131
+ sourceFolderId,
132
+ update: back,
133
+ conversationIds: [],
134
+ };
135
+
136
+ group.conversationIds.push(place.conversationId);
137
+ groups.set(key, group);
138
+ }
139
+
140
+ if (undoId) {
141
+ try {
142
+ await undoSpam.mutateAsync({
143
+ mailboxId: input.mailboxId,
144
+ undoId,
145
+ changes: [...groups.values()].map((group) => ({
146
+ type: "move",
147
+ ...group,
148
+ undoSnapshot: saved,
149
+ })),
150
+ });
151
+ } catch (error) {
152
+ toast.error(
153
+ error instanceof Error ? error.message : "Could not undo that"
154
+ );
155
+ }
156
+
157
+ return;
158
+ }
159
+
160
+ const results = await Promise.allSettled(
161
+ [...groups.values()].map((group) =>
162
+ mutation.mutateAsync({
163
+ mailboxId: input.mailboxId,
164
+ sourceFolderId: group.sourceFolderId,
165
+ conversationIds: group.conversationIds,
166
+ action: { type: "update", update: group.update, undo: true },
167
+ undoSnapshot: saved,
168
+ })
169
+ )
170
+ );
171
+
172
+ const failed = results.find((result) => result.status === "rejected");
173
+
174
+ if (failed) {
175
+ toast.error(
176
+ failed.reason instanceof Error
177
+ ? failed.reason.message
178
+ : "Could not undo that"
179
+ );
180
+ }
181
+ }
182
+
183
+ /**
184
+ * How many of `conversationIds` changed; null when it failed or there was
185
+ * nothing to do. `expected` names where they go when the cache can't
186
+ * (a conversation marked unread leaves the reader).
187
+ */
188
+ async function apply(
189
+ conversationIds: readonly string[],
190
+ action: BulkConversationAction,
191
+ messages: ActionMessages,
192
+ options: { undoable?: boolean; expected?: ConversationPlace[] } = {}
193
+ ) {
194
+ if (!scope.mailboxId || !conversationIds.length) return null;
195
+
196
+ const input: BulkConversationInput = {
197
+ mailboxId: scope.mailboxId,
198
+ sourceFolderId: scope.folderId,
199
+ conversationIds: [...conversationIds],
200
+ action,
201
+ };
202
+
203
+ // Read before the change shows: where they go, and where they were.
204
+ const expected =
205
+ options.expected ??
206
+ expectedPlaces(client, scope.mailboxId, bulkOwnChange(input));
207
+
208
+ let saved =
209
+ options.undoable && messages.done
210
+ ? captureUndo(client, scope.mailboxId, conversationIds)
211
+ : undefined;
212
+
213
+ const forgetUndo = () => {
214
+ saved = undefined;
215
+ };
216
+
217
+ const answer = mutation.mutateAsync(input);
218
+ const follow = scope.follow(expected);
219
+ const requested = conversationIds.length;
220
+
221
+ const undoOptions = saved
222
+ ? {
223
+ action: {
224
+ label: "Undo",
225
+ onClick: () => {
226
+ const snapshot = saved;
227
+
228
+ if (!snapshot) return;
229
+ forgetUndo();
230
+ void undo(input, answer, snapshot).finally(() =>
231
+ snapshot.clear()
232
+ );
233
+ },
234
+ },
235
+ duration: UNDO_TOAST_MS,
236
+ onDismiss: forgetUndo,
237
+ onAutoClose: forgetUndo,
238
+ }
239
+ : undefined;
240
+
241
+ const toastId = messages.done
242
+ ? toast.success(messages.done(requested), undoOptions)
243
+ : undefined;
244
+
245
+ try {
246
+ const result = await answer;
247
+ const { updatedCount, places } = result;
248
+
249
+ const rejoined =
250
+ action.type !== "report" &&
251
+ places.some((place) => place.conversationId !== place.from);
252
+
253
+ if (!updatedCount) {
254
+ forgetUndo();
255
+ toast.warning(messages.unchanged, { id: toastId, action: undefined });
256
+ } else if (updatedCount < requested) {
257
+ toast.warning(
258
+ messages.partial?.(updatedCount, requested) ??
259
+ messages.done?.(updatedCount) ??
260
+ messages.unchanged,
261
+ { id: toastId }
262
+ );
263
+ } else if (rejoined && toastId !== undefined) {
264
+ const reversible = "undoId" in result && result.undoId;
265
+
266
+ if (!reversible) forgetUndo();
267
+ toast.success(messages.rejoined ?? messages.done?.(updatedCount), {
268
+ id: toastId,
269
+ ...(reversible ? undoOptions : { action: undefined }),
270
+ });
271
+ }
272
+
273
+ follow(places);
274
+
275
+ return { changed: updatedCount };
276
+ } catch (error) {
277
+ const message =
278
+ error instanceof Error ? error.message : "Could not update mail";
279
+
280
+ forgetUndo();
281
+
282
+ if (toastId === undefined) toast.error(message);
283
+ else toast.error(message, { id: toastId, action: undefined });
284
+
285
+ follow(null);
286
+
287
+ return null;
288
+ }
289
+ }
290
+
291
+ return { apply };
292
+ }
@@ -0,0 +1,51 @@
1
+ import { useState } from "react";
2
+
3
+ import { newerThan } from "./conversation-order";
4
+ import type { ConversationSummary } from "./types";
5
+
6
+ /** Next and Previous follow folder order, even after reading removes the open row from Unread. */
7
+ export function useConversationPosition(
8
+ rows: ConversationSummary[],
9
+ id: string | undefined,
10
+ unreadScope: string | null
11
+ ) {
12
+ const index = rows.findIndex((row) => row.conversationId === id);
13
+ const row = rows[index];
14
+
15
+ const [last, setLast] = useState<{
16
+ scope: string;
17
+ row: ConversationSummary;
18
+ } | null>(null);
19
+
20
+ const same =
21
+ last && last.scope === unreadScope && last.row.conversationId === id;
22
+
23
+ if (
24
+ unreadScope &&
25
+ row &&
26
+ (!same || last.row.id !== row.id || last.row.timelineAt !== row.timelineAt)
27
+ ) {
28
+ setLast({ scope: unreadScope, row });
29
+ } else if (last && !same) {
30
+ setLast(null);
31
+ }
32
+
33
+ const anchor = row ?? (same ? last.row : undefined);
34
+
35
+ function nextIndex(list: ConversationSummary[]) {
36
+ if (!anchor) return -1;
37
+ const after = list.findIndex((item) => newerThan(anchor, item));
38
+
39
+ return after === -1 ? list.length : after;
40
+ }
41
+
42
+ const after = index === -1 ? nextIndex(rows) : index + 1;
43
+
44
+ return {
45
+ index,
46
+ previous: rows[index === -1 ? after - 1 : index - 1],
47
+ next: rows[after],
48
+ atLoadedEnd: after !== -1 && after === rows.length,
49
+ nextIndex,
50
+ };
51
+ }