@open-workspace/email 0.3.0 → 0.4.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 (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -0,0 +1,260 @@
1
+ import {
2
+ Popover,
3
+ PopoverContent,
4
+ PopoverTrigger,
5
+ Tooltip,
6
+ TooltipContent,
7
+ TooltipTrigger,
8
+ cn,
9
+ } from "@open-workspace/core/ui";
10
+ import type { ReactNode } from "react";
11
+
12
+ import { fullDate } from "./message-format";
13
+ import { verdictCopy } from "./sender-authentication";
14
+ import type { MessageDetail } from "./types";
15
+
16
+ /** A badge whose explanation shows on hover. */
17
+ function HintBadge({
18
+ hint,
19
+ className,
20
+ children,
21
+ ...props
22
+ }: {
23
+ hint: string;
24
+ className: string;
25
+ children: ReactNode;
26
+ "data-testid"?: string;
27
+ }) {
28
+ return (
29
+ <Tooltip>
30
+ <TooltipTrigger render={<span className={className} {...props} />}>
31
+ {children}
32
+ </TooltipTrigger>
33
+ <TooltipContent>{hint}</TooltipContent>
34
+ </Tooltip>
35
+ );
36
+ }
37
+
38
+ /**
39
+ * Why the sender is blocked: a button, so the pattern opens on tap and from
40
+ * the keyboard as well as on hover.
41
+ */
42
+ function BlockedBadge({
43
+ block,
44
+ }: {
45
+ block: NonNullable<MessageDetail["sender"]>["block"] & {};
46
+ }) {
47
+ return (
48
+ <Popover>
49
+ <PopoverTrigger
50
+ openOnHover
51
+ delay={300}
52
+ className="bg-destructive/8 text-destructive focus-visible:ring-ring shrink-0 rounded-sm px-1 py-px text-[10.5px] font-medium outline-none focus-visible:ring-2"
53
+ >
54
+ Blocked
55
+ </PopoverTrigger>
56
+ <PopoverContent
57
+ side="bottom"
58
+ align="start"
59
+ className="w-auto max-w-xs px-3 py-2 text-xs"
60
+ >
61
+ {block.workspace
62
+ ? `Blocked for everyone by an administrator (${block.pattern})`
63
+ : `You blocked ${block.pattern}`}
64
+ </PopoverContent>
65
+ </Popover>
66
+ );
67
+ }
68
+
69
+ /** The sender's name with its badges (You, via, External, New sender, Blocked); collapses the message when it can. */
70
+ export function SenderLine({
71
+ message,
72
+ sender,
73
+ own,
74
+ onCollapse,
75
+ }: {
76
+ message: MessageDetail;
77
+ sender: string;
78
+ own: boolean;
79
+ onCollapse?: () => void;
80
+ }) {
81
+ const { security } = message;
82
+
83
+ const content = (
84
+ <>
85
+ <span className="text-foreground truncate text-[13.5px] font-semibold">
86
+ {sender}
87
+ </span>
88
+ {own && (
89
+ <span className="bg-accent text-accent-foreground shrink-0 rounded-sm px-1 py-px text-[10.5px] font-semibold">
90
+ You
91
+ </span>
92
+ )}
93
+ {security?.via && (
94
+ <HintBadge
95
+ className="text-muted-foreground hidden min-w-0 shrink truncate text-xs @md/reader:inline"
96
+ hint={`Sent through ${security.via} on behalf of ${security.fromDomain ?? message.fromAddress}`}
97
+ >
98
+ via {security.via}
99
+ </HintBadge>
100
+ )}
101
+ {security?.external && !own && (
102
+ <HintBadge
103
+ className="text-muted-foreground ring-border shrink-0 rounded-sm px-1 py-px text-[10.5px] font-medium ring-1 ring-inset"
104
+ hint="This sender is outside your organization"
105
+ >
106
+ External
107
+ </HintBadge>
108
+ )}
109
+ {security?.firstTimeSender && !own && !security.warnings.length && (
110
+ <HintBadge
111
+ data-testid="first-time-sender"
112
+ className="bg-info/10 text-info hidden shrink-0 rounded-sm px-1 py-px text-[10.5px] font-medium @sm/reader:inline"
113
+ hint="This is the first message from this address, and this mailbox has never written to it"
114
+ >
115
+ New sender
116
+ </HintBadge>
117
+ )}
118
+ </>
119
+ );
120
+
121
+ const blocked = message.sender?.block ? (
122
+ <BlockedBadge block={message.sender.block} />
123
+ ) : null;
124
+
125
+ const className = "flex min-w-0 shrink items-center gap-1.5 text-left";
126
+
127
+ if (!onCollapse) {
128
+ return (
129
+ <div className={className}>
130
+ {content}
131
+ {blocked}
132
+ </div>
133
+ );
134
+ }
135
+
136
+ return (
137
+ // The Blocked badge is a button of its own, so it sits beside the collapse button, not in it.
138
+ <div className={className}>
139
+ <button
140
+ type="button"
141
+ aria-expanded="true"
142
+ aria-label={`Collapse message from ${sender}`}
143
+ onClick={onCollapse}
144
+ className={cn(
145
+ className,
146
+ "focus-visible:ring-ring rounded-sm outline-none focus-visible:ring-2"
147
+ )}
148
+ >
149
+ {content}
150
+ </button>
151
+ {blocked}
152
+ </div>
153
+ );
154
+ }
155
+
156
+ /** The expanded header's full From/To/Date list, with one line about the sender's authentication. */
157
+ export function MessageDetails({
158
+ message,
159
+ onShowOriginal,
160
+ }: {
161
+ message: MessageDetail;
162
+ onShowOriginal?: () => void;
163
+ }) {
164
+ const rows: [string, ReactNode][] = [
165
+ [
166
+ "From",
167
+ message.fromName
168
+ ? `${message.fromName} <${message.fromAddress}>`
169
+ : message.fromAddress,
170
+ ],
171
+ ["To", message.toAddresses.join(", ") || "—"],
172
+ ];
173
+
174
+ if (message.ccAddresses.length) {
175
+ rows.push(["Cc", message.ccAddresses.join(", ")]);
176
+ }
177
+
178
+ if (message.bccAddresses.length) {
179
+ rows.push(["Bcc", message.bccAddresses.join(", ")]);
180
+ }
181
+
182
+ if (message.replyToAddresses.length) {
183
+ rows.push(["Reply-to", message.replyToAddresses.join(", ")]);
184
+ }
185
+
186
+ if (message.viaList) rows.push(["Mailing list", message.viaList]);
187
+ rows.push(["Date", fullDate(message.timelineAt)]);
188
+ // One security line; the full analysis (IP, AI check, headers) lives in Show original.
189
+ const { security } = message;
190
+
191
+ if ((security && security.verdict !== "unavailable") || onShowOriginal) {
192
+ const verdict =
193
+ security && security.verdict !== "unavailable"
194
+ ? verdictCopy[security.verdict]
195
+ : null;
196
+
197
+ // An authentic signature on a message forwarded from someone else's account is not reassurance.
198
+ const copy =
199
+ verdict &&
200
+ security?.warnings.some(
201
+ (warning) => warning.kind === "addressed_elsewhere"
202
+ )
203
+ ? {
204
+ ...verdict,
205
+ title:
206
+ security.verdict === "verified"
207
+ ? "Signed, but forwarded"
208
+ : verdict.title,
209
+ tone: "warn" as const,
210
+ }
211
+ : verdict;
212
+
213
+ rows.push([
214
+ "Security",
215
+ // oxlint-disable-next-line react/jsx-key -- a [label, value] row, rendered with the label as key
216
+ <span className="inline-flex flex-wrap items-baseline gap-x-1.5">
217
+ {copy && (
218
+ <span
219
+ className={cn(
220
+ copy.tone === "pass" && "text-success",
221
+ copy.tone === "warn" && "text-amber-700 dark:text-amber-300"
222
+ )}
223
+ >
224
+ {copy.title}
225
+ </span>
226
+ )}
227
+ {security?.signedBy && (
228
+ <span className="text-muted-foreground">
229
+ · signed by {security.signedBy}
230
+ </span>
231
+ )}
232
+ {security?.forwardedVia && (
233
+ <span className="text-muted-foreground">
234
+ · forwarded via {security.forwardedVia}
235
+ </span>
236
+ )}
237
+ {onShowOriginal && (
238
+ <button
239
+ type="button"
240
+ className="text-foreground font-medium hover:underline"
241
+ onClick={onShowOriginal}
242
+ >
243
+ {copy ? "· Details" : "Show original"}
244
+ </button>
245
+ )}
246
+ </span>,
247
+ ]);
248
+ }
249
+
250
+ return (
251
+ <dl className="bg-surface-sunken ring-border mt-3 grid max-w-2xl grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 rounded-lg px-3.5 py-3 text-xs ring-1 @lg/reader:ml-12">
252
+ {rows.map(([term, value]) => (
253
+ <div key={term} className="contents">
254
+ <dt className="text-muted-foreground">{term}</dt>
255
+ <dd className="[overflow-wrap:anywhere]">{value}</dd>
256
+ </div>
257
+ ))}
258
+ </dl>
259
+ );
260
+ }
@@ -0,0 +1,225 @@
1
+ import { responseJson } from "@open-workspace/core/ui";
2
+ import { useMutation } from "@tanstack/react-query";
3
+ import { Languages, LoaderCircle } from "lucide-react";
4
+ import { useMemo, useState } from "react";
5
+ import { toast } from "sonner";
6
+
7
+ import {
8
+ MAX_TRANSLATION_CHARACTERS,
9
+ MAX_TRANSLATION_SEGMENTS,
10
+ } from "../../shared/mail-translation";
11
+ import { mailApi } from "../lib/mail-api";
12
+ import { EmailHtmlBody, messageTextClassName } from "./email-html-body";
13
+ import { emailHtmlTextSegments } from "./translation-html";
14
+ import { browserLanguage, COMMON_LANGUAGES } from "./translation-language";
15
+ import type { MessageDetail } from "./types";
16
+ import { useSanitizedEmailHtml } from "./use-sanitized-email-html";
17
+
18
+ type TranslationResult = {
19
+ messageId: string;
20
+ language: string;
21
+ translations: string[];
22
+ };
23
+
24
+ export function languageName(code: string) {
25
+ return (
26
+ new Intl.DisplayNames([browserLanguage()], { type: "language" }).of(code) ??
27
+ code
28
+ );
29
+ }
30
+
31
+ export type MessageTranslationState = ReturnType<typeof useMessageTranslation>;
32
+
33
+ /**
34
+ * Translation state for one message: which language was requested, the cached
35
+ * result, and whether the translated text is currently shown.
36
+ */
37
+ export function useMessageTranslation(
38
+ message: MessageDetail,
39
+ mailboxId?: string
40
+ ) {
41
+ const [language, setLanguage] = useState(browserLanguage);
42
+ const [result, setResult] = useState<TranslationResult | null>(null);
43
+ const [showTranslation, setShowTranslation] = useState(false);
44
+ const html = useSanitizedEmailHtml(mailboxId ?? "", message);
45
+
46
+ const sourceHtml =
47
+ message.direction === "incoming"
48
+ ? html.data?.renderAsHtml
49
+ ? html.data.srcDoc
50
+ : null
51
+ : html.data?.composerHtml || null;
52
+
53
+ const segments = useMemo(
54
+ () =>
55
+ sourceHtml
56
+ ? emailHtmlTextSegments(sourceHtml)
57
+ : [message.bodyText || message.preview].filter((text) =>
58
+ Boolean(text.trim())
59
+ ),
60
+ [message.bodyText, message.preview, sourceHtml]
61
+ );
62
+
63
+ const mutation = useMutation({
64
+ mutationFn: async ({
65
+ targetLanguage,
66
+ textSegments,
67
+ }: {
68
+ targetLanguage: string;
69
+ textSegments: string[];
70
+ }) => {
71
+ const response = await mailApi.api.mail.messages[":id"].translate.$post({
72
+ param: { id: message.id },
73
+ query: { mailboxId: mailboxId ?? "" },
74
+ json: { language: targetLanguage, segments: textSegments },
75
+ });
76
+
77
+ return responseJson(response);
78
+ },
79
+ });
80
+
81
+ const cached = result?.messageId === message.id ? result : null;
82
+ const visible = showTranslation && cached?.language === language;
83
+
84
+ const languages = COMMON_LANGUAGES.includes(language)
85
+ ? COMMON_LANGUAGES
86
+ : [language, ...COMMON_LANGUAGES];
87
+
88
+ async function translate(targetLanguage = language) {
89
+ setLanguage(targetLanguage);
90
+
91
+ if (cached?.language === targetLanguage) {
92
+ setShowTranslation(true);
93
+
94
+ return;
95
+ }
96
+
97
+ setShowTranslation(false);
98
+
99
+ if (!segments.length) {
100
+ toast.error("Message has no text to translate");
101
+
102
+ return;
103
+ }
104
+
105
+ if (
106
+ segments.length > MAX_TRANSLATION_SEGMENTS ||
107
+ segments.join("").length > MAX_TRANSLATION_CHARACTERS
108
+ ) {
109
+ toast.error("Message is too long to translate");
110
+
111
+ return;
112
+ }
113
+
114
+ try {
115
+ const response = await mutation.mutateAsync({
116
+ targetLanguage,
117
+ textSegments: segments,
118
+ });
119
+
120
+ setResult({
121
+ messageId: message.id,
122
+ language: targetLanguage,
123
+ translations: response.translations,
124
+ });
125
+ setShowTranslation(true);
126
+ } catch (error) {
127
+ toast.error(
128
+ error instanceof Error
129
+ ? error.message
130
+ : "Could not translate this message"
131
+ );
132
+ }
133
+ }
134
+
135
+ return {
136
+ available: Boolean(mailboxId && (message.bodyText || message.bodyHtml)),
137
+ ready: !(message.bodyHtml && html.isPending),
138
+ pending: mutation.isPending,
139
+ language,
140
+ languages,
141
+ /** Translated text is cached for the current language. */
142
+ hasResult: cached?.language === language,
143
+ visible,
144
+ translations: visible ? cached.translations : undefined,
145
+ sourceHtml,
146
+ translate,
147
+ showOriginal: () => setShowTranslation(false),
148
+ };
149
+ }
150
+
151
+ /** Slim status line shown above a message body while translating or translated. */
152
+ export function TranslationBar({
153
+ translation,
154
+ }: {
155
+ translation: MessageTranslationState;
156
+ }) {
157
+ if (!translation.pending && !translation.visible) return null;
158
+
159
+ return (
160
+ <div
161
+ role="status"
162
+ className="bg-surface-sunken text-muted-foreground ring-border mb-3 flex min-h-8 max-w-[72ch] items-center gap-2 rounded-md px-2.5 py-1.5 text-xs ring-1"
163
+ >
164
+ {translation.pending ? (
165
+ <LoaderCircle className="size-3.5 shrink-0 animate-spin" />
166
+ ) : (
167
+ <Languages className="text-primary size-3.5 shrink-0" />
168
+ )}
169
+ <span className="min-w-0 flex-1 truncate">
170
+ {translation.pending
171
+ ? `Translating to ${languageName(translation.language)}…`
172
+ : `Translated to ${languageName(translation.language)}`}
173
+ </span>
174
+ {translation.visible && (
175
+ <button
176
+ type="button"
177
+ className="text-foreground focus-visible:ring-ring shrink-0 rounded-sm font-medium outline-none hover:underline focus-visible:ring-2"
178
+ onClick={translation.showOriginal}
179
+ >
180
+ Show original
181
+ </button>
182
+ )}
183
+ </div>
184
+ );
185
+ }
186
+
187
+ /** Message body: sanitized HTML, composer HTML or plain text, translated in place when requested. */
188
+ export function MessageBody({
189
+ message,
190
+ mailboxId,
191
+ translation,
192
+ }: {
193
+ message: MessageDetail;
194
+ mailboxId?: string;
195
+ translation: MessageTranslationState;
196
+ }) {
197
+ if (!mailboxId || !(message.bodyText || message.bodyHtml)) {
198
+ return (
199
+ <div className={messageTextClassName}>
200
+ {message.bodyText ||
201
+ (message.quotedText
202
+ ? "No new text"
203
+ : message.preview || "No text body")}
204
+ </div>
205
+ );
206
+ }
207
+
208
+ const { translations } = translation;
209
+
210
+ if (message.bodyHtml && (!translations || translation.sourceHtml)) {
211
+ return (
212
+ <EmailHtmlBody
213
+ mailboxId={mailboxId}
214
+ message={message}
215
+ translations={translations}
216
+ />
217
+ );
218
+ }
219
+
220
+ return (
221
+ <div className={messageTextClassName}>
222
+ {translations ? translations[0] : message.bodyText}
223
+ </div>
224
+ );
225
+ }