@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
@@ -4,6 +4,7 @@ import {
4
4
  TooltipContent,
5
5
  TooltipTrigger,
6
6
  cn,
7
+ useDelayedPending,
7
8
  } from "@open-workspace/core/ui";
8
9
  import {
9
10
  Ban,
@@ -89,18 +90,14 @@ function Muted({ children }: { children: ReactNode }) {
89
90
  return <span className="text-muted-foreground">{children}</span>;
90
91
  }
91
92
 
92
- function spamhausRow(
93
- label: string,
94
- check: SpamhausCheck,
95
- target: ReactNode
96
- ): [string, ReactNode] {
93
+ function spamhausRow(label: string, check: SpamhausCheck, target: ReactNode) {
97
94
  if (check.status !== "ok") {
98
95
  return [
99
96
  label,
100
97
  <Muted>
101
98
  {check.error ?? lookupFailure[check.status] ?? "Not checked"}
102
99
  </Muted>,
103
- ];
100
+ ] satisfies [string, ReactNode];
104
101
  }
105
102
 
106
103
  if (!check.listings.length) {
@@ -110,7 +107,7 @@ function spamhausRow(
110
107
  <Check className="text-success size-3" />
111
108
  Not listed <Muted>{target}</Muted>
112
109
  </span>,
113
- ];
110
+ ] satisfies [string, ReactNode];
114
111
  }
115
112
 
116
113
  return [
@@ -132,11 +129,11 @@ function spamhausRow(
132
129
  </li>
133
130
  ))}
134
131
  </ul>,
135
- ];
132
+ ] satisfies [string, ReactNode];
136
133
  }
137
134
 
138
135
  /** Rows for the "Sender" section of Show original. */
