@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,194 @@
1
+ // Kept apart from use-drafts.ts, which loads the API client, so unit tests
2
+ // can import these.
3
+ import { EMAIL_SERVICE_MAX_BYTES } from "../../shared/mail";
4
+ import { normalizedContentId } from "../../shared/rich-content";
5
+ import { linkTargetSuffix } from "./composer-link-text";
6
+ import type { ComposerAsset } from "./composer-session";
7
+ import type { DraftContent, SavedDraft } from "./use-drafts";
8
+
9
+ /** The finished uploads a composer's draft keeps. */
10
+ export function draftAttachments(assets: readonly ComposerAsset[]) {
11
+ return assets.flatMap((asset) =>
12
+ asset.status === "uploaded" && asset.uploadId
13
+ ? [
14
+ {
15
+ assetId: asset.id,
16
+ uploadId: asset.uploadId,
17
+ disposition: asset.intent,
18
+ // JSON leaves an undefined one out.
19
+ contentId: asset.contentId ?? undefined,
20
+ },
21
+ ]
22
+ : []
23
+ );
24
+ }
25
+
26
+ /**
27
+ * A reopened draft's files as composer assets, already uploaded: its
28
+ * attachments, and the inline files its editor HTML (`html`, from
29
+ * restoredDraftHtml) still shows. An inline file the HTML no longer refers
30
+ * to, such as a copy of a signature image left out, isn't brought back.
31
+ */
32
+ export function restoredComposerAssets(
33
+ mailboxId: string,
34
+ draft: Pick<SavedDraft, "attachments"> | undefined,
35
+ html: string
36
+ ) {
37
+ // The HTML is the browser's serialization, so the attribute reads this way.
38
+ const shown = new Set(
39
+ Array.from(
40
+ html.matchAll(/data-composer-asset="([^"]+)"/gu),
41
+ (match) => match[1]
42
+ )
43
+ );
44
+
45
+ return (draft?.attachments ?? []).flatMap((file) =>
46
+ file.disposition === "inline" && !shown.has(file.assetId)
47
+ ? []
48
+ : [
49
+ {
50
+ id: file.assetId,
51
+ uploadId: file.uploadId,
52
+ filename: file.filename,
53
+ contentType: file.contentType,
54
+ size: file.size,
55
+ intent: file.disposition,
56
+ contentId: file.contentId,
57
+ // As for a new upload: an image too large to send inline becomes a link.
58
+ previewUrl:
59
+ file.disposition === "inline" &&
60
+ file.size <= EMAIL_SERVICE_MAX_BYTES
61
+ ? `/api/mail/drafts/files/${encodeURIComponent(file.uploadId)}?mailboxId=${encodeURIComponent(mailboxId)}`
62
+ : null,
63
+ status: "uploaded" as const,
64
+ error: null,
65
+ },
66
+ ]
67
+ );
68
+ }
69
+
70
+ /** Plain text as editor HTML: a paragraph per blank-line-separated block. */
71
+ function textHtml(text: string) {
72
+ const document = new DOMParser().parseFromString("", "text/html");
73
+
74
+ for (const block of text.split(/\r?\n\s*\r?\n/u)) {
75
+ const paragraph = document.createElement("p");
76
+
77
+ block.split(/\r?\n/u).forEach((line, index) => {
78
+ if (index > 0) paragraph.appendChild(document.createElement("br"));
79
+ paragraph.appendChild(document.createTextNode(line));
80
+ });
81
+ document.body.appendChild(paragraph);
82
+ }
83
+
84
+ return document.body.innerHTML;
85
+ }
86
+
87
+ /**
88
+ * A reopened draft's editor HTML. The signature images it kept as its own
89
+ * files become ordinary inline images of those files, so the draft no longer
90
+ * depends on the signature as it is now. A mail app's draft has no editor
91
+ * HTML: its cid: images are matched to uploads, and text becomes paragraphs.
92
+ */
93
+ export function restoredDraftHtml(
94
+ draft: Pick<
95
+ SavedDraft,
96
+ "bodyHtml" | "editorHtml" | "bodyText" | "attachments"
97
+ >
98
+ ) {
99
+ const document = new DOMParser().parseFromString(
100
+ draft.editorHtml ?? draft.bodyHtml ?? textHtml(draft.bodyText),
101
+ "text/html"
102
+ );
103
+
104
+ for (const image of document.querySelectorAll<HTMLImageElement>(
105
+ 'img[data-stored-owner], img[src^="cid:" i]'
106
+ )) {
107
+ const contentId =
108
+ image.dataset.cid ??
109
+ (image.getAttribute("src") ?? "").replace(/^cid:/iu, "");
110
+
111
+ // JMAP HTML refers to inline uploads by Content-ID. The web editor
112
+ // bookmarks the same file by asset ID so autosave and send can retain it.
113
+ const owner = image.dataset.storedOwner;
114
+
115
+ const copy = draft.attachments.find((file) =>
116
+ owner === undefined
117
+ ? file.disposition === "inline" &&
118
+ file.contentId !== null &&
119
+ normalizedContentId(file.contentId) === normalizedContentId(contentId)
120
+ : file.storedImage?.ownerId === owner &&
121
+ file.storedImage.contentId === contentId
122
+ );
123
+
124
+ if (!copy) {
125
+ image.remove();
126
+ continue;
127
+ }
128
+
129
+ const asset = document.createElement("span");
130
+ asset.dataset.composerAsset = copy.assetId;
131
+ asset.dataset.composerAssetIntent = "inline";
132
+ image.replaceWith(asset);
133
+ }
134
+
135
+ return document.body.innerHTML;
136
+ }
137
+
138
+ /**
139
+ * A reopened draft as the composer's content, the way its editor opens it
140
+ * (`html`, from restoredDraftHtml). Starting from this, opening a draft
141
+ * changes nothing, so it doesn't save; and it counts as written, so it can
142
+ * be sent as is.
143
+ */
144
+ export function restoredDraftContent(
145
+ draft: Pick<SavedDraft, "bodyHtml" | "bodyText" | "editorHtml">,
146
+ html: string,
147
+ assets: readonly ComposerAsset[]
148
+ ) {
149
+ return {
150
+ bodyHtml: draft.bodyHtml ?? "",
151
+ editorHtml: draft.editorHtml === null ? null : html,
152
+ bodyText: draft.bodyText,
153
+ inlineAssetIds: assets.flatMap((asset) =>
154
+ asset.intent === "inline" ? [asset.id] : []
155
+ ),
156
+ storedImages: [],
157
+ linkedAssetIds: [],
158
+ };
159
+ }
160
+
161
+ /** The text of HTML the editor opens with, images as their alt text, as the editor reads it. */
162
+ export function openingText(html: string) {
163
+ const document = new DOMParser().parseFromString(html, "text/html");
164
+
165
+ for (const image of document.querySelectorAll("img")) {
166
+ image.replaceWith(image.alt);
167
+ }
168
+
169
+ for (const link of document.querySelectorAll("a[href]")) {
170
+ link.append(
171
+ linkTargetSuffix(link.textContent, link.getAttribute("href") ?? "")
172
+ );
173
+ }
174
+
175
+ return document.body.textContent;
176
+ }
177
+
178
+ /**
179
+ * Whether a draft holds nothing but what its composer opened with
180
+ * (`initialText`, e.g. the signature): no new text and no files. Spacing is
181
+ * ignored, since the editor and the opening HTML space blocks apart
182
+ * differently.
183
+ */
184
+ export function holdsOnlyInitialContent(
185
+ content: Pick<DraftContent, "bodyText" | "attachments">,
186
+ initialText: string
187
+ ) {
188
+ const squeeze = (text: string) => text.replaceAll(/\s+/gu, "");
189
+
190
+ return (
191
+ squeeze(content.bodyText ?? "") === squeeze(initialText) &&
192
+ !content.attachments?.length
193
+ );
194
+ }
@@ -1,12 +1,11 @@
1
1
  import { Skeleton, cn } from "@open-workspace/core/ui";
