@open-workspace/email 0.3.0 → 0.4.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 (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,156 @@
1
+ import { AnnotationMode } from "pdfjs-dist";
2
+ import type { PDFDocumentProxy, RenderTask } from "pdfjs-dist";
3
+ import type { PDFPageView } from "pdfjs-dist/types/web/pdf_page_view";
4
+ import type { PDFViewer } from "pdfjs-dist/web/pdf_viewer.mjs";
5
+ import { useEffect, useState } from "react";
6
+
7
+ import type { PdfTranslationLayout } from "./pdf-translation-layout";
8
+
9
+ export function usePdfTranslationOverlay({
10
+ viewer,
11
+ document,
12
+ page,
13
+ layout,
14
+ language,
15
+ }: {
16
+ viewer: PDFViewer | null;
17
+ document: PDFDocumentProxy | null;
18
+ page: number;
19
+ layout: PdfTranslationLayout | null | undefined;
20
+ language: string;
21
+ }) {
22
+ // A failure belongs to the page and translation it happened for; another
23
+ // one starts without it.
24
+ const [failure, setFailure] = useState<{
25
+ viewer: PDFViewer;
26
+ document: PDFDocumentProxy;
27
+ page: number;
28
+ layout: PdfTranslationLayout;
29
+ language: string;
30
+ } | null>(null);
31
+
32
+ const error =
33
+ failure &&
34
+ failure.viewer === viewer &&
35
+ failure.document === document &&
36
+ failure.page === page &&
37
+ failure.layout === layout &&
38
+ failure.language === language
39
+ ? "Could not render the translated page"
40
+ : null;
41
+
42
+ useEffect(() => {
43
+ if (!viewer || !document || !layout) return;
44
+ let disposeRender = () => {};
45
+ const lifetime = new AbortController();
46
+
47
+ const render = () => {
48
+ disposeRender();
49
+ const view: PDFPageView | undefined = viewer.getPageView(page - 1);
50
+
51
+ if (!view) return;
52
+ let cancelled = false;
53
+ let task: RenderTask | undefined;
54
+ const overlay = window.document.createElement("section");
55
+ overlay.className = "pdf-translation-overlay";
56
+ overlay.setAttribute("aria-label", "PDF translation");
57
+ overlay.lang = language;
58
+ const canvas = window.document.createElement("canvas");
59
+ canvas.setAttribute("aria-hidden", "true");
60
+ overlay.appendChild(canvas);
61
+ disposeRender = () => {
62
+ cancelled = true;
63
+ task?.cancel();
64
+ overlay.remove();
65
+ view.div.classList.remove("pdf-page-translated");
66
+ };
67
+
68
+ void (async () => {
69
+ const pdfPage = await document.getPage(page);
70
+
71
+ if (cancelled) return;
72
+ const viewport = view.viewport.clone();
73
+
74
+ const ratio = Math.min(
75
+ window.devicePixelRatio || 1,
76
+ 2,
77
+ Math.sqrt(16_777_216 / (viewport.width * viewport.height))
78
+ );
79
+
80
+ canvas.width = Math.ceil(viewport.width * ratio);
81
+ canvas.height = Math.ceil(viewport.height * ratio);
82
+ const omitted = new Set(layout.omittedOperations);
83
+ task = pdfPage.render({
84
+ canvas,
85
+ viewport,
86
+ transform: [ratio, 0, 0, ratio, 0, 0],
87
+ annotationMode: AnnotationMode.DISABLE,
88
+ operationsFilter: (index) => !omitted.has(index),
89
+ });
90
+ await task.promise;
91
+
92
+ if (cancelled) return;
93
+ const layer = window.document.createElement("div");
94
+ layer.className = "pdf-translated-text";
95
+ layer.style.width = `${layout.width}px`;
96
+ layer.style.height = `${layout.height}px`;
97
+ // PDF.js rounds page dimensions to device pixels. Match the canvas CSS size.
98
+ layer.style.transform = `scale(${view.div.clientWidth / layout.width}, ${view.div.clientHeight / layout.height})`;
99
+
100
+ const measure = window.document
101
+ .createElement("canvas")
102
+ .getContext("2d");
103
+
104
+ if (!measure) throw new Error("No 2D canvas to measure text");
105
+
106
+ for (const block of layout.blocks) {
107
+ const span = window.document.createElement("span");
108
+ span.textContent = block.text;
109
+ span.dir = "auto";
110
+ const font = `${block.italic ? "italic" : "normal"} ${block.bold ? "bold" : "normal"}`;
111
+ measure.font = `${font} ${block.fontSize}px ${block.fontFamily}`;
112
+
113
+ // Stay inside the source line's bounds so a longer translation cannot
114
+ // overwrite neighbouring table cells. Preserve its vertical centre.
115
+ const size =
116
+ block.fontSize *
117
+ Math.min(
118
+ 1,
119
+ block.width / Math.max(1, measure.measureText(block.text).width)
120
+ );
121
+
122
+ Object.assign(span.style, {
123
+ left: `${block.x}px`,
124
+ top: `${block.y + (block.fontSize - size) / 2}px`,
125
+ width: `${block.width}px`,
126
+ font: `${font} ${size}px / 1 ${block.fontFamily}`,
127
+ });
128
+ layer.appendChild(span);
129
+ }
130
+
131
+ overlay.appendChild(layer);
132
+ view.div.appendChild(overlay);
133
+ view.div.classList.add("pdf-page-translated");
134
+ setFailure(null);
135
+ })().catch(() => {
136
+ if (cancelled) return;
137
+ disposeRender();
138
+ setFailure({ viewer, document, page, layout, language });
139
+ });
140
+ };
141
+
142
+ const rerender = ({ pageNumber }: { pageNumber: number }) => {
143
+ if (pageNumber === page) render();
144
+ };
145
+
146
+ viewer.eventBus.on("pagerendered", rerender, { signal: lifetime.signal });
147
+ render();
148
+
149
+ return () => {
150
+ lifetime.abort();
151
+ disposeRender();
152
+ };
153
+ }, [viewer, document, page, layout, language]);
154
+
155
+ return error;
156
+ }
@@ -0,0 +1,100 @@
1
+ import { responseJson } from "@open-workspace/core/ui";
2
+ import { useQuery } from "@tanstack/react-query";
3
+ import type { PDFDocumentProxy } from "pdfjs-dist";
4
+ import { useState } from "react";
5
+
6
+ import {
7
+ MAX_TRANSLATION_CHARACTERS,
8
+ MAX_TRANSLATION_SEGMENTS,
9
+ } from "../../shared/mail-translation";
10
+ import { mailApi } from "../lib/mail-api";
11
+ import { getPdfTranslationLayout } from "./pdf-translation-layout";
12
+ import type { PdfTranslationLayout } from "./pdf-translation-layout";
13
+ import { browserLanguage } from "./translation-language";
14
+
15
+ /** The layout with its translated blocks' text replaced, in order. */
16
+ function withTranslations(
17
+ layout: PdfTranslationLayout,
18
+ translations: readonly string[]
19
+ ): PdfTranslationLayout {
20
+ let index = 0;
21
+
22
+ return {
23
+ ...layout,
24
+ blocks: layout.blocks.map((block) => {
25
+ if (!block.translate) return block;
26
+ const text = translations[index] ?? block.text;
27
+ index += 1;
28
+
29
+ return { ...block, text: text.replaceAll(/\s+/gu, " ") };
30
+ }),
31
+ };
32
+ }
33
+
34
+ export function usePdfTranslation({
35
+ document,
36
+ page,
37
+ url,
38
+ messageId,
39
+ mailboxId,
40
+ }: {
41
+ document: PDFDocumentProxy | null;
42
+ page: number;
43
+ url: string;
44
+ messageId: string;
45
+ mailboxId: string;
46
+ }) {
47
+ const [visible, setVisible] = useState(false);
48
+ const [language, setLanguage] = useState(browserLanguage);
49
+
50
+ const translation = useQuery({
51
+ queryKey: ["pdf-inline-translation", url, page, language],
52
+ enabled: visible && Boolean(document),
53
+ staleTime: Infinity,
54
+ retry: false,
55
+ queryFn: async ({ signal }) => {
56
+ if (!document) throw new Error("PDF is not loaded");
57
+ const pdfPage = await document.getPage(page);
58
+ const layout = await getPdfTranslationLayout(pdfPage);
59
+
60
+ if (!layout.blocks.length) return null;
61
+
62
+ const segments = layout.blocks
63
+ .filter((block) => block.translate)
64
+ .map((block) => block.text);
65
+
66
+ if (!segments.length) return layout;
67
+
68
+ if (
69
+ segments.length > MAX_TRANSLATION_SEGMENTS ||
70
+ segments.join("").length > MAX_TRANSLATION_CHARACTERS
71
+ ) {
72
+ throw new Error("Page is too long to translate");
73
+ }
74
+
75
+ signal.throwIfAborted();
76
+
77
+ const response = await mailApi.api.mail.messages[":id"].translate.$post(
78
+ {
79
+ param: { id: messageId },
80
+ query: { mailboxId },
81
+ json: { language, segments },
82
+ },
83
+ { init: { signal } }
84
+ );
85
+
86
+ const { translations } = await responseJson(response);
87
+
88
+ if (
89
+ translations.length !== segments.length ||
90
+ translations.some((text) => !text.trim())
91
+ ) {
92
+ throw new Error("Incomplete page translation");
93
+ }
94
+
95
+ return withTranslations(layout, translations);
96
+ },
97
+ });
98
+
99
+ return { visible, setVisible, language, setLanguage, translation };
100
+ }
@@ -0,0 +1,215 @@
1
+ import {
2
+ AnnotationMode,
3
+ getDocument,
4
+ GlobalWorkerOptions,
5
+ version,
6
+ } from "pdfjs-dist";
7
+ import type { PDFDocumentProxy } from "pdfjs-dist";
8
+ // oxlint-disable-next-line import/default -- Vite's ?url import has a default export
9
+ import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
10
+ import {
11
+ EventBus,
12
+ PDFViewer,
13
+ PDFLinkService,
14
+ PDFFindController,
15
+ LinkTarget,
16
+ } from "pdfjs-dist/web/pdf_viewer.mjs";
17
+ import { useEffect, useRef, useState } from "react";
18
+
19
+ import { pdfjsAssetUrls } from "../../shared/pdfjs-assets";
20
+
21
+ GlobalWorkerOptions.workerSrc = workerUrl;
22
+
23
+ export function usePdfViewer(url: string) {
24
+ const containerRef = useRef<HTMLDivElement>(null);
25
+ const pagesRef = useRef<HTMLDivElement>(null);
26
+ const viewerRef = useRef<PDFViewer | null>(null);
27
+ const [viewer, setViewer] = useState<PDFViewer | null>(null);
28
+ const [document, setDocument] = useState<PDFDocumentProxy | null>(null);
29
+ const [page, setPage] = useState(1);
30
+ const [scale, setScale] = useState(1);
31
+ const [ready, setReady] = useState(false);
32
+ const [error, setError] = useState<string | null>(null);
33
+ const [matches, setMatches] = useState({ current: 0, total: 0 });
34
+
35
+ useEffect(() => {
36
+ const container = containerRef.current;
37
+ const pages = pagesRef.current;
38
+
39
+ if (!container || !pages) return;
40
+ const lifetime = new AbortController();
41
+ const eventBus = new EventBus();
42
+
43
+ const linkService = new PDFLinkService({
44
+ eventBus,
45
+ externalLinkTarget: LinkTarget.BLANK,
46
+ });
47
+
48
+ const findController = new PDFFindController({ eventBus, linkService });
49
+
50
+ const options = {
51
+ container,
52
+ viewer: pages,
53
+ eventBus,
54
+ linkService,
55
+ findController,
56
+ // Read-only attachments: no form editing, document scripts, or automatic downloads.
57
+ annotationMode: AnnotationMode.ENABLE,
58
+ maxCanvasPixels: 16_777_216,
59
+ abortSignal: lifetime.signal,
60
+ };
61
+
62
+ const pdfViewer = new PDFViewer(options);
63
+ viewerRef.current = pdfViewer;
64
+ linkService.setViewer(pdfViewer);
65
+
66
+ // Re-fit when the viewport changes. PDFViewer's
67
+ // own observer updates dimensions, but does not recalculate named zoom levels.
68
+ const resize = new ResizeObserver(() => {
69
+ if (!pdfViewer.pdfDocument) return;
70
+
71
+ if (pdfViewer.currentScaleValue === "page-width") {
72
+ pdfViewer.currentScaleValue = "page-width";
73
+ }
74
+
75
+ pdfViewer.update();
76
+ });
77
+
78
+ resize.observe(container);
79
+ const listenerOptions = { signal: lifetime.signal };
80
+ eventBus.on(
81
+ "pagesinit",
82
+ () => {
83
+ pdfViewer.currentScaleValue = "page-width";
84
+ setReady(true);
85
+ },
86
+ listenerOptions
87
+ );
88
+ eventBus.on(
89
+ "pagechanging",
90
+ ({ pageNumber }: { pageNumber: number }) => setPage(pageNumber),
91
+ listenerOptions
92
+ );
93
+ eventBus.on(
94
+ "scalechanging",
95
+ ({ scale: nextScale }: { scale: number }) => setScale(nextScale),
96
+ listenerOptions
97
+ );
98
+
99
+ const updateMatches = ({
100
+ matchesCount,
101
+ }: {
102
+ matchesCount: { current: number; total: number };
103
+ }) => setMatches(matchesCount);
104
+
105
+ eventBus.on("updatefindmatchescount", updateMatches, listenerOptions);
106
+ eventBus.on("updatefindcontrolstate", updateMatches, listenerOptions);
107
+ eventBus.on(
108
+ "pagerendered",
109
+ ({ error: renderError }: { error?: Error }) => {
110
+ if (renderError) setError("Could not render this PDF");
111
+ },
112
+ listenerOptions
113
+ );
114
+
115
+ const task = getDocument({
116
+ url,
117
+ ...pdfjsAssetUrls(version),
118
+ enableXfa: false,
119
+ });
120
+
121
+ void task.promise
122
+ .then(async (pdf) => {
123
+ if (lifetime.signal.aborted) return;
124
+ linkService.setDocument(pdf);
125
+ pdfViewer.setDocument(pdf);
126
+ setViewer(pdfViewer);
127
+ setDocument(pdf);
128
+ // PDFViewer reports initialization failures via its pages promise.
129
+ await pdfViewer.pagesPromise;
130
+ })
131
+ .catch((cause: unknown) => {
132
+ if (lifetime.signal.aborted) return;
133
+ setError(
134
+ cause instanceof Error && cause.name === "PasswordException"
135
+ ? "This PDF requires a password"
136
+ : "Could not open this PDF"
137
+ );
138
+ });
139
+
140
+ return () => {
141
+ resize.disconnect();
142
+ lifetime.abort();
143
+
144
+ // SAFETY: PDF.js explicitly accepts null to detach (setDocument checks
145
+ // for it); its generated declaration omits null.
146
+ const detach = pdfViewer.setDocument as (
147
+ document: PDFDocumentProxy | null
148
+ ) => void;
149
+
150
+ detach.call(pdfViewer, null);
151
+ linkService.setDocument(null);
152
+ viewerRef.current = null;
153
+ void task.destroy();
154
+ };
155
+ }, [url]);
156
+
157
+ function find(query: string, again = false, previous = false) {
158
+ viewerRef.current?.eventBus.dispatch("find", {
159
+ source: containerRef.current,
160
+ type: again ? "again" : "",
161
+ query,
162
+ caseSensitive: false,
163
+ entireWord: false,
164
+ highlightAll: true,
165
+ findPrevious: previous,
166
+ matchDiacritics: false,
167
+ });
168
+ }
169
+
170
+ /** Moves to a page in range; returns the page shown afterwards. */
171
+ function goToPage(target: number) {
172
+ const { current } = viewerRef;
173
+
174
+ if (!current) return 1;
175
+
176
+ if (
177
+ Number.isInteger(target) &&
178
+ target >= 1 &&
179
+ target <= current.pagesCount
180
+ ) {
181
+ current.currentPageNumber = target;
182
+ }
183
+
184
+ return current.currentPageNumber;
185
+ }
186
+
187
+ function zoomIn() {
188
+ viewerRef.current?.increaseScale();
189
+ }
190
+
191
+ function zoomOut() {
192
+ viewerRef.current?.decreaseScale();
193
+ }
194
+
195
+ function fitWidth() {
196
+ if (viewerRef.current) viewerRef.current.currentScaleValue = "page-width";
197
+ }
198
+
199
+ return {
200
+ containerRef,
201
+ pagesRef,
202
+ viewer,
203
+ document,
204
+ page,
205
+ scale,
206
+ ready,
207
+ error,
208
+ matches,
209
+ find,
210
+ goToPage,
211
+ zoomIn,
212
+ zoomOut,
213
+ fitWidth,
214
+ };
215
+ }
@@ -0,0 +1,114 @@
1
+ import type { ValidatedComposerRecipients } from "./composer-recipients";
2
+ import { isUploadedAsset } from "./composer-session";
3
+ import type { ComposerSession, ComposerSessionPhase } from "./composer-session";
4
+ import { notifyOutboundResult } from "./outbound-notification";
5
+ import type { Mailbox, MessageDetail, ReplyAction } from "./types";
6
+ import { resolveComposerAttachmentPlan } from "./use-composer-attachment-preflight";
7
+ import { useComposerSubmission } from "./use-composer-submission";
8
+ import type { PreparedComposerSubmission } from "./use-composer-submission";
9
+ import type { MailSendDraft, SubmittedMessage } from "./use-mail-send";
10
+
11
+ export type SentReply = Pick<SubmittedMessage, "conversationId" | "detached">;
12
+
13
+ type ReplySubmissionInput = {
14
+ session: ComposerSession;
15
+ phase: ComposerSessionPhase;
16
+ mailbox?: Mailbox;
17
+ parent: MessageDetail;
18
+ action?: ReplyAction;
19
+ recipients: ValidatedComposerRecipients;
20
+ body: string;
21
+ uploadLimitError: string | null;
22
+ uploadsPending: boolean;
23
+ uploadsFailed: boolean;
24
+ onSuccess: (result: SentReply) => void;
25
+ };
26
+
27
+ export function useReplySubmission(input: ReplySubmissionInput) {
28
+ return useComposerSubmission({
29
+ session: input.session,
30
+ phase: input.phase,
31
+ validate: () => replySubmissionValidationError(input),
32
+ prepare: (signal) => prepareReplySubmission(input, signal),
33
+ failureLabel: "Could not send reply",
34
+ onSuccess: (result) => {
35
+ notifyOutboundResult(result, "reply");
36
+ input.onSuccess({
37
+ conversationId: result.conversationId,
38
+ detached: result.detached,
39
+ });
40
+ },
41
+ });
42
+ }
43
+
44
+ function replySubmissionValidationError(input: ReplySubmissionInput) {
45
+ if (!input.mailbox?.canSend || !input.action) {
46
+ return "Reply is no longer available";
47
+ }
48
+
49
+ if (input.recipients.error) return input.recipients.error;
50
+
51
+ if (input.uploadLimitError) return input.uploadLimitError;
52
+
53
+ if (input.uploadsPending) {
54
+ return "Wait for attachments to finish uploading";
55
+ }
56
+
57
+ if (input.uploadsFailed) return "Retry or remove failed attachments";
58
+
59
+ if (!input.body.trim()) return "Add text to the reply before sending";
60
+
61
+ return null;
62
+ }
63
+
64
+ async function prepareReplySubmission(
65
+ input: ReplySubmissionInput,
66
+ signal: AbortSignal
67
+ ): Promise<PreparedComposerSubmission> {
68
+ if (!input.mailbox || !input.action) {
69
+ throw new Error("Reply is no longer available");
70
+ }
71
+
72
+ const submittedAssets = input.session
73
+ .getSnapshot()
74
+ .assets.filter(isUploadedAsset);
75
+
76
+ if (submittedAssets.length) {
77
+ await resolveComposerAttachmentPlan(
78
+ input.session,
79
+ {
80
+ kind: "reply",
81
+ mailboxId: input.mailbox.id,
82
+ sourceEmailId: input.parent.id,
83
+ mode: input.action.mode,
84
+ cc: input.recipients.cc,
85
+ bcc: input.recipients.bcc,
86
+ bodyText: input.body,
87
+ },
88
+ submittedAssets,
89
+ signal
90
+ );
91
+ }
92
+
93
+ const uploadedAttachments = submittedAssets.map((asset) => ({
94
+ uploadId: asset.uploadId,
95
+ disposition: "attachment" as const,
96
+ }));
97
+
98
+ const command: MailSendDraft = {
99
+ kind: "reply",
100
+ mailboxId: input.mailbox.id,
101
+ cc: input.recipients.cc,
102
+ bcc: input.recipients.bcc,
103
+ bodyText: input.body,
104
+ uploadedAttachments,
105
+ parentEmailId: input.parent.id,
106
+ mode: input.action.mode,
107
+ };
108
+
109
+ return {
110
+ assetIds: submittedAssets.map((asset) => asset.id),
111
+ command,
112
+ submissionKey: JSON.stringify(command),
113
+ };
114
+ }
@@ -0,0 +1,20 @@
1
+ import { useQuery } from "@tanstack/react-query";
2
+
3
+ import { sanitizedHtmlQuery } from "./mail-queries";
4
+ import type { MessageDetail } from "./types";
5
+
6
+ export function useSanitizedEmailHtml(
7
+ mailboxId: string,
8
+ message: MessageDetail
9
+ ) {
10
+ return useQuery({
11
+ ...sanitizedHtmlQuery(mailboxId, message),
12
+ // A new remote token re-sanitizes the same message: keep showing the
13
+ // document it replaces rather than a skeleton.
14
+ placeholderData: (previous, previousQuery) =>
15
+ previousQuery?.queryKey[1] === mailboxId &&
16
+ previousQuery.queryKey[2] === message.id
17
+ ? previous
18
+ : undefined,
19
+ });
20
+ }