139
- export function senderIntelRows(intel: SenderIntel): [string, ReactNode][] {
136
+ export function senderIntelRows(intel: SenderIntel) {
140
137
  const rows: [string, ReactNode][] = [];
141
138
  const ptrFailure = lookupFailure[intel.ptr.status];
142
139
  rows.push([
@@ -334,7 +331,9 @@ export function SenderSecurityBanner({
334
331
  }) {
335
332
  const warnings = message.security?.warnings ?? [];
336
333
  const [first, ...rest] = warnings;
337
- const pending = message.senderIntelPending;
334
+ // A quick check (most are) shows nothing; a slow one says so, and stays
335
+ // long enough to read.
336
+ const pending = useDelayedPending(Boolean(message.senderIntelPending));
338
337
 
339
338
  if (!first) {
340
339
  // Blocklist results can still add a warning: say so instead of nothing.
@@ -0,0 +1,43 @@
1
+ import { signatureHtmlWithName } from "../../shared/signature";
2
+ import { storedImagesHtml } from "./rich-content";
3
+ import type { Mailbox } from "./types";
4
+
5
+ /** Where the app shows a saved signature image (worker/mail/signature-routes.ts). */
6
+ export function signatureImageUrl(ownerId: string, contentId: string) {
7
+ return `/api/mail/signature-images/${encodeURIComponent(ownerId)}/${encodeURIComponent(contentId)}`;
8
+ }
9
+
10
+ /** A saved signature as editor content, its images shown from where they are stored. */
11
+ function signatureEditorHtml(
12
+ signature: { ownerId: string; html: string },
13
+ html = signature.html
14
+ ) {
15
+ return storedImagesHtml(html, signature.ownerId, (contentId) =>
16
+ signatureImageUrl(signature.ownerId, contentId)
17
+ );
18
+ }
19
+
20
+ /**
21
+ * What a new message (`new`) or a reply or forward (`reply`) from `mailbox`
22
+ * opens with: an empty line, then the signature that applies with `{name}`
23
+ * filled in, ready to edit. Empty when there is none or it is switched off.
24
+ */
25
+ export function messageSignatureHtml(
26
+ mailbox: Pick<Mailbox, "signature">,
27
+ kind: "new" | "reply",
28
+ senderName: string
29
+ ) {
30
+ const { signature } = mailbox;
31
+
32
+ if (
33
+ !signature ||
34
+ !(kind === "new" ? signature.useOnNew : signature.useOnReply)
35
+ ) {
36
+ return "";
37
+ }
38
+
39
+ return `<p></p>${signatureEditorHtml(
40
+ signature,
41
+ signatureHtmlWithName(signature.html, senderName)
42
+ )}`;
43
+ }
@@ -1,6 +1,6 @@
1
- const SKIP_TEXT_IN = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE"]);
1
+ const SKIP_TEXT_IN = "script, style, noscript, template, [data-mail-quote]";
2
2
 
3
- function textNodes(root: Node): Text[] {
3
+ function textNodes(root: Node) {
4
4
  const nodes: Text[] = [];
5
5
 
6
6
  function visit(node: Node) {
@@ -10,7 +10,7 @@ function textNodes(root: Node): Text[] {
10
10
  return;
11
11
  }
12
12
 
13
- if (node instanceof Element && SKIP_TEXT_IN.has(node.tagName)) return;
13
+ if (node instanceof Element && node.matches(SKIP_TEXT_IN)) return;
14
14
 
15
15
  for (const child of Array.from(node.childNodes)) visit(child);
16
16
  }
package/src/mail/types.ts CHANGED
@@ -48,6 +48,18 @@ export type ConversationSummary =
48
48
 
49
49
  export type MessageDetail = ConversationResponse["messages"][number];
50
50
 
51
+ export type ReplySource = NonNullable<ConversationResponse["replyDraftSource"]>;
52
+
51
53
  export type MessageAttachment = MessageDetail["attachments"][number];
52
54
 
53
55
  export type Folder = string;
56
+
57
+ type MailRulesRoute = (typeof mailApi.api.mail.mailboxes)[":id"]["rules"];
58
+
59
+ export type MailRule = SuccessfulResponse<
60
+ Awaited<ReturnType<MailRulesRoute["$get"]>>
61
+ >["rules"][number];
62
+
63
+ export type MailRuleInput = Parameters<
64
+ MailRulesRoute[":ruleId"]["$put"]
65
+ >[0]["json"];
@@ -3,78 +3,40 @@ import { useDebouncedValue, responseJson } from "@open-workspace/core/ui";
3
3
  import { useEffect, useEffectEvent } from "react";
4
4
 
5
5
  import type { ReplyActionMode } from "../../shared/mail";
6
+ import type { StoredImageRef } from "../../shared/rich-content";
6
7
  import { mailApi } from "../lib/mail-api";
7
8
  import type { ComposerAsset, ComposerSession } from "./composer-session";
8
9
 
9
- const textEncoder = new TextEncoder();
10
-
11
- export type PreflightContext =
10
+ export type PreflightContext = {
11
+ mailboxId: string;
12
+ bodyText: string;
13
+ bodyHtml?: string;
14
+ storedImages: StoredImageRef[];
15
+ } & (
12
16
  | {
13
17
  kind: "compose";
14
- mailboxId: string;
15
18
  subject: string;
16
- bodyText: string;
17
- bodyHtml?: string;
18
19
  }
19
20
  | {
20
21
  kind: "forward";
21
- mailboxId: string;
22
+ forwardedAttachmentIds?: string[];
22
23
  sourceEmailId: string;
23
- bodyText: string;
24
- bodyHtml?: string;
25
24
  }
26
25
  | {
27
26
  kind: "reply";
28
- mailboxId: string;
29
27
  sourceEmailId: string;
30
28
  mode: ReplyActionMode;
31
29
  cc: string[];
32
30
  bcc: string[];
33
- bodyText: string;
34
- bodyHtml?: string;
35
- };
36
-
37
- function byteLength(value: string | undefined) {
38
- return value ? textEncoder.encode(value).byteLength : 0;
39
- }
40
-
41
- function preflightContextSignature(context: PreflightContext) {
42
- const content = [
43
- byteLength(context.bodyText),
44
- byteLength(context.bodyText.trimEnd()),
45
- byteLength(context.bodyHtml),
46
- ];
47
-
48
- if (context.kind === "compose") {
49
- return [
50
- "compose",
51
- context.mailboxId,
52
- byteLength(context.subject.trim()),
53
- ...content,
54
- ];
55
- }
56
-
57
- if (context.kind === "forward") {
58
- return ["forward", context.mailboxId, context.sourceEmailId, ...content];
59
- }
60
-
61
- return [
62
- "reply",
63
- context.mailboxId,
64
- context.sourceEmailId,
65
- context.mode,
66
- context.cc,
67
- context.bcc,
68
- ...content,
69
- ];
70
- }
31
+ }
32
+ );
71
33
 
72
34
  function composerPlanKey(
73
35
  context: PreflightContext,
74
36
  assets: readonly ComposerAsset[]
75
37
  ) {
76
38
  return JSON.stringify([
77
- preflightContextSignature(context),
39
+ context,
78
40
  assets.map((asset) => [
79
41
  asset.id,
80
42
  asset.uploadId,
@@ -121,13 +83,8 @@ export async function resolveComposerAttachmentPlan(
121
83
  signal?: AbortSignal
122
84
  ) {
123
85
  const planKey = composerPlanKey(context, assets);
124
- session.beginPlan(planKey);
125
86
 
126
- if (!assets.length) {
127
- session.resolvePlan(planKey, []);
128
-
129
- return;
130
- }
87
+ if (!session.beginPlan(planKey)) return;
131
88
 
132
89
  try {
133
90
  const result = await preflightComposerAttachments(context, assets, signal);
@@ -136,7 +93,8 @@ export async function resolveComposerAttachmentPlan(
136
93
  planKey,
137
94
  assets.flatMap((asset) =>
138
95
  asset.uploadId && linkedUploadIds.has(asset.uploadId) ? [asset.id] : []
139
- )
96
+ ),
97
+ new Set(result.linkedForwardedIds)
140
98
  );
141
99
  } catch (error) {
142
100
  if (!signal?.aborted) session.failPlan(planKey);
@@ -154,12 +112,17 @@ export function useComposerAttachmentPreflight(
154
112
  assets: readonly ComposerAsset[],
155
113
  active = true
156
114
  ) {
157
- const requestKey = composerPlanKey(context, assets);
115
+ const hasAttachments =
116
+ assets.length > 0 ||
117
+ (context.kind === "forward" &&
118
+ context.forwardedAttachmentIds?.length !== 0);
119
+
120
+ const requestKey = hasAttachments ? composerPlanKey(context, assets) : "";
158
121
  const debouncedRequestKey = useDebouncedValue(requestKey, 750);
159
122
 
160
123
  // Reads this render's context and assets, which requestKey names.
161
124
  const resolvePlan = useEffectEvent((signal: AbortSignal) => {
162
- if (!assets.length || assets.some((asset) => !asset.uploadId)) return;
125
+ if (!hasAttachments || assets.some((asset) => !asset.uploadId)) return;
163
126
  void resolveComposerAttachmentPlan(session, context, assets, signal).catch(
164
127
  () => {
165
128
  // Background preflight is advisory. Final submission reports failures.
@@ -171,8 +134,8 @@ export function useComposerAttachmentPreflight(
171
134
  if (!active) return;
172
135
  session.beginPlan(requestKey);
173
136
 
174
- if (!assets.length) session.resolvePlan(requestKey, []);
175
- }, [active, assets.length, requestKey, session]);
137
+ if (!hasAttachments) session.resolvePlan(requestKey, [], new Set());
138
+ }, [active, hasAttachments, requestKey, session]);
176
139
 
177
140
  useEffect(() => {
178
141
  if (!active || requestKey !== debouncedRequestKey) return;
@@ -0,0 +1,286 @@
1
+ import { useAuth } from "@open-workspace/core/ui";
2
+ import { useLayoutEffect, useRef, useState } from "react";
3
+ import type { DragEvent } from "react";
4
+
5
+ import { composerBodyLimitError } from "../../shared/mail";
6
+ import type { ComposerContent, ComposerEditorHandle } from "./composer-editor";
7
+ import { isComposerSessionBusy, useComposerSession } from "./composer-session";
8
+ import type {
9
+ ComposerAsset,
10
+ ComposerAssetIntent,
11
+ ForwardedAttachment,
12
+ } from "./composer-session";
13
+ import { isInlineComposerImage } from "./composer-upload-client";
14
+ import {
15
+ draftAttachments,
16
+ holdsOnlyInitialContent,
17
+ openingText,
18
+ restoredComposerAssets,
19
+ restoredDraftContent,
20
+ restoredDraftHtml,
21
+ } from "./draft-attachments";
22
+ import { messageSignatureHtml } from "./signature";
23
+ import type { Mailbox } from "./types";
24
+ import type { DraftContent, SavedDraft } from "./use-drafts";
25
+
26
+ const EMPTY_CONTENT: ComposerContent = {
27
+ bodyHtml: "",
28
+ editorHtml: "",
29
+ bodyText: "",
30
+ inlineAssetIds: [],
31
+ storedImages: [],
32
+ linkedAssetIds: [],
33
+ };
34
+
35
+ const NO_ASSETS: ComposerAsset[] = [];
36
+
37
+ /** What a composer opens with, worked out once. */
38
+ function opening(input: {
39
+ mailbox: Mailbox | undefined;
40
+ draft: SavedDraft | undefined;
41
+ signature: "new" | "reply";
42
+ userName: string;
43
+ }) {
44
+ const { draft, mailbox } = input;
45
+
46
+ if (draft) {
47
+ const html = restoredDraftHtml(draft);
48
+ const assets = restoredComposerAssets(mailbox?.id ?? "", draft, html);
49
+
50
+ return {
51
+ html,
52
+ assets,
53
+ content: restoredDraftContent(draft, html, assets),
54
+ };
55
+ }
56
+
57
+ // The signature that applies, as editable content, added once: a reopened
58
+ // draft already holds it, so it never gets a second one.
59
+ return {
60
+ html: mailbox
61
+ ? messageSignatureHtml(mailbox, input.signature, input.userName)
62
+ : "",
63
+ assets: NO_ASSETS,
64
+ content: EMPTY_CONTENT,
65
+ };
66
+ }
67
+
68
+ /**
69
+ * What the compose window and the reply box share: the upload session, the
70
+ * editor and what it holds, adding and removing files, and dropping them
71
+ * anywhere on the form.
72
+ *
73
+ * The files a message holds are the ones its document refers to
74
+ * (ComposerSession.documentAssetIds); attachments are bookmarked in the
75
+ * document like inline images, so undo brings both back.
76
+ */
77
+ export function useComposerCore(input: {
78
+ mailbox: Mailbox | undefined;
79
+ /** A saved draft to reopen. */
80
+ draft: SavedDraft | undefined;
81
+ /** Which of the mailbox's signatures a new message opens with. */
82
+ signature: "new" | "reply";
83
+ /** Files that go with the message without being uploaded, e.g. a forward's. */
84
+ forwardedAttachments?: readonly ForwardedAttachment[];
85
+ }) {
86
+ const editor = useRef<ComposerEditorHandle>(null);
87
+ const form = useRef<HTMLFormElement>(null);
88
+ const fileInput = useRef<HTMLInputElement>(null);
89
+ const inlineFileInput = useRef<HTMLInputElement>(null);
90
+ const { user } = useAuth();
91
+
92
+ // oxlint-disable-next-line react/hook-use-state -- read once, when the editor is created; nothing sets it
93
+ const [start] = useState(() =>
94
+ opening({ ...input, userName: user?.name ?? "" })
95
+ );
96
+
97
+ // The text the editor opened with: a new composer still holding just that
98
+ // (its signature) is untouched and creates no draft.
99
+ // oxlint-disable-next-line react/hook-use-state -- read once; nothing sets it
100
+ const [initialText] = useState(() => openingText(start.html));
101
+
102
+ // Changes only as the person edits (the editor reports after a pause).
103
+ const [content, setContent] = useState(start.content);
104
+
105
+ const { session, snapshot } = useComposerSession(
106
+ input.mailbox?.id ?? "",
107
+ input.forwardedAttachments,
108
+ start.assets
109
+ );
110
+
111
+ // The editor handle as last rendered: an unmounting composer's last save
112
+ // still reads it after React has cleared `editor`.
113
+ const lastEditor = useRef<ComposerEditorHandle | null>(null);
114
+ useLayoutEffect(() => {
115
+ if (editor.current) lastEditor.current = editor.current;
116
+ });
117
+
118
+ const activeAssets = snapshot.assets.filter((asset) =>
119
+ snapshot.documentAssetIds.has(asset.id)
120
+ );
121
+
122
+ const [dragging, setDragging] = useState(false);
123
+
124
+ /** What the editor holds right now. */
125
+ function readContent() {
126
+ try {
127
+ return (editor.current ?? lastEditor.current)?.content() ?? content;
128
+ } catch {
129
+ // The editor was already destroyed.
130
+ return content;
131
+ }
132
+ }
133
+
134
+ function addFiles(
135
+ files: File[],
136
+ intent: ComposerAssetIntent,
137
+ position?: number
138
+ ) {
139
+ const assets = session.addFiles(files, intent);
140
+
141
+ if (assets) editor.current?.insertAssets(assets, position);
142
+ }
143
+
144
+ /** Images go into the text; other files attach. */
145
+ function addDroppedFiles(files: File[], position?: number) {
146
+ const images = files.filter(isInlineComposerImage);
147
+ const others = files.filter((file) => !isInlineComposerImage(file));
148
+
149
+ if (images.length) addFiles(images, "inline", position);
150
+
151
+ if (others.length) addFiles(others, "attachment", position);
152
+ }
153
+
154
+ function removeAsset(asset: ComposerAsset) {
155
+ if (editor.current?.removeAsset(asset.id)) return;
156
+ session.remove(asset.id);
157
+ }
158
+
159
+ const busy = isComposerSessionBusy(snapshot.phase);
160
+
161
+ const attachmentLimit = session.limitError();
162
+ const limitError = composerBodyLimitError(content) ?? attachmentLimit;
163
+
164
+ const uploadsPending = activeAssets.some(
165
+ (asset) => asset.status === "uploading"
166
+ );
167
+
168
+ const uploadsFailed = activeAssets.some((asset) => asset.status === "error");
169
+
170
+ const unfinishedUpload = uploadsPending
171
+ ? "Wait for attachments to finish uploading"
172
+ : uploadsFailed
173
+ ? "Retry or remove failed attachments"
174
+ : null;
175
+
176
+ const closeUploadError = unfinishedUpload
177
+ ? `${unfinishedUpload} before closing`
178
+ : null;
179
+
180
+ return {
181
+ editor,
182
+ form,
183
+ fileInput,
184
+ inlineFileInput,
185
+ session,
186
+ snapshot,
187
+ content,
188
+ /** The person changed the body (a reopened draft counts as written). */
189
+ edited: content !== EMPTY_CONTENT,
190
+ readContent,
191
+ activeAssets,
192
+ limitError,
193
+ uploadsPending,
194
+ uploadsFailed,
195
+ closeUploadError,
196
+ /** Why the message's files keep it from being sent, if they do. */
197
+ uploadsError: attachmentLimit ?? unfinishedUpload,
198
+ /** The editor footer shows content limits and attachment delivery errors. */
199
+ statusError:
200
+ limitError ??
201
+ ((activeAssets.length > 0 || snapshot.forwardedAttachments.length > 0) &&
202
+ snapshot.planError
203
+ ? "Could not check attachment delivery"
204
+ : null),
205
+ /** The finished uploads a draft keeps, as of now. */
206
+ keptAttachments: () => draftAttachments(session.documentAssets()),
207
+ /** The draft holds nothing but what the composer opened with. */
208
+ holdsOnlyOpening: (draft: Pick<DraftContent, "bodyText" | "attachments">) =>
209
+ holdsOnlyInitialContent(draft, initialText),
210
+ addFiles,
211
+ removeAsset,
212
+ /** Props for the composer's editor. */
213
+ editorProps: {
214
+ session,
215
+ initialHtml: start.html,
216
+ originalBody:
217
+ start.content.editorHtml === null ? start.content : undefined,
218
+ onChange: setContent,
219
+ onAssetsChange: session.setDocumentAssetIds,
220
+ onAddInlineFiles: (files: File[], position?: number) =>
221
+ addFiles(files, "inline", position),
222
+ onAddAttachmentFiles: (files: File[], position?: number) =>
223
+ addFiles(files, "attachment", position),
224
+ onChooseInlineImage: () => inlineFileInput.current?.click(),
225
+ onSubmitShortcut: () => form.current?.requestSubmit(),
226
+ dragging: dragging && !busy,
227
+ disabled: busy,
228
+ },
229
+ /** Props for the composer's list of files below the editor. */
230
+ attachmentListProps: {
231
+ // Uploaded files sent as links show as cards in the text instead.
232
+ uploads: activeAssets.filter(
233
+ (asset) =>
234
+ !snapshot.linkedAssetIds.has(asset.id) || asset.status !== "uploaded"
235
+ ),
236
+ linkedForwardedIds: snapshot.linkedForwardedIds,
237
+ progress: session.progress,
238
+ disabled: busy,
239
+ onRemove: removeAsset,
240
+ onRetry: (asset: ComposerAsset) => void session.retry(asset.id),
241
+ },
242
+ /** The form's drag and drop: files dropped anywhere on it are added. */
243
+ dropProps: {
244
+ onDragEnter: (event: DragEvent<HTMLFormElement>) => {
245
+ if (!event.dataTransfer.types.includes("Files")) return;
246
+ event.preventDefault();
247
+
248
+ if (!busy) setDragging(true);
249
+ },
250
+ onDragOver: (event: DragEvent<HTMLFormElement>) => {
251
+ if (!event.dataTransfer.types.includes("Files")) return;
252
+ event.preventDefault();
253
+ event.dataTransfer.dropEffect = busy ? "none" : "copy";
254
+ },
255
+ onDragLeave: (event: DragEvent<HTMLFormElement>) => {
256
+ if (
257
+ !(
258
+ event.relatedTarget instanceof Node &&
259
+ event.currentTarget.contains(event.relatedTarget)
260
+ )
261
+ ) {
262
+ setDragging(false);
263
+ }
264
+ },
265
+ onDragEnd: () => setDragging(false),
266
+ onDrop: (event: DragEvent<HTMLFormElement>) => {
267
+ if (!event.dataTransfer.types.includes("Files")) return;
268
+ event.preventDefault();
269
+ setDragging(false);
270
+
271
+ if (busy) return;
272
+
273
+ // The editor takes files dropped on the text itself, where they
274
+ // fall; the form, files dropped anywhere else.
275
+ if (
276
+ event.target instanceof Element &&
277
+ event.target.closest("[data-composer-editor-content]")
278
+ ) {
279
+ return;
280
+ }
281
+
282
+ addDroppedFiles(Array.from(event.dataTransfer.files));
283
+ },
284
+ },
285
+ };
286
+ }
@@ -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
+ }