2
- import { useEffect, useRef, useState } from "react";
2
+ import { useEffect, useLayoutEffect, useRef, useState } from "react";
3
3
 
4
- import { translatedEmailHtml } from "./translation-html";
5
- import type { MessageDetail } from "./types";
6
- import { useSanitizedEmailHtml } from "./use-sanitized-email-html";
4
+ import type { MessageBodyContent } from "./message-body";
5
+ import { PlainMessageText } from "./plain-message-text";
7
6
 
8
7
  /** Reading measure and rhythm shared by plain-text bodies. */
9
- export const messageTextClassName =
8
+ const messageTextClassName =
10
9
  "max-w-[72ch] whitespace-pre-wrap text-[14.5px] leading-[1.7] [overflow-wrap:anywhere]";
11
10
 
12
11
  const MIN_FRAME_HEIGHT = 48;
@@ -15,14 +14,72 @@ const MIN_FRAME_HEIGHT = 48;
15
14
  // inner scrollbar.
16
15
  const MAX_FRAME_HEIGHT = 20_000;
17
16
 
18
- export function EmailHtmlBody({
19
- mailboxId,
20
- message,
21
- translations,
17
+ export function MessageBody({
18
+ body,
19
+ subject,
20
+ ready,
21
+ hideQuote,
22
+ focusQuote,
22
23
  }: {
23
- mailboxId: string;
24
- message: MessageDetail;
25
- translations?: string[];
24
+ body: MessageBodyContent;
25
+ subject: string;
26
+ ready: boolean;
27
+ hideQuote: boolean;
28
+ focusQuote: boolean;
29
+ }) {
30
+ const rich = useRef<HTMLDivElement>(null);
31
+ useLayoutEffect(() => {
32
+ if (focusQuote) {
33
+ rich.current
34
+ ?.querySelector("[data-mail-quote]")
35
+ ?.scrollIntoView({ block: "start" });
36
+ }
37
+ }, [focusQuote]);
38
+
39
+ if (!ready) return <BodySkeleton />;
40
+
41
+ if (body.format === "text") {
42
+ return (
43
+ <div className={messageTextClassName}>
44
+ <PlainMessageText text={body.value} />
45
+ </div>
46
+ );
47
+ }
48
+
49
+ if (body.format === "document") {
50
+ return (
51
+ <EmailFrame
52
+ srcDoc={body.value}
53
+ subject={subject}
54
+ hideQuote={hideQuote}
55
+ focusQuote={focusQuote}
56
+ />
57
+ );
58
+ }
59
+
60
+ return (
61
+ <div
62
+ ref={rich}
63
+ className={cn(
64
+ "composer-message-body max-w-[72ch] text-[14.5px] leading-[1.7]",
65
+ hideQuote && "[&_[data-mail-quote]]:hidden!"
66
+ )}
67
+ // oxlint-disable-next-line react/no-danger -- composer HTML is sanitized for the app document
68
+ dangerouslySetInnerHTML={{ __html: body.value }}
69
+ />
70
+ );
71
+ }
72
+
73
+ function EmailFrame({
74
+ srcDoc,
75
+ subject,
76
+ hideQuote,
77
+ focusQuote,
78
+ }: {
79
+ srcDoc: string;
80
+ subject: string;
81
+ hideQuote: boolean;
82
+ focusQuote: boolean;
26
83
  }) {
27
84
  const iframe = useRef<HTMLIFrameElement>(null);
28
85
  const frameObserver = useRef<ResizeObserver | null>(null);
@@ -33,20 +90,8 @@ export function EmailHtmlBody({
33
90
  height: number;
34
91
  } | null>(null);
35
92
 
36
- const html = useSanitizedEmailHtml(mailboxId, message);
37
-
38
- const composerHtml =
39
- translations && message.direction === "outgoing" && html.data?.composerHtml
40
- ? translatedEmailHtml(html.data.composerHtml, translations, false)
41
- : html.data?.composerHtml;
42
-
43
- const srcDoc =
44
- translations && message.direction === "incoming" && html.data?.srcDoc
45
- ? translatedEmailHtml(html.data.srcDoc, translations, true)
46
- : html.data?.srcDoc;
47
-
48
93
  // A new document shows the skeleton until it has loaded and been fitted.
49
- const fitted = srcDoc && loadedFrame?.srcDoc === srcDoc ? loadedFrame : null;
94
+ const fitted = loadedFrame?.srcDoc === srcDoc ? loadedFrame : null;
50
95
  const frameReady = fitted !== null;
51
96
  const height = fitted?.height ?? MIN_FRAME_HEIGHT;
52
97
 
@@ -58,11 +103,25 @@ export function EmailHtmlBody({
58
103
  []
59
104
  );
60
105
 
106
+ // Toggle the existing document so opening a quote keeps its formatting,
107
+ // loaded images and scroll position. The printed document stays complete.
108
+ useLayoutEffect(() => {
109
+ const doc = iframe.current?.contentDocument;
110
+ doc?.documentElement.toggleAttribute("data-hide-quote", hideQuote);
111
+
112
+ if (focusQuote && frameReady) {
113
+ doc
114
+ ?.querySelector("[data-mail-quote]")
115
+ ?.scrollIntoView({ block: "start" });
116
+ }
117
+ }, [hideQuote, focusQuote, frameReady]);
118
+
61
119
  function observeFrameSize() {
62
120
  const frame = iframe.current;
63
121
  const document = frame?.contentDocument;
64
122
 
65
- if (!frame || !document || !srcDoc) return;
123
+ if (!frame || !document) return;
124
+ document.documentElement.toggleAttribute("data-hide-quote", hideQuote);
66
125
  const loadedSrcDoc = srcDoc;
67
126
 
68
127
  // Fixed-width newsletters (often 600–700px) are scaled down to the pane,
@@ -145,30 +204,6 @@ export function EmailHtmlBody({
145
204
  );
146
205
  }
147
206
 
148
- const fallback = (
149
- <div className={messageTextClassName}>
150
- {message.bodyText || message.preview || "No text body"}
151
- </div>
152
- );
153
-
154
- if (html.isPending) {
155
- return <BodySkeleton />;
156
- }
157
-
158
- if (message.direction === "outgoing") {
159
- return composerHtml ? (
160
- <div
161
- className="composer-message-body max-w-[72ch] text-[14.5px] leading-[1.7]"
162
- // oxlint-disable-next-line react/no-danger -- composerHtml is sanitized email HTML
163
- dangerouslySetInnerHTML={{ __html: composerHtml }}
164
- />
165
- ) : (
166
- fallback
167
- );
168
- }
169
-
170
- if (!html.data?.renderAsHtml || !srcDoc) return fallback;
171
-
172
207
  return (
173
208
  <div className="relative">
174
209
  {frameReady ? null : <BodySkeleton />}
@@ -181,7 +216,7 @@ export function EmailHtmlBody({
181
216
  : "pointer-events-none absolute inset-x-0 top-0 h-0 opacity-0"
182
217
  )}
183
218
  style={frameReady ? { height } : undefined}
184
- title={`HTML body of ${message.subject}`}
219
+ title={`HTML body of ${subject}`}
185
220
  sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin"
186
221
  referrerPolicy="no-referrer"
187
222
  srcDoc={srcDoc}
@@ -191,9 +226,18 @@ export function EmailHtmlBody({
191
226
  );
192
227
  }
193
228
 
194
- function BodySkeleton() {
229
+ /**
230
+ * The one placeholder a message body shows from the moment its conversation
231
+ * opens until the body is laid out. Its height is a short email's, so the
232
+ * swap neither collapses the page nor pushes it far down.
233
+ */
234
+ export function BodySkeleton() {
195
235
  return (
196
- <div aria-hidden="true" className="max-w-[72ch] space-y-2.5 py-1">
236
+ <div
237
+ aria-hidden="true"
238
+ data-body-placeholder
239
+ className="min-h-40 max-w-[72ch] space-y-2.5 py-1"
240
+ >
197
241
  <Skeleton className="h-3.5 w-11/12" />
198
242
  <Skeleton className="h-3.5 w-full" />
199
243
  <Skeleton className="h-3.5 w-4/5" />
@@ -0,0 +1,193 @@
1
+ import {
2
+ AlertDialog,
3
+ AlertDialogAction,
4
+ AlertDialogCancel,
5
+ AlertDialogContent,
6
+ AlertDialogDescription,
7
+ AlertDialogFooter,
8
+ AlertDialogHeader,
9
+ AlertDialogTitle,
10
+ Button,
11
+ responseJson,
12
+ } from "@open-workspace/core/ui";
13
+ import { useMutation, useQueryClient } from "@tanstack/react-query";
14
+ import { LoaderCircle } from "lucide-react";
15
+ import { useState } from "react";
16
+ import { toast } from "sonner";
17
+
18
+ import type { ConversationPlace } from "../../shared/mail";
19
+ import { mailApi } from "../lib/mail-api";
20
+ import { focusListAfter } from "./mail-focus";
21
+ import {
22
+ beginOwnChange,
23
+ expectedPlaces,
24
+ ownChangeDone,
25
+ ownChangeFailed,
26
+ ownChangeKey,
27
+ ownChangeSettled,
28
+ } from "./mail-query-cache";
29
+ import type { FollowChange } from "./use-conversation-actions";
30
+
31
+ function plural(count: number) {
32
+ return `${count} ${count === 1 ? "conversation" : "conversations"}`;
33
+ }
34
+
35
+ /**
36
+ * The server deletes in batches; keeps asking until nothing is left.
37
+ * `progress` holds what went, also when a later batch fails.
38
+ */
39
+ async function emptyAll(
40
+ mailboxId: string,
41
+ folder: "trash" | "spam",
42
+ progress: { deleted: number; places: ConversationPlace[] }
43
+ ) {
44
+ for (;;) {
45
+ // oxlint-disable-next-line eslint/no-await-in-loop -- each batch deletes what the last one left
46
+ const result = await responseJson(
47
+ // oxlint-disable-next-line eslint/no-await-in-loop -- same request as above
48
+ await mailApi.api.mail.mailboxes[":id"].folders[":folder"].empty.$post({
49
+ param: { id: mailboxId, folder },
50
+ })
51
+ );
52
+
53
+ progress.deleted += result.deleted;
54
+ progress.places.push(...result.places);
55
+
56
+ if (!result.remaining || !result.deleted) return;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * The line above Trash and Spam: how long mail stays (from `Email({ retention })`)
62
+ * and, with send access, "Empty". The caller hides it when the folder is empty.
63
+ */
64
+ export function FolderCleanupBar({
65
+ mailboxId,
66
+ folder,
67
+ folderName,
68
+ conversationCount,
69
+ retentionDays,
70
+ canEmpty,
71
+ follow,
72
+ }: {
73
+ mailboxId: string;
74
+ folder: "trash" | "spam";
75
+ folderName: string;
76
+ conversationCount: number;
77
+ retentionDays: number | null;
78
+ canEmpty: boolean;
79
+ /** Where the deleted conversations go, for the view to follow (`followChange`). */
80
+ follow: FollowChange;
81
+ }) {
82
+ const client = useQueryClient();
83
+ const [confirmOpen, setConfirmOpen] = useState(false);
84
+ const couldNot = `${folderName} couldn't be emptied`;
85
+
86
+ // The folder empties at once (the confirmation came first); it comes back
87
+ // only if nothing could be deleted.
88
+ const emptying = useMutation({
89
+ mutationKey: ownChangeKey(mailboxId),
90
+ mutationFn: async () => {
91
+ const places: ConversationPlace[] = [];
92
+ const progress = { deleted: 0, places };
93
+
94
+ try {
95
+ await emptyAll(mailboxId, folder, progress);
96
+
97
+ return { progress, failure: null };
98
+ } catch (error) {
99
+ if (!progress.deleted) throw error;
100
+
101
+ // Earlier batches went: the list and the open conversation follow.
102
+ return {
103
+ progress,
104
+ failure: error instanceof Error ? error.message : couldNot,
105
+ };
106
+ }
107
+ },
108
+ onMutate: () =>
109
+ beginOwnChange(client, mailboxId, { type: "empty", folder }),
110
+ onError: (_error, _input, change) =>
111
+ ownChangeFailed(client, mailboxId, change),
112
+ onSuccess: (_result, _input, change) =>
113
+ ownChangeDone(client, mailboxId, change),
114
+ onSettled: () => ownChangeSettled(client, mailboxId),
115
+ });
116
+
117
+ if (!retentionDays && !canEmpty) return null;
118
+
119
+ async function empty() {
120
+ // The bar goes with the mail, and focus (on its button) with it.
121
+ focusListAfter([]);
122
+ setConfirmOpen(false);
123
+
124
+ // A conversation open from this folder goes with it.
125
+ const followAnswer = follow(
126
+ expectedPlaces(client, mailboxId, { type: "empty", folder })
127
+ );
128
+
129
+ try {
130
+ const { progress, failure } = await emptying.mutateAsync();
131
+
132
+ if (failure) {
133
+ toast.error(
134
+ `${plural(progress.deleted)} deleted permanently; the rest couldn't be. ${failure}`
135
+ );
136
+ } else {
137
+ toast.success(`${plural(progress.deleted)} deleted permanently`);
138
+ }
139
+
140
+ followAnswer(progress.places);
141
+ } catch (error) {
142
+ toast.error(error instanceof Error ? error.message : couldNot);
143
+ followAnswer(null);
144
+ }
145
+ }
146
+
147
+ return (
148
+ <>
149
+ <p className="text-muted-foreground border-border flex flex-wrap items-center justify-center gap-x-1 border-b px-4 py-1.5 text-center text-xs">
150
+ {retentionDays && (
151
+ <span>
152
+ Conversations are deleted after {retentionDays}{" "}
153
+ {retentionDays === 1 ? "day" : "days"} in {folderName}.
154
+ </span>
155
+ )}
156
+ {retentionDays && canEmpty && <span aria-hidden>·</span>}
157
+ {canEmpty && (
158
+ <Button
159
+ variant="link"
160
+ size="sm"
161
+ className="h-auto p-0 text-xs"
162
+ disabled={emptying.isPending}
163
+ onClick={() => setConfirmOpen(true)}
164
+ >
165
+ {emptying.isPending && <LoaderCircle className="animate-spin" />}
166
+ Empty {folderName}
167
+ </Button>
168
+ )}
169
+ </p>
170
+ <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
171
+ <AlertDialogContent>
172
+ <AlertDialogHeader>
173
+ <AlertDialogTitle>Empty {folderName}?</AlertDialogTitle>
174
+ <AlertDialogDescription>
175
+ All {plural(conversationCount)} in {folderName} and their
176
+ attachments will be deleted for everyone. This cannot be undone.
177
+ </AlertDialogDescription>
178
+ </AlertDialogHeader>
179
+ <AlertDialogFooter>
180
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
181
+ <AlertDialogAction
182
+ type="button"
183
+ variant="destructive"
184
+ onClick={() => void empty()}
185
+ >
186
+ Empty {folderName}
187
+ </AlertDialogAction>
188
+ </AlertDialogFooter>
189
+ </AlertDialogContent>
190
+ </AlertDialog>
191
+ </>
192
+ );
193
+ }
@@ -2,6 +2,7 @@ import {
2
2
  Archive,
3
3
  Folder as FolderIcon,
4
4
  Inbox,
5
+ NotebookPen,
5
6
  Send,
6
7
  ShieldAlert,
7
8
  Trash2,
@@ -26,6 +27,10 @@ export function FolderGlyph({
26
27
  return <Send {...props} />;
27
28
  }
28
29
 
30
+ case "drafts": {
31
+ return <NotebookPen {...props} />;
32
+ }
33
+
29
34
  case "archive": {
30
35
  return <Archive {...props} />;
31
36
  }