The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 17:00 UTC
feat(web): preview office files, fonts, and mermaid diagrams (#21362)
maria committed
Oct 26, 2026 at 02:17 UTC
d69810a97a98747e165b641a51fb1a3080f8382f
54 files changed
+8370
-93
apps/desktop/src/ipc/methods/window.test.ts
+75
@@ -20,9 +20,13 @@ vi.mock("electron", () => ({
20
import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
21
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
22
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
23
+import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
24
+import * as ElectronDialog from "../../electron/ElectronDialog.ts";
25
+import * as ElectronWindow from "../../electron/ElectronWindow.ts";
26
import {
27
getLocalEnvironmentBootstraps,
28
getRelayTelemetryEnabled,
29
+ pickProjectFavicon,
30
probeRemoteEditors,
31
} from "./window.ts";
32
@@ -192,6 +196,77 @@ describe("getRelayTelemetryEnabled", () => {
196
);
197
});
198
199
+describe("pickProjectFavicon", () => {
200
+ const pickerLayer = (
201
+ pickFiles: () => Effect.Effect<Array<string>>,
202
+ settings?: DesktopAppSettings.DesktopSettings,
203
+ ) =>
204
+ Layer.mergeAll(
205
+ Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }),
206
+ Layer.mock(ElectronWindow.ElectronWindow)({
207
+ focusedMainOrFirst: Effect.succeedNone,
208
+ }),
209
+ DesktopAppSettings.layerTest(settings),
210
+ );
211
+
212
+ it.effect("opens a single-image picker from the project directory", () =>
213
+ Effect.gen(function* () {
214
+ const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
215
+ const result = yield* pickProjectFavicon
216
+ .handler("/project")
217
+ .pipe(Effect.provide(pickerLayer(pickFiles)));
218
+
219
+ assert.strictEqual(result, "/pictures/icon.png");
220
+ assert.deepEqual(pickFiles.mock.calls, [
221
+ [
222
+ {
223
+ owner: Option.none(),
224
+ defaultPath: Option.some("/project"),
225
+ multiple: false,
226
+ filters: [
227
+ {
228
+ name: "Images",
229
+ extensions: [
230
+ "avif",
231
+ "bmp",
232
+ "gif",
233
+ "ico",
234
+ "heic",
235
+ "jpeg",
236
+ "jpg",
237
+ "png",
238
+ "svg",
239
+ "tif",
240
+ "tiff",
241
+ "webp",
242
+ "icns",
243
+ ],
244
+ },
245
+ ],
246
+ },
247
+ ],
248
+ ]);
249
+ }),
250
+ );
251
+
252
+ it.effect("does not open a picker while the local environment is off", () =>
253
+ Effect.gen(function* () {
254
+ const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
255
+ const result = yield* pickProjectFavicon.handler("/project").pipe(
256
+ Effect.provide(
257
+ pickerLayer(pickFiles, {
258
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
259
+ localEnvironmentEnabled: false,
260
+ }),
261
+ ),
262
+ );
263
+
264
+ assert.strictEqual(result, null);
265
+ assert.strictEqual(pickFiles.mock.calls.length, 0);
266
+ }),
267
+ );
268
+});
269
+
270
it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
271
"finds remote editors installed without PATH launchers",
272
() =>
apps/mobile/src/components/ComposerContextSheet.tsx
+1
-1
@@ -111,7 +111,7 @@ export function ComposerContextSheet(props: {
111
: undefined;
112
if (record && !("payload" in record) && (record.kind === "image" || record.kind === "file")) {
113
const mimeType = videoMimeType(record) ?? record.mimeType;
114
- const previewKind = filePreviewKind(record);
114
+ const previewKind = filePreviewKind(record, { richDocuments: false });
115
const resource = {
116
_tag: "attachment" as const,
117
attachmentId: record.attachmentId,
apps/mobile/src/lib/attachmentDocument.ts
+1
-1
@@ -29,7 +29,7 @@ export function useAttachmentDocument(input: {
29
readonly environmentId: EnvironmentId | null;
30
readonly attachment: FileBackedComposerAttachment | null;
31
}) {
32
- const kind = filePreviewKind(input);
32
+ const kind = filePreviewKind(input, { richDocuments: false });
33
const delimiter = filePreviewDelimiter(input);
34
const shareController = useRef<AbortController | null>(null);
35
useEffect(() => () => shareController.current?.abort(), []);
apps/mobile/src/lib/attachmentDocumentPresentation.test.ts
new
+28
@@ -0,0 +1,28 @@
1
+import { expect, it } from "vite-plus/test";
2
+import { filePreviewKind } from "@t3tools/shared/filePreview";
3
+
4
+it.each([
5
+ [
6
+ "report.docx",
7
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
8
+ "unsupported",
9
+ ],
10
+ [
11
+ "budget.xlsx",
12
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
13
+ "unsupported",
14
+ ],
15
+ [
16
+ "deck.pptx",
17
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
18
+ "unsupported",
19
+ ],
20
+ ["report.docx", "text/plain", "text"],
21
+ ["report.docx", "application/octet-stream", "unsupported"],
22
+ ["chart.mmd", "text/vnd.mermaid", "text"],
23
+ ["chart.mermaid", "text/plain", "text"],
24
+ ["chart.mmd", "application/octet-stream", "unsupported"],
25
+ ["font.ttf", "font/ttf", "unsupported"],
26
+] as const)("preserves mobile's existing path for %s (%s)", (name, mimeType, expected) => {
27
+ expect(filePreviewKind({ name, mimeType }, { richDocuments: false })).toBe(expected);
28
+});
apps/mobile/src/lib/composerContext.ts
+1
-1
@@ -78,7 +78,7 @@ export function composerDocumentAttachmentRecord(
78
): ComposerDocumentAttachment | null {
79
if (!record || "payload" in record || record.kind !== "file") return null;
80
if (videoMimeType(record) !== null) return null;
81
- const kind = filePreviewKind(record);
81
+ const kind = filePreviewKind(record, { richDocuments: false });
82
if (kind === "image" || kind === "pdf" || kind === "video") return null;
83
return record;
84
}
apps/server/src/assets/AssetAccess.test.ts
+114
-2
@@ -915,9 +915,49 @@ describe("AssetAccess", () => {
915
kind: "file",
916
path: canonicalCssPath,
917
});
918
+ for (const extension of ["otf", "ttf", "woff", "woff2"]) {
919
+ const fontName = `preview.${extension}`;
920
+ const fontPath = path.join(root, fontName);
921
+ yield* fileSystem.writeFileString(fontPath, "font bytes");
922
+ const canonicalFontPath = yield* fileSystem.realPath(fontPath);
923
+ for (const resource of [
924
+ { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },
925
+ { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },
926
+ ]) {
927
+ const url = yield* issueAssetUrl({ resource, workspaceRoot: root });
928
+ const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
929
+ expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), fontName)).toEqual({
930
+ kind: "file",
931
+ path: canonicalFontPath,
932
+ });
933
+ }
934
+ }
935
expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
936
expect(yield* resolveAsset(token, ".env")).toBeNull();
937
expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
938
+ for (const extension of [
939
+ "docx",
940
+ "xlsx",
941
+ "pptx",
942
+ "bmp",
943
+ "heic",
944
+ "tif",
945
+ "tiff",
946
+ "weba",
947
+ "mmd",
948
+ "mermaid",
949
+ ]) {
950
+ const siblingName = `private.${extension}`;
951
+ yield* fileSystem.writeFileString(path.join(root, siblingName), "private sibling");
952
+ for (const resource of [
953
+ { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },
954
+ { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },
955
+ ]) {
956
+ const url = yield* issueAssetUrl({ resource, workspaceRoot: root });
957
+ const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
958
+ expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), siblingName)).toBeNull();
959
+ }
960
+ }
961
}).pipe(Effect.provide(layerTest)),
962
);
963
@@ -955,6 +995,58 @@ describe("AssetAccess", () => {
995
}).pipe(Effect.provide(layerTest)),
996
);
997
998
+ it.effect("issues exact workspace URLs for image, office, and font previews", () =>
999
+ Effect.gen(function* () {
1000
+ const fileSystem = yield* FileSystem.FileSystem;
1001
+ const path = yield* Path.Path;
1002
+ const root = yield* fileSystem.makeTempDirectoryScoped({
1003
+ prefix: "t3-asset-image-workspace-",
1004
+ });
1005
+ const assetsDirectory = path.join(root, "assets");
1006
+ yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
1007
+ yield* fileSystem.writeFileString(
1008
+ path.join(assetsDirectory, "private.docx"),
1009
+ "private document",
1010
+ );
1011
+ for (const extension of [
1012
+ "png",
1013
+ "bmp",
1014
+ "heic",
1015
+ "tif",
1016
+ "tiff",
1017
+ "docx",
1018
+ "xlsx",
1019
+ "pptx",
1020
+ "ttf",
1021
+ "otf",
1022
+ "woff",
1023
+ "woff2",
1024
+ ]) {
1025
+ const name = `preview.${extension}`;
1026
+ const filePath = path.join(assetsDirectory, name);
1027
+ const siblingName = `other.${extension}`;
1028
+ yield* fileSystem.writeFileString(filePath, "preview");
1029
+ yield* fileSystem.writeFileString(
1030
+ path.join(assetsDirectory, siblingName),
1031
+ "private sibling",
1032
+ );
1033
+ const canonicalPath = yield* fileSystem.realPath(filePath);
1034
+ for (const resource of [
1035
+ { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: filePath },
1036
+ { _tag: "draft-workspace-file" as const, cwd: root, path: `assets/${name}` },
1037
+ ]) {
1038
+ const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
1039
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1040
+ const token = suffix.slice(0, suffix.indexOf("/"));
1041
+ expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalPath });
1042
+ expect(yield* resolveAsset(token, siblingName)).toBeNull();
1043
+ expect(yield* resolveAsset(token, "private.docx")).toBeNull();
1044
+ expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
1045
+ }
1046
+ }
1047
+ }).pipe(Effect.provide(layerTest)),
1048
+ );
1049
+
1050
it.effect("previews workspace files with literal fragment characters in their paths", () =>
1051
Effect.gen(function* () {
1052
const fileSystem = yield* FileSystem.FileSystem;
@@ -963,7 +1055,21 @@ describe("AssetAccess", () => {
1055
const directory = path.join(root, "assets#archive");
1056
yield* fileSystem.makeDirectory(directory);
1057
966
- for (const name of ["icon#v2.png", "report#draft.pdf"]) {
1058
+ for (const name of [
1059
+ "icon#v2.png",
1060
+ "report#draft.pdf",
1061
+ "report.docx",
1062
+ "workbook.xlsx",
1063
+ "slides.pptx",
1064
+ "specimen.ttf",
1065
+ "specimen.otf",
1066
+ "specimen.woff",
1067
+ "specimen.woff2",
1068
+ "image.bmp",
1069
+ "image.heic",
1070
+ "image.tif",
1071
+ "image.tiff",
1072
+ ]) {
1073
const filePath = path.join(directory, name);
1074
yield* fileSystem.writeFileString(filePath, "preview fixture");
1075
const canonicalFile = yield* fileSystem.realPath(filePath);
@@ -1049,6 +1155,12 @@ describe("AssetAccess", () => {
1155
for (const [extension, mimeType] of [
1156
["pdf", "application/pdf"],
1157
["svg", "image/svg+xml"],
1158
+ ["bmp", "image/bmp"],
1159
+ ["ttf", "font/ttf"],
1160
+ ["otf", "font/otf"],
1161
+ ["woff", "font/woff"],
1162
+ ["woff2", "font/woff2"],
1163
+ ["weba", "audio/webm"],
1164
] as const) {
1165
const attachmentId = `thread-1-00000000-0000-4000-8000-000000000001-${extension}`;
1166
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);
@@ -1059,7 +1171,7 @@ describe("AssetAccess", () => {
1171
_tag: "attachment",
1172
attachmentId,
1173
fileName: `report.${extension}`,
1062
- mimeType,
1174
+ mimeType: "application/octet-stream",
1175
disposition: "inline",
1176
},
1177
});
apps/server/src/assets/AssetAccess.ts
+32
-19
@@ -19,14 +19,14 @@ import {
19
TurnItemId,
20
} from "@t3tools/contracts";
21
import {
22
- audioMimeTypeFromExtension,
22
hostPreviewMimeTypeFromExtension,
23
+ officePreviewKind,
24
isWorkspaceAudioPreviewPath,
25
isWorkspaceImagePreviewPath,
26
+ isWorkspaceFontPreviewPath,
27
isWorkspacePreviewEntryPath,
28
isWorkspaceVideoPreviewPath,
29
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
29
- WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
30
} from "@t3tools/shared/filePreview";
31
import {
32
IMAGE_DIMENSIONS_HEADER_BYTES,
@@ -88,10 +88,20 @@ const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
88
htm: "text/html",
89
};
90
const inlinePreviewMimeTypeForExtension = (extension: string) =>
91
- INLINE_PREVIEW_MIME_TYPES[extension] ?? audioMimeTypeFromExtension(`.${extension}`) ?? undefined;
91
+ INLINE_PREVIEW_MIME_TYPES[extension] ??
92
+ hostPreviewMimeTypeFromExtension(`.${extension}`) ??
93
+ undefined;
94
const PREVIEW_ASSET_EXTENSIONS = new Set([
95
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
94
- ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
96
+ // Keep HTML dependency grants independent of newly supported file viewers.
97
+ ".avif",
98
+ ".gif",
99
+ ".ico",
100
+ ".jpeg",
101
+ ".jpg",
102
+ ".png",
103
+ ".svg",
104
+ ".webp",
105
".css",
106
".js",
107
".mjs",
@@ -507,21 +517,24 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
517
? yield* readImageDimensionsFromHeader(canonicalFile)
518
: null;
519
return {
510
- claims: isWorkspaceImagePreviewPath(resolved.relativePath)
511
- ? {
512
- version: 1 as const,
513
- kind: "workspace-file-exact" as const,
514
- workspaceRoot: canonicalWorkspaceRoot,
515
- relativePath: resolved.relativePath,
516
- expiresAt: input.expiresAt,
517
- }
518
- : {
519
- version: 1 as const,
520
- kind: "workspace-file" as const,
521
- workspaceRoot: canonicalWorkspaceRoot,
522
- baseRelativePath: path.dirname(resolved.relativePath),
523
- expiresAt: input.expiresAt,
524
- },
520
+ claims:
521
+ isWorkspaceImagePreviewPath(resolved.relativePath) ||
522
+ isWorkspaceFontPreviewPath(resolved.relativePath) ||
523
+ officePreviewKind({ name: resolved.relativePath }) !== null
524
+ ? {
525
+ version: 1 as const,
526
+ kind: "workspace-file-exact" as const,
527
+ workspaceRoot: canonicalWorkspaceRoot,
528
+ relativePath: resolved.relativePath,
529
+ expiresAt: input.expiresAt,
530
+ }
531
+ : {
532
+ version: 1 as const,
533
+ kind: "workspace-file" as const,
534
+ workspaceRoot: canonicalWorkspaceRoot,
535
+ baseRelativePath: path.dirname(resolved.relativePath),
536
+ expiresAt: input.expiresAt,
537
+ },
538
fileName: path.basename(resolved.relativePath),
539
imageDimensions,
540
fileRevision: undefined,
apps/web/package.json
+5
@@ -13,6 +13,10 @@
13
},
14
"dependencies": {
15
"@base-ui/react": "^1.4.1",
16
+ "@betteroffice/docx": "0.4.3",
17
+ "@betteroffice/fonts": "0.4.0",
18
+ "@betteroffice/pptx": "0.2.0",
19
+ "@betteroffice/xlsx": "0.3.0",
20
"@clerk/clerk-js": "catalog:",
21
"@clerk/electron": "catalog:",
22
"@clerk/react": "catalog:",
@@ -74,6 +78,7 @@
78
"remark-gfm": "catalog:",
79
"remark-math": "6.0.0",
80
"remark-parse": "catalog:",
81
+ "saxes": "6.0.0",
82
"tailwind-merge": "^3.4.0",
83
"unbash": "^5.0.0",
84
"unified": "catalog:",
apps/web/src/components/chat/composerAttachmentFiles.test.ts
+18
-18
@@ -18,7 +18,7 @@ import {
18
} from "./composerAttachmentFiles";
19
20
describe("composer attachment files", () => {
21
- it("attaches SVG as a file and rejects other unsupported images", () => {
21
+ it("keeps previewable images providers cannot accept on the file path", () => {
22
expect(classifyComposerAttachmentFile({ name: "diagram.svg", type: "image/svg+xml" })).toBe(
23
"file",
24
);
@@ -26,12 +26,14 @@ describe("composer attachment files", () => {
26
expect(
27
classifyComposerAttachmentFile({ name: "diagram.svg", type: "application/octet-stream" }),
28
).toBe("file");
29
- expect(classifyComposerAttachmentFile({ name: "photo.tiff", type: "image/tiff" })).toBe(
30
- "unsupported-image",
31
- );
29
+ expect(classifyComposerAttachmentFile({ name: "photo.tiff", type: "image/tiff" })).toBe("file");
30
expect(classifyComposerAttachmentFile({ name: "report.pdf", type: "application/pdf" })).toBe(
31
"file",
32
);
33
+ expect(classifyComposerAttachmentFile({ name: "picture.bmp", type: "image/bmp" })).toBe("file");
34
+ expect(
35
+ classifyComposerAttachmentFile({ name: "layers.psd", type: "image/vnd.adobe.photoshop" }),
36
+ ).toBe("unsupported-image");
37
});
38
39
it("keeps DNG originals on the file path without changing their bytes", async () => {
@@ -96,7 +98,7 @@ describe("composer attachment files", () => {
98
"image",
99
"image",
100
"image",
99
- "unsupported-image",
101
+ "file",
102
"unsupported-image",
103
]);
104
});
@@ -112,20 +114,18 @@ describe("composer attachment files", () => {
114
).toBe(false);
115
});
116
115
- it("claims SVG and unsupported image pastes even when text is present", () => {
116
- const images = [
117
- new File(["svg"], "diagram.svg", { type: "image/svg+xml" }),
118
- new File(["tiff"], "photo.tiff", { type: "image/tiff" }),
119
- ];
117
+ it("claims SVG pastes even when text is present", () => {
118
+ const image = new File(["svg"], "diagram.svg", { type: "image/svg+xml" });
119
+ expect(
120
+ shouldHandleComposerAttachmentPaste({ files: [image], plainText: "Image caption" }),
121
+ ).toBe(true);
122
+ });
123
121
- for (const image of images) {
122
- expect(
123
- shouldHandleComposerAttachmentPaste({
124
- files: [image],
125
- plainText: "Image caption",
126
- }),
127
- ).toBe(true);
128
- }
124
+ it("preserves text when the clipboard also includes generic image files", () => {
125
+ const image = new File(["tiff"], "photo.tiff", { type: "image/tiff" });
126
+ expect(
127
+ shouldHandleComposerAttachmentPaste({ files: [image], plainText: "Image caption" }),
128
+ ).toBe(false);
129
});
130
131
it("uses the hard local limit while server config is unknown", () => {
apps/web/src/components/chat/composerAttachmentFiles.ts
+4
-1
@@ -12,6 +12,7 @@ import type { ComposerFileAttachment, ComposerImageAttachment } from "../../comp
12
import { isHeicImageFile } from "../../lib/imageCompression";
13
import { isVideoAttachment, videoMimeType } from "../../types";
14
import { isSvgAttachment } from "@t3tools/shared/image";
15
+import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
16
17
type ComposerAttachmentFileKind = "image" | "file" | "unsupported-image";
18
@@ -94,7 +95,9 @@ export function classifyComposerAttachmentFile(
95
if (!file.type.toLowerCase().startsWith("image/")) {
96
return "file";
97
}
97
- return isProviderSendTurnSupportedImageMimeType(file.type) ? "image" : "unsupported-image";
98
+ if (isProviderSendTurnSupportedImageMimeType(file.type)) return "image";
99
+ // These can be previewed as files, but providers must not receive them as images.
100
+ return isWorkspaceImagePreviewPath(file.name) ? "file" : "unsupported-image";
101
}
102
103
export function isPreviewableComposerVideo(
apps/web/src/components/desktop/SnapShotCoordinator.tsx
+2
-2
@@ -16,7 +16,6 @@ import { useHandleNewThread } from "../../hooks/useHandleNewThread";
16
import { useStableCallback } from "../../hooks/useStableCallback";
17
import { getClientSettings, useClientSettings } from "../../hooks/useSettings";
18
import { readThreadShell } from "../../state/entities";
19
-import { compressImageToByteLimit, dataUrlToFile } from "../../lib/imageCompression";
19
import { resolveThreadActionProjectRef } from "../../lib/chatThreadActions";
20
import {
21
beginSnapShotAnimation,
@@ -38,7 +37,6 @@ import {
37
countQuestionRequestAttachments,
38
openQuestionAttachmentDraft,
39
} from "../../questionAttachments";
41
-import { readFileAsDataUrl } from "../ChatView.logic";
40
import { stackedThreadToast, toastManager } from "../ui/toast";
41
42
type CaptureTarget = DraftId | ScopedThreadRef;
@@ -163,6 +161,8 @@ export async function deliverSnapShot(
161
const store = useComposerDraftStore.getState();
162
updateSnapShotAnimationSource(item.id, item.source);
163
const capture = await bridge.readSnapShot(item.id);
164
+ const { compressImageToByteLimit, dataUrlToFile, readFileAsDataUrl } =
165
+ await import("../../lib/imageCompression");
166
const original = dataUrlToFile(capture.dataUrl, capture.name, capture.mimeType);
167
const compressed = await compressImageToByteLimit(original, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);
168
if (!compressed.ok) {
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
new
+1271
@@ -0,0 +1,1271 @@
1
+import { act, render, stubGlobal, type Screen } from "../../../test/render";
2
+import { EnvironmentId } from "@t3tools/contracts";
3
+import { describe, expect, it, vi } from "vite-plus/test";
4
+import { page } from "vite-plus/test/browser";
5
+import "~/index.css";
6
+
7
+const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));
8
+
9
+vi.mock(import("~/assets/assetUrls"), async (original) => ({
10
+ ...(await original()),
11
+ useAssetUrlRefresh: () => refresh,
12
+}));
13
+// The real source view highlights through a worker pool; the text it receives is what matters here.
14
+// Never load the original: its highlighter graph can outlast waitFor on a cold CI browser.
15
+vi.mock(import("./ReadOnlySourcePreview"), () => ({
16
+ default: ({ text }: { text: string }) => <pre>{text}</pre>,
17
+}));
18
+
19
+import { AttachmentFilePreview } from "./AttachmentFilePreview";
20
+import { OfficeFilePreview } from "./OfficeFilePreview";
21
+import { MermaidFilePreview } from "./MermaidFilePreview";
22
+import { OFFICE_PREVIEW_MAX_COLUMNS, type OfficeWorkerResult } from "./officePreviewProtocol";
23
+
24
+it.each(["<w:body/>", "<w:body></w:body>"])(
25
+ "opens an empty Word document with %s",
26
+ async (body) => {
27
+ const { default: JSZip } = await import("jszip");
28
+ const { prepareOffice } = await import("./officeArchive");
29
+ const archive = new JSZip().file(
30
+ "word/document.xml",
31
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${body}</w:document>`,
32
+ );
33
+ const prepared = await prepareOffice(
34
+ await archive.generateAsync({ type: "arraybuffer" }),
35
+ "docx",
36
+ );
37
+ const result = await JSZip.loadAsync(prepared.bytes);
38
+ const xml = new DOMParser().parseFromString(
39
+ await result.file("word/document.xml")!.async("string"),
40
+ "application/xml",
41
+ );
42
+ expect(xml.querySelector("parsererror")).toBeNull();
43
+ expect(
44
+ xml.getElementsByTagNameNS(
45
+ "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
46
+ "body",
47
+ ),
48
+ ).toHaveLength(1);
49
+ },
50
+);
51
+
52
+it.each([false, true])(
53
+ "rejects excessive archive entries before JSZip (directories: %s)",
54
+ async (directories) => {
55
+ const { default: JSZip } = await import("jszip");
56
+ const { prepareOffice } = await import("./officeArchive");
57
+ const archive = new JSZip();
58
+ for (let i = 0; i < 4096; i++)
59
+ archive.file(`entry-${i}${directories ? "/" : ".txt"}`, "", { dir: directories });
60
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
61
+ const load = vi.spyOn(JSZip, "loadAsync");
62
+ try {
63
+ await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");
64
+ expect(load).not.toHaveBeenCalled();
65
+ // The actual central-directory records must also be bounded if EOCD lies.
66
+ const view = new DataView(bytes);
67
+ view.setUint16(bytes.byteLength - 22 + 8, 1, true);
68
+ view.setUint16(bytes.byteLength - 22 + 10, 1, true);
69
+ await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");
70
+ expect(load).not.toHaveBeenCalled();
71
+ } finally {
72
+ load.mockRestore();
73
+ }
74
+ },
75
+);
76
+
77
+it("rejects oversized embedded images before decoding pixels and retains ordinary images", async () => {
78
+ const { officeImageBitmap } = await import("./office/image-bitmap");
79
+ const canvas = new OffscreenCanvas(2, 3);
80
+ canvas.getContext("2d");
81
+ const blob = await canvas.convertToBlob({ type: "image/png" });
82
+ const bytes = await blob.arrayBuffer();
83
+ new DataView(bytes).setUint32(16, 12000);
84
+ new DataView(bytes).setUint32(20, 12000);
85
+ const decode = vi.spyOn(globalThis, "createImageBitmap");
86
+ try {
87
+ await expect(officeImageBitmap(new Blob([bytes]))).rejects.toThrow("pixel limit");
88
+ expect(decode).not.toHaveBeenCalled();
89
+ const bitmap = await officeImageBitmap(blob);
90
+ expect([bitmap.width, bitmap.height]).toEqual([2, 3]);
91
+ bitmap.close();
92
+ } finally {
93
+ decode.mockRestore();
94
+ }
95
+});
96
+
97
+it.each(["utf-16le", "utf-16be", "windows-1252"])(
98
+ "preserves %s Office XML and safe hyperlink targets",
99
+ async (encoding) => {
100
+ const { default: JSZip } = await import("jszip");
101
+ const { prepareOffice } = await import("./officeArchive");
102
+ const archive = new JSZip();
103
+ const encode = (text: string) => {
104
+ const xml = `<?xml version="1.0" encoding="${encoding}"?>${text}`;
105
+ if (encoding === "windows-1252") return Uint8Array.from(xml, (char) => char.charCodeAt(0));
106
+ const bytes = new Uint8Array(2 + xml.length * 2);
107
+ const view = new DataView(bytes.buffer);
108
+ const little = encoding === "utf-16le";
109
+ view.setUint16(0, 0xfeff, little);
110
+ for (let i = 0; i < xml.length; i++) view.setUint16(2 + i * 2, xml.charCodeAt(i), little);
111
+ return bytes;
112
+ };
113
+ archive.file(
114
+ "word/document.xml",
115
+ encode(
116
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>café</w:t></w:r></w:p></w:body></w:document>',
117
+ ),
118
+ );
119
+ archive.file(
120
+ "word/_rels/document.xml.rels",
121
+ encode(
122
+ `<Relationships>${["https://example.com/page", "http://example.com", "mailto:maria@example.com", "javascript:alert(1)", "file:///tmp/private"].map((target, i) => `<Relationship Id="r${i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" TargetMode="External" Target="${target}"/>`).join("")}</Relationships>`,
123
+ ),
124
+ );
125
+ const prepared = await prepareOffice(
126
+ await archive.generateAsync({ type: "arraybuffer" }),
127
+ "docx",
128
+ );
129
+ const result = await JSZip.loadAsync(prepared.bytes);
130
+ expect(await result.file("word/document.xml")!.async("string")).toContain("café");
131
+ const links = await result.file("word/_rels/document.xml.rels")!.async("string");
132
+ expect(links).toContain('encoding="UTF-8"');
133
+ expect(links).toContain("https://example.com/page");
134
+ expect(links).toContain("http://example.com");
135
+ expect(links).toContain("mailto:maria@example.com");
136
+ expect(links).not.toContain("javascript:");
137
+ expect(links).not.toContain("file:");
138
+ },
139
+);
140
+
141
+it.each([
142
+ ["", "worksheets/./sheet1.xml", false],
143
+ ["x:", "../xl/worksheets/sheet1.xml", false],
144
+ ["", "/xl/worksheets/sheet1.xml", true],
145
+])("preserves %sworksheet metadata with relationship target %s", async (prefix, target, empty) => {
146
+ const { default: JSZip } = await import("jszip");
147
+ const archive = new JSZip();
148
+ const ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
149
+ archive.file(
150
+ "xl/workbook.xml",
151
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="s"/></sheets></workbook>',
152
+ );
153
+ archive.file(
154
+ "xl/_rels/workbook.xml.rels",
155
+ `<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}"/></Relationships>`,
156
+ );
157
+ archive.file(
158
+ "xl/worksheets/sheet1.xml",
159
+ `<${prefix}worksheet xmlns${prefix ? ":x" : ""}="${ns}"><${prefix}dimension ref="XFD1048576"/><${prefix}cols><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS - 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 10}" width="20"/><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS + 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 30}" hidden="1"/></${prefix}cols><${prefix}sheetData><${prefix}row ht="42" customHeight="1" hidden="1"><${prefix}c r="A50" t="inlineStr"><${prefix}is><${prefix}t>${"value".repeat(1000)}</${prefix}t></${prefix}is></${prefix}c></${prefix}row></${prefix}sheetData><${prefix}mergeCells><${prefix}mergeCell ref="XFD1048576"/></${prefix}mergeCells></${prefix}worksheet>`
160
+ .replace(/<((?:x:)?(?:col|dimension|mergeCell))\b([^>]*)\/>/g, prefix ? "<$1$2></$1>" : "$&")
161
+ .replace(/<sheetData>[\s\S]*?<\/sheetData>/, (data) => (empty ? "<sheetData/>" : data))
162
+ .replace(/="([^"]*)"/g, (attribute, value: string) =>
163
+ prefix || empty
164
+ ? ` = '${value.replace(/\d/g, (digit) => `&#${digit.charCodeAt(0)};`)}'`
165
+ : attribute,
166
+ ),
167
+ );
168
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
169
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
170
+ type: "module",
171
+ });
172
+ try {
173
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
174
+ worker.addEventListener(
175
+ "message",
176
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
177
+ { once: true },
178
+ );
179
+ worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
180
+ });
181
+ expect(result.type).toBe("xlsx");
182
+ if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
183
+ const bounded = await JSZip.loadAsync(result.bytes);
184
+ const sheet = new DOMParser().parseFromString(
185
+ await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
186
+ "application/xml",
187
+ );
188
+ expect(sheet.querySelector("parsererror")).toBeNull();
189
+ const row = sheet.getElementsByTagNameNS(ns, "row")[0];
190
+ if (empty) expect(row).toBeUndefined();
191
+ else {
192
+ expect(row!.getAttribute("ht")).toBe("42");
193
+ expect(row!.getAttribute("hidden")).toBe("1");
194
+ expect(row!.getElementsByTagNameNS(ns, "c")[0]!.getAttribute("r")).toBe("A50");
195
+ expect(row!.getElementsByTagNameNS(ns, "t")[0]!.textContent).toHaveLength(4096);
196
+ }
197
+ expect(sheet.getElementsByTagNameNS(ns, "dimension")).toHaveLength(0);
198
+ expect(sheet.getElementsByTagNameNS(ns, "mergeCell")).toHaveLength(0);
199
+ const columns = sheet.getElementsByTagNameNS(ns, "col");
200
+ expect(columns).toHaveLength(1);
201
+ expect(columns[0]!.getAttribute("min")).toBe(String(OFFICE_PREVIEW_MAX_COLUMNS - 1));
202
+ expect(columns[0]!.getAttribute("max")).toBe(String(OFFICE_PREVIEW_MAX_COLUMNS));
203
+ } finally {
204
+ worker.terminate();
205
+ }
206
+});
207
+
208
+it("reports the final slide at maximum scroll after page visibility changes", async () => {
209
+ const { OfficePages } = await import("./office/OfficePages");
210
+ const changed = vi.fn();
211
+ const container = document.createElement("div");
212
+ container.style.cssText = "display:flex;flex-direction:column;width:400px;height:400px";
213
+ await using screen = await render(
214
+ <OfficePages
215
+ pages={Array.from({ length: 6 }, () => ({ width: 400, height: 240 }))}
216
+ label="Slide"
217
+ paint={async () => undefined}
218
+ onPageChange={changed}
219
+ onError={(error) => {
220
+ throw error;
221
+ }}
222
+ />,
223
+ { container },
224
+ );
225
+ const scroller = screen.container.querySelector<HTMLElement>("[data-office-pages]")!;
226
+ await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(scroller.clientHeight));
227
+ await act(() => {
228
+ scroller.scrollTop = scroller.scrollHeight;
229
+ });
230
+ await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(5));
231
+ await act(() => {
232
+ scroller.scrollTop = 10;
233
+ });
234
+ await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(0));
235
+});
236
+
237
+it("preserves merged text across tile clears", async () => {
238
+ const { paintFrame } = await import("./office/sheet-frame");
239
+ const canvas = new OffscreenCanvas(400, 80);
240
+ const context = canvas.getContext("2d")!;
241
+ paintFrame(
242
+ context,
243
+ {
244
+ viewport: { x: 0, y: 0, width: 400, height: 80 },
245
+ list: { width: 400, height: 80, commands: [] },
246
+ tiles: [
247
+ {
248
+ x: 0,
249
+ y: 0,
250
+ clipX: 0,
251
+ clipY: 0,
252
+ list: {
253
+ width: 208,
254
+ height: 80,
255
+ commands: [
256
+ {
257
+ op: "text",
258
+ x: 2,
259
+ y: 40,
260
+ text: "MMMMMMMMMMMMMMMMMMMMMMMM",
261
+ fontSize: 20,
262
+ color: "#000",
263
+ clip: { x: 0, y: 0, w: 400, h: 80 },
264
+ },
265
+ ],
266
+ },
267
+ },
268
+ { x: 192, y: 0, clipX: 200, clipY: 0, list: { width: 208, height: 80, commands: [] } },
269
+ ],
270
+ },
271
+ { ratio: 1, origin: { x: 0, y: 0 } },
272
+ );
273
+ const pixels = context.getImageData(240, 15, 100, 35).data;
274
+ expect(pixels.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);
275
+});
276
+
277
+it.each([
278
+ "paragraphs",
279
+ "runs",
280
+ "tables",
281
+ "auxiliary XML",
282
+ "XML bytes",
283
+ "renamed XML",
284
+ "section after prefix",
285
+ "oversized section",
286
+])("bounds excessive Word %s before rendering DOM", async (scenario) => {
287
+ const { default: JSZip } = await import("jszip");
288
+ const archive = new JSZip();
289
+ const body = ["paragraphs", "section after prefix", "oversized section"].includes(scenario)
290
+ ? "<w:p><w:r><w:t>x</w:t></w:r></w:p>".repeat(200_000)
291
+ : scenario === "runs"
292
+ ? `<w:p>${"<w:r><w:t>x</w:t></w:r>".repeat(50_001)}</w:p>`
293
+ : scenario === "tables"
294
+ ? "<w:tbl/>".repeat(50_001)
295
+ : scenario === "XML bytes"
296
+ ? `<w:p><w:r><w:t>${"x".repeat(2 * 1024 * 1024)}</w:t></w:r></w:p>`
297
+ : "<w:p/>";
298
+ const section =
299
+ '<w:sectPr><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/><w:pgMar w:top="1440" w:left="1440" w:bottom="1440" w:right="1440"/></w:sectPr>';
300
+ archive.file(
301
+ "word/document.xml",
302
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${body}${scenario === "section after prefix" ? '<w:p xmlns:s="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:pPr><s:sectPr><s:pgSz s:w="11906" s:h="16838"/></s:sectPr></w:pPr></w:p>' : ""}${scenario === "oversized section" ? `<w:sectPr>${"<w:cols/>".repeat(2_001)}</w:sectPr>` : section}</w:body></w:document>`,
303
+ );
304
+ if (scenario === "auxiliary XML" || scenario === "renamed XML")
305
+ archive.file(
306
+ scenario === "renamed XML" ? "word/footnotes.dat" : "word/footnotes.xml",
307
+ `<w:footnotes>${"<w:p/>".repeat(50_001)}</w:footnotes>`,
308
+ );
309
+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
310
+ const src = URL.createObjectURL(file);
311
+ try {
312
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
313
+ type: "module",
314
+ });
315
+ try {
316
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
317
+ worker.addEventListener(
318
+ "message",
319
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
320
+ { once: true },
321
+ );
322
+ void file
323
+ .arrayBuffer()
324
+ .then((bytes) => worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]));
325
+ });
326
+ if (
327
+ scenario === "auxiliary XML" ||
328
+ scenario === "renamed XML" ||
329
+ scenario === "oversized section"
330
+ ) {
331
+ expect(result).toMatchObject({
332
+ type: "error",
333
+ message: expect.stringContaining("Preview limited"),
334
+ });
335
+ } else {
336
+ expect(result.type).toBe("docx");
337
+ if (result.type !== "docx") throw new Error("Expected a Word prefix");
338
+ expect(result.truncated).toBe(true);
339
+ const bounded = await JSZip.loadAsync(result.bytes);
340
+ const markup = await bounded.file("word/document.xml")!.async("string");
341
+ {
342
+ const xml = markup;
343
+ const document = new DOMParser().parseFromString(xml, "application/xml");
344
+ expect(document.querySelector("parsererror")).toBeNull();
345
+ const bodies = document.getElementsByTagNameNS("*", "body");
346
+ expect(bodies).toHaveLength(1);
347
+ const section = bodies[0]!.lastElementChild!;
348
+ expect(section.localName).toBe("sectPr");
349
+ const size = section.getElementsByTagNameNS("*", "pgSz")[0]!;
350
+ expect(size.getAttributeNS(section.namespaceURI, "w")).toBe(
351
+ scenario === "section after prefix" ? "11906" : "16838",
352
+ );
353
+ expect(size.getAttributeNS(section.namespaceURI, "orient")).toBe(
354
+ scenario === "section after prefix" ? null : "landscape",
355
+ );
356
+ }
357
+ expect(markup.length).toBeLessThan(body.length);
358
+ expect(markup.length).toBeLessThanOrEqual(3 * 1024 * 1024);
359
+ expect(markup.match(/<(?![!?/])/g)!.length).toBeLessThanOrEqual(100_000);
360
+ }
361
+ } finally {
362
+ worker.terminate();
363
+ }
364
+ } finally {
365
+ URL.revokeObjectURL(src);
366
+ }
367
+});
368
+
369
+it.each([
370
+ "relationship markup",
371
+ "relationship bytes",
372
+ "content type",
373
+ "metadata type",
374
+ "deep XML",
375
+ "query path",
376
+])("bounds XML hidden in media by %s", async (scenario) => {
377
+ const { default: JSZip } = await import("jszip");
378
+ const archive = new JSZip();
379
+ const path = `word/media/payload.png${scenario === "query path" ? "?xml" : ""}`;
380
+ archive.file(
381
+ "word/document.xml",
382
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p/></w:body></w:document>',
383
+ );
384
+ archive.file(
385
+ "[Content_Types].xml",
386
+ `<Types><Override PartName="/${path}" ContentType="${scenario === "content type" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml" : "image/png"}"/>${scenario === "metadata type" ? '<Default Extension="rels" ContentType="image/png"/>' : ""}</Types>`,
387
+ );
388
+ archive.file(
389
+ "word/_rels/document.xml.rels",
390
+ `<Relationships>${scenario === "content type" ? "" : `<Relationship Id="style" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="${path.slice(5)}"/>`}${scenario === "metadata type" ? "<unused/>".repeat(50_001) : ""}</Relationships>`,
391
+ );
392
+ archive.file(
393
+ path,
394
+ scenario === "relationship bytes"
395
+ ? `<styles>${"x".repeat(1024 * 1024)}</styles>`
396
+ : scenario === "deep XML"
397
+ ? `${"<styles>".repeat(65)}${"</styles>".repeat(65)}`
398
+ : `<styles>${"<style/>".repeat(50_001)}</styles>`,
399
+ );
400
+ const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
401
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
402
+ type: "module",
403
+ });
404
+ try {
405
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
406
+ worker.addEventListener(
407
+ "message",
408
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
409
+ { once: true },
410
+ );
411
+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
412
+ });
413
+ expect(result).toMatchObject({
414
+ type: "error",
415
+ message: expect.stringContaining("Preview limited"),
416
+ });
417
+ } finally {
418
+ worker.terminate();
419
+ }
420
+});
421
+
422
+it.each([
423
+ "footnotes",
424
+ "note roots",
425
+ "endnotes",
426
+ "header",
427
+ "footer",
428
+ "comments",
429
+ "styles",
430
+ "style chain",
431
+ "style count",
432
+ "style visits",
433
+ "numbering",
434
+ "picture numbering",
435
+])("keeps the body and warns when omitting expanded %s", async (role) => {
436
+ const { default: JSZip } = await import("jszip");
437
+ const archive = new JSZip();
438
+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
439
+ const type = role.startsWith("style")
440
+ ? "styles"
441
+ : role === "picture numbering"
442
+ ? "numbering"
443
+ : role === "note roots"
444
+ ? "footnotes"
445
+ : role;
446
+ archive.file(
447
+ "_rels/.rels",
448
+ '<Relationships><Relationship Id="doc" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
449
+ );
450
+ const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
451
+ archive.file(
452
+ "word/document.xml",
453
+ `<w:document xmlns:w="${ns}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>${text("body retained")}${Array.from({ length: 500 }, () => `<w:p><w:r><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/><w:commentReference w:id="1"/><w:br w:type="page"/></w:r></w:p>`).join("")}<w:sectPr><w:headerReference w:type="default" r:id="aux"/><w:footerReference w:type="default" r:id="aux"/></w:sectPr></w:body></w:document>`,
454
+ );
455
+ archive.file(
456
+ "word/_rels/document.xml.rels",
457
+ `<Relationships><Relationship Id="aux" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="media/aux.xml"/></Relationships>`,
458
+ );
459
+ const xml =
460
+ role === "style chain" || role === "style count" || role === "style visits"
461
+ ? `<w:styles xmlns:w="${ns}">${Array.from({ length: role === "style count" ? 3_000 : 1_000 }, (_, i) => `<w:style w:styleId="s${i}" w:type="paragraph">${i ? `<w:basedOn w:val="s${role === "style visits" && i >= 30 ? 29 : i - 1}"/>` : ""}<w:pPr><w:spacing w:after="120"/></w:pPr></w:style>`).join("")}</w:styles>`
462
+ : role === "styles"
463
+ ? `<w:styles xmlns:w="${ns}">${Array.from({ length: 100 }, (_, i) => `<w:style w:styleId="${"s".repeat(2_000)}${i}" w:type="paragraph"><w:basedOn w:val="s0"/><w:pPr><w:spacing w:after="120"/></w:pPr></w:style>`).join("")}</w:styles>`
464
+ : role.includes("numbering")
465
+ ? `<w:numbering xmlns:w="${ns}">${role === "picture numbering" ? '<w:numPicBullet w:numPicBulletId="1"/>' : ""}<w:abstractNum w:abstractNumId="1">${Array.from({ length: 9 }, (_, i) => `<w:lvl w:ilvl="${i}"><w:lvlText w:val="%1."/></w:lvl>`).join("")}</w:abstractNum>${Array.from({ length: 100 }, (_, i) => `<w:num w:numId="${i}"><w:abstractNumId w:val="1"/></w:num>`).join("")}</w:numbering>`
466
+ : role === "header" || role === "footer"
467
+ ? `<w:${role === "header" ? "hdr" : "ftr"} xmlns:w="${ns}">${text("omitted payload").repeat(2_000)}</w:${role === "header" ? "hdr" : "ftr"}>`
468
+ : `<w:${role} xmlns:w="${ns}"><w:${role.slice(0, -1)} w:id="1">${text("omitted payload").repeat(2_000)}</w:${role.slice(0, -1)}></w:${role}>`;
469
+ archive.file("word/media/aux.xml", xml);
470
+ if (role === "note roots") {
471
+ archive.file(
472
+ "word/document.xml",
473
+ `<w:document xmlns:w="${ns}"><w:body>${text("body retained")}${Array.from({ length: 200 }, (_, id) => `<w:p><w:r><w:footnoteReference w:id="${id}"/></w:r></w:p>`).join("")}</w:body></w:document>`,
474
+ );
475
+ archive.file(
476
+ "word/media/aux.xml",
477
+ `<w:footnotes xmlns:w="${ns}" padding="${"x".repeat(32_000)}">${Array.from({ length: 200 }, (_, id) => `<w:footnote w:id="${id}">${text("omitted payload")}</w:footnote>`).join("")}</w:footnotes>`,
478
+ );
479
+ }
480
+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
481
+ if (role === "note roots") {
482
+ const { SaxesParser } = await import("saxes");
483
+ const { prepareOffice } = await import("./officeArchive");
484
+ const parse = vi.spyOn(SaxesParser.prototype, "write");
485
+ try {
486
+ expect((await prepareOffice(await file.arrayBuffer(), "docx")).truncated).toBe(true);
487
+ expect(
488
+ parse.mock.calls.reduce(
489
+ (sum, [chunk]) => sum + (typeof chunk === "string" ? chunk.length : 0),
490
+ 0,
491
+ ),
492
+ ).toBeLessThan(4 * 1024 * 1024);
493
+ } finally {
494
+ parse.mockRestore();
495
+ }
496
+ }
497
+ const src = URL.createObjectURL(file);
498
+ try {
499
+ const container = document.createElement("div");
500
+ container.style.cssText = "display:flex;flex-direction:column;width:640px;height:700px";
501
+ await using screen = await render(
502
+ <OfficeFilePreview src={src} name="expanded.docx" kind="docx" sizeBytes={file.size} />,
503
+ { container },
504
+ );
505
+ await vi.waitFor(
506
+ () => {
507
+ expect(screen.container.querySelector('[role="alert"]')?.textContent ?? "").toBe("");
508
+ expect(screen.container.textContent).toContain("body retained");
509
+ },
510
+ { timeout: 30_000 },
511
+ );
512
+ expect(screen.container.textContent).toContain("Preview limited");
513
+ expect(screen.container.textContent).not.toContain("omitted payload");
514
+ await vi.waitFor(() =>
515
+ expect(screen.container.querySelector("canvas")!.width).toBeGreaterThan(0),
516
+ );
517
+ } finally {
518
+ URL.revokeObjectURL(src);
519
+ }
520
+});
521
+
522
+it.each([
523
+ "ordinary parts",
524
+ "unused parts",
525
+ "independent styles",
526
+ "inherited styles",
527
+ "python-docx package",
528
+ "default template styles",
529
+ "binary package properties",
530
+])("retains Word %s without a limit warning", async (scenario) => {
531
+ const { default: JSZip } = await import("jszip");
532
+ const archive = new JSZip();
533
+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
534
+ const r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
535
+ const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
536
+ archive.file(
537
+ "_rels/.rels",
538
+ `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/></Relationships>`,
539
+ );
540
+ if (scenario === "python-docx package" || scenario === "binary package properties") {
541
+ const packageRelationships = "http://schemas.openxmlformats.org/package/2006/relationships";
542
+ archive.file(
543
+ "_rels/.rels",
544
+ `<Relationships xmlns="${packageRelationships}"><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/><Relationship Id="thumbnail" Type="${packageRelationships}/metadata/thumbnail" Target="docProps/thumbnail.jpeg"/><Relationship Id="core" Type="${packageRelationships}/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="app" Type="${r}/extended-properties" Target="docProps/app.xml"/><Relationship Id="custom" Type="${r}/custom-properties" Target="docProps/custom.xml"/><Relationship Id="signature" Type="${packageRelationships}/digital-signature/origin" Target="_xmlsignatures/origin.sigs"/></Relationships>`,
545
+ );
546
+ archive.file(
547
+ "[Content_Types].xml",
548
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/></Types>',
549
+ );
550
+ archive.file(
551
+ "docProps/thumbnail.jpeg",
552
+ new Uint8Array([255, 216, 255, 224, 0, 16, 74, 70, 73, 70]),
553
+ );
554
+ archive.file("_xmlsignatures/origin.sigs", new Uint8Array());
555
+ for (const part of ["core", "app", "custom"])
556
+ archive.file(`docProps/${part}.xml`, '<properties xmlns="urn:properties"/>');
557
+ if (scenario === "binary package properties") {
558
+ const roles = [
559
+ `${packageRelationships}/metadata/core-properties`,
560
+ `${r}/extended-properties`,
561
+ `${packageRelationships}/metadata/custom-properties`,
562
+ `${packageRelationships}/digital-signature/signature`,
563
+ ];
564
+ archive.file(
565
+ "_rels/.rels",
566
+ `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/>${roles.map((role, i) => `<Relationship Id="metadata${i}" Type="${role}" Target="docProps/metadata${i}.dat"/>`).join("")}</Relationships>`,
567
+ );
568
+ for (const i of roles.keys())
569
+ archive.file(`docProps/metadata${i}.dat`, new Uint8Array([255, 216, 255, 0]));
570
+ }
571
+ }
572
+ const ordinary = scenario === "ordinary parts";
573
+ archive.file(
574
+ "word/document.xml",
575
+ `<w:document xmlns:w="${ns}" xmlns:r="${r}"><w:body>${text("ordinary body")}<w:p><w:pPr><w:pStyle w:val="s19"/></w:pPr><w:r><w:t>styled body</w:t>${ordinary ? '<w:footnoteReference w:id="1"/><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/><w:commentReference w:id="1"/>' : ""}</w:r></w:p><w:sectPr>${ordinary ? '<w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/>' : ""}</w:sectPr></w:body></w:document>`,
576
+ );
577
+ archive.file(
578
+ "word/_rels/document.xml.rels",
579
+ `<Relationships>${["header", "footer", "footnotes", "endnotes", "comments", "fontTable", "styles"].map((role) => `<Relationship Id="${role}" Type="${r}/${role}" Target="${role}.xml"/>`).join("")}</Relationships>`,
580
+ );
581
+ for (const [role, root] of [
582
+ ["header", "hdr"],
583
+ ["footer", "ftr"],
584
+ ])
585
+ archive.file(
586
+ `word/${role}.xml`,
587
+ `<w:${root} xmlns:w="${ns}">${text(`${role} retained`)}</w:${root}>`,
588
+ );
589
+ for (const role of ["footnotes", "endnotes", "comments"])
590
+ archive.file(
591
+ `word/${role}.xml`,
592
+ `<w:${role} xmlns:w="${ns}"><w:${role.slice(0, -1)} w:id="1" w:author="reviewer" w:date="2026-10-01T00:00:00Z">${text(`${role} retained`)}</w:${role.slice(0, -1)}></w:${role}>`,
593
+ );
594
+ archive.file(
595
+ "word/fontTable.xml",
596
+ `<w:fonts xmlns:w="${ns}"><w:font w:name="unused"/></w:fonts>`,
597
+ );
598
+ archive.file(
599
+ "word/styles.xml",
600
+ `<w:styles xmlns:w="${ns}"><w:docDefaults/><w:style w:type="paragraph" w:styleId="base"><w:rPr><w:b/></w:rPr></w:style>${Array.from({ length: 20 }, (_, i) => `<w:style w:styleId="s${i}" w:type="paragraph">${scenario === "inherited styles" ? '<w:basedOn w:val="base"/>' : ""}<w:rPr><w:color w:val="123456"/></w:rPr></w:style>`).join("")}</w:styles>`,
601
+ );
602
+ if (scenario === "default template styles") {
603
+ const heading =
604
+ '<w:style w:type="paragraph" w:styleId="s19"><w:basedOn w:val="Normal"/><w:link w:val="HeadingChar"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/><w:color w:val="123456"/></w:rPr></w:style>';
605
+ const conditions = [
606
+ "wholeTable",
607
+ "firstRow",
608
+ "lastRow",
609
+ "firstCol",
610
+ "lastCol",
611
+ "band1Horz",
612
+ "band2Horz",
613
+ "band1Vert",
614
+ "band2Vert",
615
+ ];
616
+ archive.file(
617
+ "word/styles.xml",
618
+ `<w:styles xmlns:w="${ns}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault></w:docDefaults><w:latentStyles>${Array.from({ length: 276 }, (_, i) => `<w:lsdException w:name="latent ${i}" w:semiHidden="0" w:uiPriority="99"/>`).join("")}</w:latentStyles><w:style w:type="paragraph" w:styleId="Normal"/><w:style w:type="character" w:styleId="HeadingChar"><w:rPr><w:b/></w:rPr></w:style>${heading}${Array.from({ length: 61 }, (_, i) => `<w:style w:type="paragraph" w:styleId="p${i}"><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:color w:val="123456"/></w:rPr></w:style>`).join("")}${Array.from({ length: 100 }, (_, i) => `<w:style w:type="table" w:styleId="Table${i}">${i ? '<w:basedOn w:val="Table0"/>' : ""}<w:tblPr><w:tblCellMar><w:top w:w="0"/><w:left w:w="108"/><w:bottom w:w="0"/><w:right w:w="108"/></w:tblCellMar></w:tblPr>${conditions.map((type) => `<w:tblStylePr w:type="${type}"><w:pPr><w:spacing w:after="0"/></w:pPr><w:rPr><w:b/><w:color w:val="123456"/></w:rPr><w:tcPr><w:shd w:fill="D9E2F3"/></w:tcPr></w:tblStylePr>`).join("")}</w:style>`).join("")}</w:styles>`,
619
+ );
620
+ archive.file(
621
+ "word/_rels/document.xml.rels",
622
+ (await archive.file("word/_rels/document.xml.rels")!.async("string")).replace(
623
+ "</Relationships>",
624
+ `<Relationship Id="numbering" Type="${r}/numbering" Target="numbering.xml"/></Relationships>`,
625
+ ),
626
+ );
627
+ archive.file(
628
+ "word/numbering.xml",
629
+ `<w:numbering xmlns:w="${ns}">${Array.from({ length: 9 }, (_, i) => `<w:abstractNum w:abstractNumId="${i}"><w:multiLevelType w:val="singleLevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:lvlJc w:val="left"/><w:pPr><w:tabs><w:tab w:val="num" w:pos="720"/></w:tabs><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum><w:num w:numId="${i + 1}"><w:abstractNumId w:val="${i}"/></w:num>`).join("")}</w:numbering>`,
630
+ );
631
+ const document = await archive.file("word/document.xml")!.async("string");
632
+ archive.file(
633
+ "word/document.xml",
634
+ document.replace(
635
+ "<w:sectPr>",
636
+ '<w:tbl><w:tblPr><w:tblStyle w:val="Table99"/></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>styled cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:sectPr>',
637
+ ),
638
+ );
639
+ }
640
+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
641
+ const src = URL.createObjectURL(file);
642
+ try {
643
+ const container = document.createElement("div");
644
+ container.style.cssText = "display:flex;flex-direction:column;width:640px;height:700px";
645
+ await using screen = await render(
646
+ <OfficeFilePreview src={src} name="ordinary.docx" kind="docx" />,
647
+ { container },
648
+ );
649
+ await vi.waitFor(() => expect(screen.container.textContent).toContain("ordinary body"), {
650
+ timeout: 30_000,
651
+ });
652
+ expect(screen.container.textContent).not.toContain("Preview limited");
653
+ await vi.waitFor(() =>
654
+ expect(screen.container.querySelector("canvas")!.width).toBeGreaterThan(0),
655
+ );
656
+ if (scenario === "default template styles")
657
+ expect(screen.container.textContent).toContain("styled cell");
658
+ if (ordinary) {
659
+ expect(screen.container.textContent).toContain("header retained");
660
+ expect(screen.container.textContent).toContain("footer retained");
661
+ }
662
+ } finally {
663
+ URL.revokeObjectURL(src);
664
+ }
665
+});
666
+
667
+it.each([false, true])(
668
+ "bounds shared-string text including CDATA %s per cell and across sheets in the worker and viewer",
669
+ async (cdata) => {
670
+ const { default: JSZip } = await import("jszip");
671
+ const archive = new JSZip();
672
+ archive.file(
673
+ "xl/workbook.xml",
674
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="one" sheetId="1" r:id="s"/><sheet name="two" sheetId="2" r:id="s"/></sheets></workbook>',
675
+ );
676
+ archive.file(
677
+ "xl/_rels/workbook.xml.rels",
678
+ '<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
679
+ );
680
+ const sharedPath = cdata ? "customStrings.xml" : "sharedStrings.xml";
681
+ archive.file(
682
+ "xl/_rels/workbook.xml.rels",
683
+ (await archive.file("xl/_rels/workbook.xml.rels")!.async("string")).replace(
684
+ "</Relationships>",
685
+ `<Relationship Id="strings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="${sharedPath}"/></Relationships>`,
686
+ ),
687
+ );
688
+ const content = "x".repeat(32_767);
689
+ archive.file(
690
+ `xl/${sharedPath}`,
691
+ `<sst><si><t>${cdata ? `<![CDATA[${content}]]>` : content}</t></si></sst>`,
692
+ );
693
+ archive.file(
694
+ "xl/worksheets/sheet1.xml",
695
+ `<worksheet><sheetData>${Array.from({ length: 500 }, (_, i) => `<row r="${i + 1}">${Array.from({ length: 50 }, (_, j) => `<c r="${j < 26 ? String.fromCharCode(65 + j) : "A" + String.fromCharCode(65 + j - 26)}${i + 1}" t="s"><v>${cdata ? "<![CDATA[0]]>" : "0"}</v></c>`).join("")}</row>`).join("")}</sheetData></worksheet>`.replace(
696
+ '<c r="A1" t="s"><v><![CDATA[0]]></v></c>',
697
+ `<c r="A1" t="inlineStr"><is><t><![CDATA[${content}]]></t></is></c>`,
698
+ ),
699
+ );
700
+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
701
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
702
+ type: "module",
703
+ });
704
+ try {
705
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
706
+ worker.addEventListener(
707
+ "message",
708
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
709
+ { once: true },
710
+ );
711
+ void file
712
+ .arrayBuffer()
713
+ .then((bytes) => worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]));
714
+ });
715
+ expect(result.type).toBe("xlsx");
716
+ if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
717
+ const bounded = await JSZip.loadAsync(result.bytes);
718
+ const sheet = new DOMParser().parseFromString(
719
+ await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
720
+ "application/xml",
721
+ );
722
+ const cells = [...sheet.getElementsByTagName("t")].map((cell) => cell.textContent ?? "");
723
+ expect(cells.reduce((total, cell) => total + cell.length, 0)).toBe(1024 * 1024);
724
+ expect(Math.max(...cells.map((cell) => cell.length))).toBe(4096);
725
+ expect(result.truncated).toBe(true);
726
+ } finally {
727
+ worker.terminate();
728
+ }
729
+ const src = URL.createObjectURL(file);
730
+ try {
731
+ const container = document.createElement("div");
732
+ container.style.cssText = "display:flex;flex-direction:column;width:640px;height:480px";
733
+ await using screen = await render(
734
+ <OfficeFilePreview src={src} name="shared.xlsx" kind="xlsx" />,
735
+ { container },
736
+ );
737
+ await vi.waitFor(
738
+ () =>
739
+ expect(screen.container.querySelector('[role="gridcell"]')?.textContent).toHaveLength(
740
+ 4096,
741
+ ),
742
+ { timeout: 30_000 },
743
+ );
744
+ expect(screen.container.textContent).toContain("Preview limited");
745
+ const canvas = screen.container.querySelector("canvas")!;
746
+ await vi.waitFor(() => expect(canvas.width).toBeGreaterThan(0));
747
+ const scroll = screen.container.querySelector<HTMLElement>('[role="grid"]')!;
748
+ await act(() => {
749
+ scroll.scrollTop = 200;
750
+ scroll.scrollLeft = 200;
751
+ });
752
+ await vi.waitFor(() => expect(scroll.scrollTop).toBe(200));
753
+ expect(canvas.getBoundingClientRect().top).toBeCloseTo(scroll.getBoundingClientRect().top, 0);
754
+ } finally {
755
+ URL.revokeObjectURL(src);
756
+ }
757
+ },
758
+);
759
+
760
+it.each([1, 145])(
761
+ "counts shared Word settings once with %s text repetitions",
762
+ async (repetitions) => {
763
+ const { default: JSZip } = await import("jszip");
764
+ const archive = new JSZip();
765
+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
766
+ archive.file(
767
+ "word/document.xml",
768
+ `<w:document xmlns:w="${ns}"><w:body>${`<w:p><w:r><w:t>${"body".repeat(repetitions)}</w:t></w:r></w:p>`.repeat(5_000)}</w:body></w:document>`,
769
+ );
770
+ archive.file(
771
+ "word/_rels/document.xml.rels",
772
+ '<Relationships><Relationship Id="settings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/></Relationships>',
773
+ );
774
+ const settings = `<w:settings xmlns:w="${ns}"><w:unused>${"s".repeat(120_000)}</w:unused></w:settings>`;
775
+ archive.file("word/settings.xml", settings);
776
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
777
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
778
+ type: "module",
779
+ });
780
+ try {
781
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
782
+ worker.addEventListener(
783
+ "message",
784
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
785
+ { once: true },
786
+ );
787
+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
788
+ });
789
+ expect(result.type).toBe("docx");
790
+ if (result.type !== "docx") throw new Error("Expected a Word prefix");
791
+ expect(result.truncated).toBe(repetitions > 1);
792
+ const bounded = await JSZip.loadAsync(result.bytes);
793
+ const document = await bounded.file("word/document.xml")!.async("string");
794
+ const retainedSettings = await bounded.file("word/settings.xml")!.async("string");
795
+ expect(document.match(/<w:p>/g)!.length).toBeGreaterThan(100);
796
+ expect(document.length + retainedSettings.length).toBeLessThanOrEqual(3 * 1024 * 1024);
797
+ } finally {
798
+ worker.terminate();
799
+ }
800
+ },
801
+);
802
+
803
+it.each(["repeated binary", "XML relationship alias", "duplicate relationship ID"])(
804
+ "bounds Word image expansion for %s",
805
+ async (scenario) => {
806
+ const { default: JSZip } = await import("jszip");
807
+ const archive = new JSZip();
808
+ archive.file(
809
+ "[Content_Types].xml",
810
+ '<Types><Default Extension="png" ContentType="image/png"/></Types>',
811
+ );
812
+ archive.file(
813
+ "word/_rels/document.xml.rels",
814
+ `<Relationships><Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${scenario === "XML relationship alias" ? "styles" : "image"}" Target="media/payload.png"/>${scenario === "duplicate relationship ID" ? '<Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/tiny.png"/>' : ""}</Relationships>`,
815
+ );
816
+ archive.file(
817
+ "word/media/payload.png",
818
+ scenario === "XML relationship alias" ? "<styles/>" : new Uint8Array(8 * 1024 * 1024),
819
+ );
820
+ if (scenario === "duplicate relationship ID")
821
+ archive.file("word/media/tiny.png", new Uint8Array(1));
822
+ archive.file(
823
+ "word/document.xml",
824
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body><w:p>${'<w:r><a:blip r:embed="image"/></w:r>'.repeat(7)}</w:p></w:body></w:document>`,
825
+ );
826
+ const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
827
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
828
+ type: "module",
829
+ });
830
+ try {
831
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
832
+ worker.addEventListener(
833
+ "message",
834
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
835
+ { once: true },
836
+ );
837
+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
838
+ });
839
+ expect(result).toMatchObject({
840
+ type: "error",
841
+ message: expect.stringContaining("expanded markup"),
842
+ });
843
+ } finally {
844
+ worker.terminate();
845
+ }
846
+ },
847
+);
848
+
849
+it.each(["XFD200", "XFD1048576", "AX500", "AZ9999999"])(
850
+ "bounds spreadsheet cells at %s before padding",
851
+ async (ref) => {
852
+ const { default: JSZip } = await import("jszip");
853
+ const archive = new JSZip();
854
+ archive.file(
855
+ "xl/workbook.xml",
856
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="rId1"/></sheets></workbook>',
857
+ );
858
+ // A nonstandard relationship target must get the same bounds.
859
+ archive.file(
860
+ "xl/_rels/workbook.xml.rels",
861
+ '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="custom.xml"/></Relationships>',
862
+ );
863
+ archive.file(
864
+ "xl/custom.xml",
865
+ `<worksheet><dimension ref="A1:${ref}"/><sheetData><row r="1"><c r="A1"><v>7</v></c></row><row r="${ref.replace(/\D/g, "")}"><c r="${ref}"><v>9</v></c></row></sheetData></worksheet>`,
866
+ );
867
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
868
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
869
+ type: "module",
870
+ });
871
+ try {
872
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
873
+ worker.addEventListener(
874
+ "message",
875
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
876
+ { once: true },
877
+ );
878
+ worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
879
+ });
880
+ if (ref === "AZ9999999") {
881
+ expect(result).toMatchObject({
882
+ type: "error",
883
+ message: expect.stringContaining("invalid"),
884
+ });
885
+ } else {
886
+ expect(result.type).toBe("xlsx");
887
+ if (result.type !== "xlsx") throw new Error("Expected workbook values");
888
+ const bounded = await JSZip.loadAsync(result.bytes);
889
+ const sheet = new DOMParser().parseFromString(
890
+ await bounded.file("xl/custom.xml")!.async("string"),
891
+ "application/xml",
892
+ );
893
+ expect(sheet.querySelector('c[r="A1"] v')?.textContent).toBe("7");
894
+ expect(sheet.querySelectorAll("row").length).toBeLessThanOrEqual(500);
895
+ expect(result.truncated).toBe(ref !== "AX500");
896
+ if (ref === "AX500") expect(sheet.querySelector('c[r="AX500"] v')?.textContent).toBe("9");
897
+ else expect(sheet.querySelector('c[r="' + ref + '"]')).toBeNull();
898
+ }
899
+ } finally {
900
+ worker.terminate();
901
+ }
902
+ },
903
+);
904
+
905
+it("keeps spreadsheet dates on their calendar day west of UTC", async () => {
906
+ const { default: JSZip } = await import("jszip");
907
+ const archive = new JSZip();
908
+ archive.file(
909
+ "xl/workbook.xml",
910
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Dates" sheetId="1" r:id="rId1"/></sheets></workbook>',
911
+ );
912
+ archive.file(
913
+ "xl/_rels/workbook.xml.rels",
914
+ '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
915
+ );
916
+ archive.file(
917
+ "xl/styles.xml",
918
+ '<styleSheet><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/></cellXfs></styleSheet>',
919
+ );
920
+ archive.file(
921
+ "xl/worksheets/sheet1.xml",
922
+ '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>46023</v></c></row></sheetData></worksheet>',
923
+ );
924
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
925
+ const workerModule = new URL(
926
+ "./office/spreadsheet.worker.ts?worker_file&type=module",
927
+ import.meta.url,
928
+ ).href;
929
+ // Give the worker a west-of-UTC default while preserving explicit format options.
930
+ const bootstrap = URL.createObjectURL(
931
+ new Blob(
932
+ [
933
+ `
934
+ const NativeURL = URL;
935
+ globalThis.URL = class extends NativeURL {
936
+ constructor(input, base) { super(input, base?.startsWith("blob:") ? ${JSON.stringify(location.href)} : base); }
937
+ };
938
+ const format = Date.prototype.toLocaleDateString;
939
+ Date.prototype.toLocaleDateString = function(locale, options) {
940
+ return format.call(this, "en-US", { timeZone: "America/Los_Angeles", ...options });
941
+ };
942
+ await import(${JSON.stringify(workerModule)});
943
+ postMessage({ type: "ready" });
944
+ `,
945
+ ],
946
+ { type: "text/javascript" },
947
+ ),
948
+ );
949
+ const worker = new Worker(bootstrap, { type: "module" });
950
+ try {
951
+ await new Promise<void>((resolve, reject) => {
952
+ worker.addEventListener(
953
+ "message",
954
+ (event) => {
955
+ if (event.data.type === "ready") resolve();
956
+ },
957
+ { once: true },
958
+ );
959
+ worker.addEventListener("error", (event) => reject(new Error(event.message)), { once: true });
960
+ });
961
+ const { createWorkerClient } = await import("./office/worker-rpc");
962
+ const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
963
+ await client.call("open", { bytes }, { transfer: [bytes] });
964
+ const cells = await client.call("cells", {
965
+ sheet: 0,
966
+ range: { top: 0, bottom: 0, left: 0, right: 0 },
967
+ });
968
+ expect(cells[0]![0]).toMatch(/^1\/1\/(26|2026)$/);
969
+ } finally {
970
+ worker.terminate();
971
+ URL.revokeObjectURL(bootstrap);
972
+ }
973
+});
974
+
975
+it.each([60, 100])("renders all %i pages of a table-heavy Word report", async (pages) => {
976
+ const { default: JSZip } = await import("jszip");
977
+ const archive = new JSZip();
978
+ const paragraph = (text: string) =>
979
+ `<w:p><w:pPr><w:spacing w:after="120"/><w:jc w:val="left"/></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Calibri"/><w:sz w:val="22"/></w:rPr><w:t>${text}</w:t></w:r></w:p>`;
980
+ archive.file(
981
+ "word/document.xml",
982
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${Array.from({ length: pages }, (_, page) => paragraph(`page ${page + 1}`) + `<w:tbl>${Array.from({ length: 10 }, () => `<w:tr>${Array.from({ length: 5 }, () => `<w:tc><w:tcPr><w:tcW w:w="1800"/></w:tcPr>${paragraph("report entry")}</w:tc>`).join("")}</w:tr>`).join("")}</w:tbl>`).join("")}</w:body></w:document>`,
983
+ );
984
+ archive.file(
985
+ "_rels/.rels",
986
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
987
+ );
988
+ archive.file(
989
+ "[Content_Types].xml",
990
+ '<Types><Default Extension="png" ContentType="image/png"/></Types>',
991
+ );
992
+ // Binary media must not consume the document's markup budget.
993
+ archive.file("word/media/image.png", new Uint8Array(2_500_000));
994
+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
995
+ await using screen = await render(
996
+ <AttachmentFilePreview
997
+ name="report.docx"
998
+ mimeType="application/octet-stream"
999
+ file={file}
1000
+ sizeBytes={file.size}
1001
+ />,
1002
+ );
1003
+ await vi.waitFor(() => expect(screen.container.textContent).toMatch(/\d+ pages/), {
1004
+ timeout: 30_000,
1005
+ });
1006
+ expect(screen.container.textContent).not.toContain("Preview limited");
1007
+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1008
+ const scroll = screen.container.querySelector<HTMLElement>("[data-office-pages]")!;
1009
+ await act(() => scroll.scrollTo({ top: scroll.scrollHeight }));
1010
+ await vi.waitFor(() => expect(screen.container.textContent).toContain("page " + pages), {
1011
+ timeout: 30_000,
1012
+ });
1013
+});
1014
+
1015
+describe("standalone Mermaid previews", () => {
1016
+ it.each([
1017
+ 'A@{ "img": "//attacker.invalid/pixel.png" }',
1018
+ 'A@{ "im\\u0067": "/pixel.png" }',
1019
+ "A@{ label: &key img, *key: '/pixel.png' }",
1020
+ 'A["<img src=//attacker.invalid/pixel.png>"]',
1021
+ ])("rejects resource syntax before Mermaid lays out %s", async (node) => {
1022
+ using imageSource = vi
1023
+ .spyOn(HTMLImageElement.prototype, "src", "set")
1024
+ .mockImplementation(() => {});
1025
+ await using screen = await render(<MermaidFilePreview text={`flowchart LR\n${node}`} />);
1026
+ await vi.waitFor(() =>
1027
+ expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain(
1028
+ "Show Mermaid source",
1029
+ ),
1030
+ );
1031
+ expect(imageSource).not.toHaveBeenCalled();
1032
+ expect(screen.container.querySelector("svg")).toBeNull();
1033
+ });
1034
+
1035
+ it.each(["<-->", "<==>", "<-.->", "-->"])("renders the %s arrow", async (arrow) => {
1036
+ await using screen = await render(<MermaidFilePreview text={`flowchart LR\nA ${arrow} B`} />);
1037
+ await vi.waitFor(
1038
+ () => {
1039
+ const diagram = screen.container.querySelector("svg");
1040
+ expect(diagram?.querySelector("path")).not.toBeNull();
1041
+ expect(diagram?.textContent).toContain("A");
1042
+ expect(diagram?.textContent).toContain("B");
1043
+ },
1044
+ { timeout: 10_000 },
1045
+ );
1046
+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1047
+ });
1048
+});
1049
+
1050
+it("reloads a workspace Word file after a preview remount", async () => {
1051
+ const { default: JSZip } = await import("jszip");
1052
+ let heading = "Original outlook";
1053
+ using _fetch = stubGlobal(
1054
+ "fetch",
1055
+ vi.fn(async () => {
1056
+ const archive = new JSZip().file(
1057
+ "word/document.xml",
1058
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>${heading}</w:t></w:r></w:p></w:body></w:document>`,
1059
+ );
1060
+ return new Response(await archive.generateAsync({ type: "arraybuffer" }));
1061
+ }),
1062
+ );
1063
+ refresh.mockReset().mockResolvedValue("https://example.com/workspace.docx");
1064
+ const asset = { environmentId: EnvironmentId.make("test-environment"), attachmentId: "word" };
1065
+ await using screen = await render(
1066
+ <AttachmentFilePreview
1067
+ key="original"
1068
+ name="outlook.docx"
1069
+ mimeType="application/octet-stream"
1070
+ sizeBytes={0}
1071
+ asset={asset}
1072
+ />,
1073
+ );
1074
+ await vi.waitFor(() => expect(screen.container.textContent).toContain("Original outlook"), {
1075
+ timeout: 10_000,
1076
+ });
1077
+ heading = "Revised outlook";
1078
+ await screen.rerender(
1079
+ <AttachmentFilePreview
1080
+ key="refreshed"
1081
+ name="outlook.docx"
1082
+ mimeType="application/octet-stream"
1083
+ sizeBytes={0}
1084
+ asset={asset}
1085
+ />,
1086
+ );
1087
+ await vi.waitFor(() => expect(screen.container.textContent).toContain("Revised outlook"), {
1088
+ timeout: 10_000,
1089
+ });
1090
+ expect(screen.container.textContent).not.toContain("Original outlook");
1091
+});
1092
+
1093
+it("clears an Office metadata error when the same URL becomes previewable", async () => {
1094
+ const src = "data:application/octet-stream,invalid-office-file";
1095
+ let resolveResponse!: (response: Response) => void;
1096
+ const response = new Promise<Response>((resolve) => {
1097
+ resolveResponse = resolve;
1098
+ });
1099
+ using _fetch = stubGlobal(
1100
+ "fetch",
1101
+ vi.fn(() => response),
1102
+ );
1103
+ await using screen = await render(
1104
+ <OfficeFilePreview src={src} name="report.docx" kind="docx" sizeBytes={51 * 1024 * 1024} />,
1105
+ );
1106
+ await vi.waitFor(() => expect(screen.container.textContent).toContain("under 50 MB"));
1107
+ await screen.rerender(
1108
+ <OfficeFilePreview src={src} name="report.docx" kind="docx" sizeBytes={100} />,
1109
+ );
1110
+ await vi.waitFor(() =>
1111
+ expect(screen.container.querySelector('[aria-label="Loading file"]')).not.toBeNull(),
1112
+ );
1113
+ expect(screen.container.textContent).not.toContain("under 50 MB");
1114
+ resolveResponse(new Response("invalid-office-file"));
1115
+ await vi.waitFor(() => expect(screen.container.textContent).toContain("not a readable ZIP"), {
1116
+ timeout: 10_000,
1117
+ });
1118
+});
1119
+
1120
+describe("attachment HTML preview recovery", () => {
1121
+ const originalUrl = "data:text/html,original";
1122
+ const renewedUrl = "data:text/html,renewed";
1123
+
1124
+ function setup() {
1125
+ refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl);
1126
+ }
1127
+
1128
+ const openRemote = () =>
1129
+ render(
1130
+ <AttachmentFilePreview
1131
+ name="document.html"
1132
+ mimeType="text/html"
1133
+ sizeBytes={100}
1134
+ asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}
1135
+ />,
1136
+ );
1137
+
1138
+ const toggleMode = async (screen: Screen, label: string) => {
1139
+ const button = screen.container.querySelector<HTMLButtonElement>(
1140
+ `button[aria-label="${label}"]`,
1141
+ );
1142
+ expect(button, label).not.toBeNull();
1143
+ await act(async () => button!.click());
1144
+ };
1145
+ const alert = (screen: Screen) => screen.container.querySelector('[role="alert"]');
1146
+
1147
+ it("keeps a renewed URL for subsequent rendered and source views", async () => {
1148
+ setup();
1149
+ let now = 0;
1150
+ using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
1151
+ using _fetch = stubGlobal(
1152
+ "fetch",
1153
+ vi.fn(async () => new Response("<p>Captured HTML</p>")),
1154
+ );
1155
+ await using screen = await openRemote();
1156
+ expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(originalUrl);
1157
+ now = 61 * 60_000;
1158
+ await toggleMode(screen, "Show HTML source");
1159
+ await act(async () => {
1160
+ await import("./ReadOnlySourcePreview");
1161
+ });
1162
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));
1163
+ await vi.waitFor(() =>
1164
+ expect(screen.container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"),
1165
+ );
1166
+
1167
+ await toggleMode(screen, "Show rendered page");
1168
+ expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl);
1169
+ await toggleMode(screen, "Show HTML source");
1170
+ expect(refresh).toHaveBeenCalledTimes(2);
1171
+ expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);
1172
+ });
1173
+
1174
+ it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {
1175
+ setup();
1176
+ let now = 0;
1177
+ using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
1178
+ using _fetch = stubGlobal(
1179
+ "fetch",
1180
+ vi.fn(async () => new Response("<p>Captured HTML</p>")),
1181
+ );
1182
+ await using screen = await openRemote();
1183
+ now = 61 * 60_000;
1184
+ refresh.mockResolvedValue(null);
1185
+ await toggleMode(screen, "Show HTML source");
1186
+ expect(fetch).not.toHaveBeenCalled();
1187
+ expect(alert(screen)?.textContent).toContain("Reconnect to the environment and try again.");
1188
+
1189
+ await toggleMode(screen, "Show rendered page");
1190
+ await toggleMode(screen, "Show HTML source");
1191
+ expect(refresh).toHaveBeenCalledTimes(3);
1192
+ expect(fetch).not.toHaveBeenCalled();
1193
+ });
1194
+
1195
+ it("can return to rendered HTML after local source decoding fails", async () => {
1196
+ setup();
1197
+ let now = 0;
1198
+ using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
1199
+ using _fetch = stubGlobal(
1200
+ "fetch",
1201
+ vi.fn(async () => new Response("<p>Captured HTML</p>")),
1202
+ );
1203
+ const file = new Blob([new Uint8Array([0x3c, 0x70, 0x3e, 0xe9])], { type: "text/html" });
1204
+ await using screen = await render(
1205
+ <AttachmentFilePreview
1206
+ name="document.html"
1207
+ mimeType="text/html"
1208
+ sizeBytes={file.size}
1209
+ file={file}
1210
+ />,
1211
+ );
1212
+ await toggleMode(screen, "Show HTML source");
1213
+ await vi.waitFor(() => expect(alert(screen)?.textContent).toContain("not UTF-8"));
1214
+
1215
+ await toggleMode(screen, "Show rendered page");
1216
+ expect(alert(screen)).toBeNull();
1217
+ expect(screen.container.querySelector("iframe")?.title).toBe("document.html");
1218
+ });
1219
+});
1220
+
1221
+it("loads a font attachment through the lazy preview", async () => {
1222
+ const { default: fontUrl } =
1223
+ await import("../../../node_modules/@betteroffice/fonts/assets/Carlito-Regular.ttf?url");
1224
+ const file = await (await fetch(fontUrl)).blob();
1225
+ await using screen = await render(
1226
+ <AttachmentFilePreview
1227
+ name="Carlito.ttf"
1228
+ mimeType="font/ttf"
1229
+ sizeBytes={file.size}
1230
+ file={file}
1231
+ />,
1232
+ );
1233
+ await vi.waitFor(() => {
1234
+ const frame = screen.container.querySelector("iframe");
1235
+ expect(frame?.title).toBe("Carlito.ttf");
1236
+ expect(frame?.srcdoc).toContain("@font-face");
1237
+ expect(frame?.srcdoc).toContain("The quick brown fox");
1238
+ });
1239
+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1240
+});
1241
+
1242
+it("toggles a Mermaid attachment between diagram and source through the lazy preview", async () => {
1243
+ const text = "flowchart LR\nA --> B";
1244
+ const file = new Blob([text], { type: "text/vnd.mermaid" });
1245
+ await using screen = await render(
1246
+ <AttachmentFilePreview
1247
+ name="diagram.mmd"
1248
+ mimeType={file.type}
1249
+ sizeBytes={file.size}
1250
+ file={file}
1251
+ />,
1252
+ );
1253
+ await vi.waitFor(() =>
1254
+ expect(screen.container.querySelector("[data-markdown-mermaid] svg path")).not.toBeNull(),
1255
+ );
1256
+ await screen.getByRole("button", { name: "Expand diagram" }).click();
1257
+ await vi.waitFor(() => {
1258
+ const image = document.querySelector<HTMLImageElement>('[role="dialog"] img');
1259
+ expect(image?.alt).toBe("Mermaid diagram");
1260
+ expect(image?.naturalWidth).toBeGreaterThan(0);
1261
+ });
1262
+ await page.getByRole("button", { name: "Close image preview" }).click();
1263
+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
1264
+ await screen.getByRole("button", { name: "Show Mermaid source" }).click();
1265
+ await vi.waitFor(() => expect(screen.container.querySelector("pre")?.textContent).toBe(text));
1266
+ await screen.getByRole("button", { name: "Show rendered diagram" }).click();
1267
+ await vi.waitFor(() =>
1268
+ expect(screen.container.querySelector("[data-markdown-mermaid] svg path")).not.toBeNull(),
1269
+ );
1270
+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1271
+});
apps/web/src/components/files/AttachmentFilePreview.tsx
+61
-7
@@ -5,7 +5,11 @@ import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
5
import { settlePromise } from "@t3tools/client-runtime/state/runtime";
6
import * as AsyncResult from "effect/reactivity/AsyncResult";
7
import * as Cause from "effect/Cause";
8
-import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
8
+import {
9
+ filePreviewKind,
10
+ officePreviewKind,
11
+ FILE_TEXT_PREVIEW_MAX_BYTES,
12
+} from "@t3tools/shared/filePreview";
13
import { ChevronRightIcon, DownloadIcon, Trash2Icon, WrapTextIcon, XIcon } from "lucide-react";
14
import { Check, Code2, Copy, Eye, Table2 } from "lucide";
15
import { lazy, Suspense, useEffect, useRef, useState } from "react";
@@ -30,6 +34,18 @@ import {
34
FileSurfaceNotice,
35
} from "./fileSurfaceChrome";
36
37
+const OfficeFilePreview = lazy(() =>
38
+ import("./OfficeFilePreview").then((module) => ({ default: module.OfficeFilePreview })),
39
+);
40
+
41
+const FontFilePreview = lazy(() =>
42
+ import("./FontFilePreview").then((module) => ({ default: module.FontFilePreview })),
43
+);
44
+
45
+const MermaidFilePreview = lazy(() =>
46
+ import("./MermaidFilePreview").then((module) => ({ default: module.MermaidFilePreview })),
47
+);
48
+
49
const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
50
51
const STALE_URL_MS = 5 * 60_000;
@@ -42,7 +58,11 @@ export function ReadOnlySourcePreview(props: { name: string; text: string }) {
58
);
59
}
60
45
-function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
61
+function renderedToggleLabel(
62
+ mode: "markdown" | "mermaid" | "html" | "table",
63
+ rendered: boolean,
64
+): string {
65
+ if (mode === "mermaid") return rendered ? "Show Mermaid source" : "Show rendered diagram";
66
if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
67
if (mode === "table") return rendered ? "Show source" : "Show table";
68
return rendered ? "Show HTML source" : "Show rendered page";
@@ -55,7 +75,10 @@ export function AttachmentFilePreview(props: {
75
file?: Blob | null;
76
asset?:
77
| { environmentId: EnvironmentId; attachmentId: string }
58
- | { environmentId: EnvironmentId; resource: Extract<AssetResource, { _tag: "media-file" }> };
78
+ | {
79
+ environmentId: EnvironmentId;
80
+ resource: Extract<AssetResource, { _tag: "media-file" | "draft-workspace-file" }>;
81
+ };
82
htmlRender?: boolean;
83
threadRef?: ScopedThreadRef;
84
origin?: string;
@@ -63,9 +86,18 @@ export function AttachmentFilePreview(props: {
86
onClose?: () => void;
87
}) {
88
const kind = filePreviewKind(props);
89
+ const officeKind = officePreviewKind(props);
90
const delimiter = filePreviewDelimiter(props);
91
const renderedMode =
68
- kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;
92
+ kind === "mermaid"
93
+ ? "mermaid"
94
+ : kind === "markdown"
95
+ ? "markdown"
96
+ : kind === "html"
97
+ ? "html"
98
+ : delimiter
99
+ ? "table"
100
+ : null;
101
const attachmentId =
102
props.asset && "attachmentId" in props.asset ? props.asset.attachmentId : undefined;
103
const { copyToClipboard, isCopied } = useCopyToClipboard({ target: props.name });
@@ -82,7 +114,11 @@ export function AttachmentFilePreview(props: {
114
disposition: "inline" as const,
115
}
116
: null;
85
- const downloadResource = resource ? { ...resource, disposition: "attachment" as const } : null;
117
+ const downloadResource = resource
118
+ ? resource._tag === "draft-workspace-file"
119
+ ? resource
120
+ : { ...resource, disposition: "attachment" as const }
121
+ : null;
122
const refresh = useAssetUrlRefresh(
123
props.file ? null : (props.asset?.environmentId ?? null),
124
props.file ? null : resource,
@@ -127,7 +163,8 @@ export function AttachmentFilePreview(props: {
163
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
164
}, [props.file, refresh, revision]);
165
const url = props.file ? localUrl : remoteUrl;
130
- const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
166
+ const needsText =
167
+ kind === "text" || kind === "markdown" || kind === "mermaid" || (kind === "html" && !rendered);
168
useEffect(() => {
169
if (!needsText || !url) return;
170
const controller = new AbortController();
@@ -170,7 +207,7 @@ export function AttachmentFilePreview(props: {
207
needsText &&
208
content !== null &&
209
!(delimiter && rendered) &&
173
- !(kind === "markdown" && rendered);
210
+ !((kind === "markdown" || kind === "mermaid") && rendered);
211
212
const save = () => {
213
setSaving(true);
@@ -217,6 +254,10 @@ export function AttachmentFilePreview(props: {
254
) : needsText && content ? (
255
delimiter && rendered ? (
256
<DelimitedTablePreview name={props.name} text={content.text} delimiter={delimiter} />
257
+ ) : kind === "mermaid" && rendered ? (
258
+ <Suspense fallback={<FileSurfaceLoading />}>
259
+ <MermaidFilePreview text={content.text} />
260
+ </Suspense>
261
) : kind === "markdown" && rendered ? (
262
<ScrollArea className="min-h-0 flex-1">
263
<ChatMarkdown text={content.text} cwd={undefined} className="mx-auto max-w-4xl px-6 py-5" />
@@ -224,6 +265,19 @@ export function AttachmentFilePreview(props: {
265
) : (
266
<ReadOnlySourcePreview name={props.name} text={content.text} />
267
)
268
+ ) : kind === "font" ? (
269
+ <Suspense fallback={<FileSurfaceLoading />}>
270
+ <FontFilePreview src={url} name={props.name} />
271
+ </Suspense>
272
+ ) : officeKind ? (
273
+ <Suspense fallback={<FileSurfaceLoading />}>
274
+ <OfficeFilePreview
275
+ src={url}
276
+ name={props.name}
277
+ kind={officeKind}
278
+ sizeBytes={props.sizeBytes}
279
+ />
280
+ </Suspense>
281
) : kind === "pdf" || kind === "html" ? (
282
<BrowserDocumentFrame
283
src={url}
apps/web/src/components/files/FilePreviewPanel.test.ts
+11
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vite-plus/test";
6
import { remapFileCommentAnnotations } from "./fileCommentAnnotations";
7
import {
8
filePreviewReadErrorMessage,
9
+ isMarkdownPreviewFile,
10
resolveFilePreviewPath,
11
setMarkdownTaskChecked,
12
shouldShowFileExplorer,
@@ -63,6 +64,16 @@ describe("file comment annotations", () => {
64
});
65
});
66
67
+describe("isMarkdownPreviewFile", () => {
68
+ it("recognizes markdown and MDX files case-insensitively", () => {
69
+ expect(isMarkdownPreviewFile("README.md")).toBe(true);
70
+ expect(isMarkdownPreviewFile("docs/guide.MDX")).toBe(true);
71
+ expect(isMarkdownPreviewFile("docs/guide.MARKDOWN")).toBe(true);
72
+ expect(isMarkdownPreviewFile("docs/guide.mdown")).toBe(true);
73
+ expect(isMarkdownPreviewFile("docs/guide.mkd")).toBe(true);
74
+ });
75
+});
76
+
77
describe("setMarkdownTaskChecked", () => {
78
const markdown = "- [ ] First\n- [x] Second\n";
79
apps/web/src/components/files/FilePreviewPanel.tsx
+75
-29
@@ -11,7 +11,9 @@ import { AuthFilesystemWriteScope } from "@t3tools/contracts";
11
import {
12
isWorkspaceAudioPreviewPath,
13
isWorkspaceImagePreviewPath,
14
+ isWorkspaceFontPreviewPath,
15
isWorkspaceVideoPreviewPath,
16
+ officePreviewKind,
17
} from "@t3tools/shared/filePreview";
18
import { useAtomValue } from "@effect/atom-react";
19
import {
@@ -41,7 +43,7 @@ import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
43
import { FolderTree, Globe2, WrapTextIcon } from "lucide-react";
44
import { Code2, Eye, Table2 } from "lucide";
45
import * as Schema from "effect/Schema";
44
-import { useEffect, useRef, useState } from "react";
46
+import { lazy, Suspense, useEffect, useRef, useState } from "react";
47
48
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
49
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
@@ -141,6 +143,10 @@ interface FilePreviewPanelProps {
143
workspaceMutationId: string | null;
144
}
145
146
+const MermaidFilePreview = lazy(() =>
147
+ import("./MermaidFilePreview").then((module) => ({ default: module.MermaidFilePreview })),
148
+);
149
+
150
const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
151
const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";
152
const RENDER_BROWSER_FILE_STORAGE_KEY = "t3code.renderBrowserFile";
@@ -954,7 +960,11 @@ function RenderedMarkdownSurface({
960
);
961
}
962
957
-function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
963
+function renderedToggleLabel(
964
+ mode: "markdown" | "mermaid" | "html" | "table",
965
+ rendered: boolean,
966
+): string {
967
+ if (mode === "mermaid") return rendered ? "Show Mermaid source" : "Show rendered diagram";
968
if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
969
if (mode === "table") return rendered ? "Show source" : "Show table";
970
return rendered ? "Show HTML source" : "Show rendered page";
@@ -992,6 +1002,7 @@ export default function FilePreviewPanel({
1002
const relativePath =
1003
attachment === undefined ? resolveFilePreviewPath(requestedPath, cwd) : requestedPath;
1004
const draft = typeof composerDraftTarget === "string";
1005
+ const [documentRefreshId, setDocumentRefreshId] = useState(0);
1006
const { resolvedTheme } = useTheme();
1007
const wordWrap = useClientSettings((settings) => settings.wordWrap);
1008
const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);
@@ -1011,6 +1022,10 @@ export default function FilePreviewPanel({
1022
const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);
1023
const isMedia = isImage || isVideo || isAudio;
1024
const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);
1025
+ const isDocument =
1026
+ relativePath !== null &&
1027
+ (officePreviewKind({ name: relativePath }) !== null ||
1028
+ isWorkspaceFontPreviewPath(relativePath));
1029
const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);
1030
const isHostFile =
1031
attachment !== undefined || (relativePath !== null && isHostPath(relativePath));
@@ -1071,35 +1086,54 @@ export default function FilePreviewPanel({
1086
);
1087
const breadcrumbRef = useRef<HTMLDivElement>(null);
1088
const isMarkdown = previewPath ? isMarkdownPreviewFile(previewPath) : false;
1089
+ const isMermaid = previewPath !== null && /\.(mmd|mermaid)$/i.test(previewPath);
1090
+ const [renderMermaidPreferred, setRenderMermaidPreferred] = useLocalStorage(
1091
+ "t3code.renderMermaid",
1092
+ true,
1093
+ Schema.Boolean,
1094
+ );
1095
const tableDelimiter =
1096
previewPath && attachment === undefined ? filePreviewDelimiter({ name: previewPath }) : null;
1097
const revealHandled =
1098
revealLine === null ||
1099
(handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);
1100
const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;
1101
+ const renderMermaid = isMermaid && renderMermaidPreferred && revealHandled;
1102
const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);
1103
const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled;
1082
- const renderedMode = isMarkdown
1083
- ? ("markdown" as const)
1084
- : tableDelimiter
1085
- ? ("table" as const)
1086
- : isHtml
1087
- ? ("html" as const)
1088
- : null;
1104
+ const renderedMode = isMermaid
1105
+ ? ("mermaid" as const)
1106
+ : isMarkdown
1107
+ ? ("markdown" as const)
1108
+ : tableDelimiter
1109
+ ? ("table" as const)
1110
+ : isHtml
1111
+ ? ("html" as const)
1112
+ : null;
1113
const canToggleRendered =
1114
previewPath !== null && attachment === undefined && renderedMode !== null;
1115
const showsRawText =
1116
previewPath !== null &&
1117
file.data !== null &&
1118
!(isMarkdown && renderMarkdown) &&
1119
+ !renderMermaid &&
1120
!(tableDelimiter && renderTable) &&
1096
- !renderBrowserFile;
1097
- const rendered = isMarkdown ? renderMarkdown : tableDelimiter ? renderTable : renderBrowserFile;
1098
- const setRenderedPreferred = isMarkdown
1099
- ? setRenderMarkdownPreferred
1100
- : tableDelimiter
1101
- ? setRenderTablePreferred
1102
- : setRenderBrowserFilePreferred;
1121
+ !renderBrowserFile &&
1122
+ !isDocument;
1123
+ const rendered = isMermaid
1124
+ ? renderMermaid
1125
+ : isMarkdown
1126
+ ? renderMarkdown
1127
+ : tableDelimiter
1128
+ ? renderTable
1129
+ : renderBrowserFile;
1130
+ const setRenderedPreferred = isMermaid
1131
+ ? setRenderMermaidPreferred
1132
+ : isMarkdown
1133
+ ? setRenderMarkdownPreferred
1134
+ : tableDelimiter
1135
+ ? setRenderTablePreferred
1136
+ : setRenderBrowserFilePreferred;
1137
const canOpenInBrowser =
1138
canOperatePreview &&
1139
previewPath !== null &&
@@ -1126,9 +1160,8 @@ export default function FilePreviewPanel({
1160
enabled:
1161
attachment === undefined &&
1162
relativePath !== null &&
1129
- // Skip mutation reads for media/PDF files; re-read similarly named folders to detect conversion to
1130
- // files.
1131
- (isFolder || (!isMedia && !isPdf)) &&
1163
+ // Skip mutation reads for media and documents; folders still detect conversion to files.
1164
+ (isFolder || (!isMedia && !isPdf && !isDocument)) &&
1165
!selectedFilePending,
1166
mutationId: workspaceMutationId,
1167
refresh: file.refresh,
@@ -1353,20 +1386,25 @@ export default function FilePreviewPanel({
1386
title={relativePath}
1387
workspaceMutationId={workspaceMutationId}
1388
/>
1356
- ) : relativePath && absolutePath && file.readError?.failure === "binary_file" ? (
1389
+ ) : relativePath &&
1390
+ absolutePath &&
1391
+ (isDocument || file.readError?.failure === "binary_file") ? (
1392
<AttachmentFilePreview
1358
- key={`${environmentId}:${absolutePath}`}
1393
+ key={`${environmentId}:${absolutePath}:${workspaceMutationId}:${documentRefreshId}`}
1394
name={relativePath.split(/[\\/]/).at(-1) || relativePath}
1395
mimeType="application/octet-stream"
1396
sizeBytes={0}
1397
asset={{
1398
environmentId,
1364
- resource: {
1365
- _tag: "media-file",
1366
- threadId: threadRef.threadId,
1367
- path: absolutePath,
1368
- disposition: "attachment",
1369
- },
1399
+ resource:
1400
+ draft && isDocument
1401
+ ? { _tag: "draft-workspace-file", cwd, path: absolutePath }
1402
+ : {
1403
+ _tag: "media-file",
1404
+ threadId: threadRef.threadId,
1405
+ path: absolutePath,
1406
+ ...(isDocument ? {} : { disposition: "attachment" as const }),
1407
+ },
1408
}}
1409
origin="File"
1410
/>
@@ -1403,7 +1441,11 @@ export default function FilePreviewPanel({
1441
<Spinner size="lg" />
1442
</div>
1443
) : relativePath && file.data ? (
1406
- isMarkdown && renderMarkdown ? (
1444
+ renderMermaid ? (
1445
+ <Suspense fallback={<FileSurfaceLoading />}>
1446
+ <MermaidFilePreview text={file.data.contents} />
1447
+ </Suspense>
1448
+ ) : isMarkdown && renderMarkdown ? (
1449
<RenderedMarkdownSurface
1450
key={relativePath}
1451
environmentId={environmentId}
@@ -1472,7 +1514,11 @@ export default function FilePreviewPanel({
1514
onOpenFile={onOpenFile}
1515
workspaceMutationId={workspaceMutationId}
1516
{...(previewPath && !isMedia && !isPdf
1475
- ? { onRefreshSelectedFile: file.refresh }
1517
+ ? {
1518
+ onRefreshSelectedFile: isDocument
1519
+ ? () => setDocumentRefreshId((revision) => revision + 1)
1520
+ : file.refresh,
1521
+ }
1522
: {})}
1523
/>
1524
</aside>
apps/web/src/components/files/FontFilePreview.tsx
new
+13
@@ -0,0 +1,13 @@
1
+import { lazy, Suspense } from "react";
2
+
3
+import { FileSurfaceLoading } from "./fileSurfaceChrome";
4
+
5
+const FontViewer = lazy(() => import("./FontViewer"));
6
+
7
+export function FontFilePreview(props: { readonly src: string; readonly name: string }) {
8
+ return (
9
+ <Suspense fallback={<FileSurfaceLoading />}>
10
+ <FontViewer key={props.src} {...props} />
11
+ </Suspense>
12
+ );
13
+}
apps/web/src/components/files/FontViewer.tsx
new
+86
@@ -0,0 +1,86 @@
1
+import { useEffect, useState } from "react";
2
+
3
+import { useTheme } from "~/hooks/useTheme";
4
+
5
+import { FileSurfaceLoading } from "./fileSurfaceChrome";
6
+
7
+const MAX_FONT_BYTES = 10 * 1024 * 1024;
8
+
9
+async function readFont(src: string, signal: AbortSignal) {
10
+ const response = await fetch(src, { signal });
11
+ if (!response.ok) throw new Error("The font could not be loaded.");
12
+ if (Number(response.headers.get("content-length")) > MAX_FONT_BYTES)
13
+ throw new Error("Font previews are limited to 10 MB.");
14
+ const reader = response.body?.getReader();
15
+ if (!reader) throw new Error("The font is unavailable.");
16
+ const chunks: Uint8Array<ArrayBuffer>[] = [];
17
+ let length = 0;
18
+ try {
19
+ while (true) {
20
+ const { done, value } = await reader.read();
21
+ if (done) break;
22
+ length += value.length;
23
+ if (length > MAX_FONT_BYTES) throw new Error("Font previews are limited to 10 MB.");
24
+ chunks.push(value);
25
+ }
26
+ } finally {
27
+ await reader.cancel();
28
+ }
29
+ const blob = new Blob(chunks);
30
+ await new FontFace("file-preview", await blob.arrayBuffer()).load();
31
+ return await new Promise<string>((resolve, reject) => {
32
+ const reader = new FileReader();
33
+ reader.addEventListener("load", () => resolve(String(reader.result)), { once: true });
34
+ reader.addEventListener("error", () => reject(new Error("The font could not be decoded.")), {
35
+ once: true,
36
+ });
37
+ reader.readAsDataURL(blob);
38
+ });
39
+}
40
+
41
+export default function FontViewer(props: { readonly src: string; readonly name: string }) {
42
+ const { resolvedTheme } = useTheme();
43
+ const [data, setData] = useState<string | null>(null);
44
+ const [error, setError] = useState<string | null>(null);
45
+ // oxlint-disable-next-line t3code/react-effect-budget -- Load the font from its URL and abort the request and timeout when the source changes or unmounts.
46
+ useEffect(() => {
47
+ const controller = new AbortController();
48
+ const timeout = setTimeout(() => {
49
+ setError("The font took too long to load.");
50
+ controller.abort();
51
+ }, 30_000);
52
+ void readFont(props.src, controller.signal)
53
+ .then((value) => {
54
+ if (!controller.signal.aborted) setData(value);
55
+ })
56
+ .catch((cause: unknown) => {
57
+ if (!controller.signal.aborted)
58
+ setError(cause instanceof Error ? cause.message : "The font is damaged or unsupported.");
59
+ })
60
+ .finally(() => clearTimeout(timeout));
61
+ return () => {
62
+ controller.abort();
63
+ clearTimeout(timeout);
64
+ };
65
+ }, [props.src]);
66
+ if (error)
67
+ return (
68
+ <div
69
+ role="alert"
70
+ className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
71
+ >
72
+ <p className="text-sm font-medium">No preview for this file</p>
73
+ <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
74
+ {error} Save it to open in another app.
75
+ </p>
76
+ </div>
77
+ );
78
+ if (!data) return <FileSurfaceLoading />;
79
+ const tokens = getComputedStyle(document.documentElement);
80
+ const background = tokens.getPropertyValue("--background");
81
+ const foreground = tokens.getPropertyValue("--foreground");
82
+ const srcDoc = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><style>@font-face{font-family:preview;src:url('${data}')}html{color-scheme:${resolvedTheme};background:${background};color:${foreground}}body{margin:0;padding:32px;font-family:preview;overflow-wrap:anywhere}h1{font-size:40px;font-weight:normal}p{line-height:1.4}small{font:12px monospace;display:block;opacity:.6;margin-bottom:8px}</style></head><body><h1>Font preview</h1><p style="font-size:24px">ABCDEFGHIJKLMNOPQRSTUVWXYZ<br>abcdefghijklmnopqrstuvwxyz<br>0123456789 !?&@#%(){}[]</p>${[12, 16, 24, 40, 64].map((size) => `<p style="font-size:${size}px"><small>${size} px</small>The quick brown fox jumps over the lazy dog.</p>`).join("")}</body></html>`;
83
+ return (
84
+ <iframe title={props.name} srcDoc={srcDoc} sandbox="" className="min-h-0 flex-1 border-0" />
85
+ );
86
+}
apps/web/src/components/files/MermaidFilePreview.tsx
new
+13
@@ -0,0 +1,13 @@
1
+import { lazy, Suspense } from "react";
2
+
3
+import { FileSurfaceLoading } from "./fileSurfaceChrome";
4
+
5
+const MermaidViewer = lazy(() => import("./MermaidViewer"));
6
+
7
+export function MermaidFilePreview(props: { readonly text: string }) {
8
+ return (
9
+ <Suspense fallback={<FileSurfaceLoading />}>
10
+ <MermaidViewer key={props.text} {...props} />
11
+ </Suspense>
12
+ );
13
+}
apps/web/src/components/files/MermaidViewer.tsx
new
+33
@@ -0,0 +1,33 @@
1
+import { useState } from "react";
2
+
3
+import { MermaidDiagram } from "../chat/MermaidDiagram";
4
+import { ExpandedImageDialog } from "../chat/ExpandedImageDialog";
5
+
6
+export default function MermaidViewer(props: { readonly text: string }) {
7
+ const [expanded, setExpanded] = useState<string | null>(null);
8
+ // Mermaid lays out DOM before sanitizing its SVG. Refuse resource and config
9
+ // syntax before that pass so standalone files cannot initiate requests. Node
10
+ // metadata is YAML, whose escaped/aliased image keys cannot be checked lexically.
11
+ if (
12
+ /%%\s*\{|^\s*---|<\/?[A-Za-z]|<[!?]|@\s*\{|\b(?:img|image)\s*:|url\s*\(|@import|(?:https?|data|blob|file):/im.test(
13
+ props.text,
14
+ )
15
+ )
16
+ return (
17
+ <div role="alert" className="p-6 text-xs text-muted-foreground">
18
+ This diagram contains resource URLs, markup, node metadata, or custom configuration. Show
19
+ Mermaid source to inspect it safely.
20
+ </div>
21
+ );
22
+ return (
23
+ <div className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto p-6 [&_*]:animate-none!">
24
+ <MermaidDiagram source={props.text} onExpand={setExpanded} />
25
+ {expanded ? (
26
+ <ExpandedImageDialog
27
+ preview={{ images: [{ src: expanded, name: "Mermaid diagram" }], index: 0 }}
28
+ onClose={() => setExpanded(null)}
29
+ />
30
+ ) : null}
31
+ </div>
32
+ );
33
+}
apps/web/src/components/files/OfficeFilePreview.tsx
new
+19
@@ -0,0 +1,19 @@
1
+import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
2
+import { lazy, Suspense } from "react";
3
+
4
+import { FileSurfaceLoading } from "./fileSurfaceChrome";
5
+
6
+const OfficeViewer = lazy(() => import("./OfficeViewer"));
7
+
8
+export function OfficeFilePreview(props: {
9
+ readonly src: string;
10
+ readonly name: string;
11
+ readonly kind: OfficePreviewKind;
12
+ readonly sizeBytes?: number;
13
+}) {
14
+ return (
15
+ <Suspense fallback={<FileSurfaceLoading />}>
16
+ <OfficeViewer key={JSON.stringify([props.src, props.kind, props.sizeBytes])} {...props} />
17
+ </Suspense>
18
+ );
19
+}
apps/web/src/components/files/OfficeViewer.tsx
new
+129
@@ -0,0 +1,129 @@
1
+import { useStableCallback } from "~/hooks/useStableCallback";
2
+import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
3
+import { lazy, Suspense, useEffect, useState } from "react";
4
+import {
5
+ FileSurfaceLoading,
6
+ FileSurfaceNotice,
7
+ FILE_SURFACE_SUBHEADER_CLASS,
8
+} from "./fileSurfaceChrome";
9
+import { OFFICE_PREVIEW_MAX_BYTES, type OfficeWorkerResult } from "./officePreviewProtocol";
10
+const WordDocument = lazy(() => import("./office/WordDocument"));
11
+const Spreadsheet = lazy(() => import("./office/Spreadsheet"));
12
+const Presentation = lazy(() => import("./office/Presentation"));
13
+async function readOfficeFile(src: string, signal: AbortSignal) {
14
+ const response = await fetch(src, { signal });
15
+ if (!response.ok) throw new Error("The file could not be loaded. Close it and try again.");
16
+ if (Number(response.headers.get("content-length")) > OFFICE_PREVIEW_MAX_BYTES)
17
+ throw new Error("Preview limited to files under 50 MB.");
18
+ const reader = response.body?.getReader();
19
+ if (!reader) throw new Error("The file is unavailable.");
20
+ const chunks: Uint8Array<ArrayBuffer>[] = [];
21
+ let size = 0;
22
+ try {
23
+ while (true) {
24
+ const { value, done } = await reader.read();
25
+ if (done) break;
26
+ size += value.length;
27
+ if (size > OFFICE_PREVIEW_MAX_BYTES) throw new Error("Preview limited to files under 50 MB.");
28
+ chunks.push(value);
29
+ }
30
+ } finally {
31
+ await reader.cancel();
32
+ }
33
+ return new Blob(chunks).arrayBuffer();
34
+}
35
+
36
+export default function OfficeViewer(props: {
37
+ readonly src: string;
38
+ readonly name: string;
39
+ readonly kind: OfficePreviewKind;
40
+ readonly sizeBytes?: number;
41
+}) {
42
+ const [error, setError] = useState<string | null>(null);
43
+ const [prepared, setPrepared] = useState<Exclude<OfficeWorkerResult, { type: "error" }>>();
44
+ const [details, setDetails] = useState("");
45
+ const fail = useStableCallback((cause: unknown) =>
46
+ setError(cause instanceof Error ? cause.message : "Could not render this Office document."),
47
+ );
48
+ // oxlint-disable-next-line t3code/react-effect-budget -- Own the Office fetch, preparation worker, and timeout for this source and release them on cleanup.
49
+ useEffect(() => {
50
+ if ((props.sizeBytes ?? 0) > OFFICE_PREVIEW_MAX_BYTES) {
51
+ // Metadata bounds are checked before fetching or starting an engine.
52
+ // oxlint-disable-next-line react/set-state-in-effect
53
+ setError("Preview limited to files under 50 MB.");
54
+ return;
55
+ }
56
+ const controller = new AbortController();
57
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
58
+ type: "module",
59
+ });
60
+ const failure = (cause: unknown) => {
61
+ if (!controller.signal.aborted) fail(cause);
62
+ controller.abort();
63
+ worker.terminate();
64
+ };
65
+ const timer = setTimeout(
66
+ () => failure(new Error("This document took too long to preview. Open it in another app.")),
67
+ 30000,
68
+ );
69
+ worker.addEventListener("error", () => failure(new Error("Could not load the Office viewer.")));
70
+ worker.addEventListener("messageerror", () =>
71
+ failure(new Error("Could not read the Office viewer response.")),
72
+ );
73
+ worker.addEventListener("message", (event: MessageEvent<OfficeWorkerResult>) => {
74
+ if (controller.signal.aborted) return;
75
+ clearTimeout(timer);
76
+ if (event.data.type === "error") failure(new Error(event.data.message));
77
+ else {
78
+ setPrepared(event.data);
79
+ worker.terminate();
80
+ }
81
+ });
82
+ void readOfficeFile(props.src, controller.signal)
83
+ .then((bytes) => {
84
+ if (!controller.signal.aborted)
85
+ worker.postMessage({ type: "open", kind: props.kind, bytes }, [bytes]);
86
+ })
87
+ .catch(failure);
88
+ return () => {
89
+ controller.abort();
90
+ worker.terminate();
91
+ clearTimeout(timer);
92
+ };
93
+ }, [props.src, props.kind, props.sizeBytes, fail]);
94
+ if (error)
95
+ return (
96
+ <div
97
+ role="alert"
98
+ className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
99
+ >
100
+ <p className="text-sm font-medium">No preview for this file</p>
101
+ <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
102
+ {error} Save it or open it in another app.
103
+ </p>
104
+ </div>
105
+ );
106
+ if (!prepared) return <FileSurfaceLoading />;
107
+ const Viewer =
108
+ props.kind === "docx" ? WordDocument : props.kind === "xlsx" ? Spreadsheet : Presentation;
109
+ return (
110
+ <div className="flex min-h-0 flex-1 flex-col">
111
+ {details ? (
112
+ <div className={FILE_SURFACE_SUBHEADER_CLASS}>
113
+ <span className="text-xs text-muted-foreground" aria-live="polite">
114
+ {details}
115
+ {props.kind !== "xlsx" ? " · Fit to width" : ""}
116
+ </span>
117
+ </div>
118
+ ) : null}
119
+ {prepared.truncated ? (
120
+ <FileSurfaceNotice>
121
+ Preview limited. Save it or open it in another app to read the full document.
122
+ </FileSurfaceNotice>
123
+ ) : null}
124
+ <Suspense fallback={<FileSurfaceLoading />}>
125
+ <Viewer bytes={prepared.bytes} onDetails={setDetails} onError={fail} />
126
+ </Suspense>
127
+ </div>
128
+ );
129
+}
apps/web/src/components/files/filePreviewMode.ts
+2
-1
@@ -7,7 +7,8 @@ export function resolveFilePreviewPath(path: string | null, cwd: string): string
7
return path === "." || workspaceRelativeFilePath(path, cwd) === "." ? null : path;
8
}
9
10
-export const isMarkdownPreviewFile = (path: string): boolean => /\.(?:md|mdx)$/i.test(path);
10
+export const isMarkdownPreviewFile = (path: string): boolean =>
11
+ /\.(?:md|mdx|markdown|mdown|mkd)$/i.test(path);
12
13
export function filePreviewReadErrorMessage(error: ProjectReadFileError): string {
14
switch (error.failure) {
apps/web/src/components/files/office/LICENSE.opencode
new
+21
@@ -0,0 +1,21 @@
1
+MIT License
2
+
3
+Copyright (c) 2025 opencode
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in all
13
+copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+SOFTWARE.
apps/web/src/components/files/office/OfficePages.tsx
new
+206
@@ -0,0 +1,206 @@
1
+/* oxlint-disable react/no-array-index-key -- A page keeps its ordinal throughout incremental layout. */
2
+import { observeResize } from "~/lib/observeResize";
3
+import {
4
+ useEffect,
5
+ useImperativeHandle,
6
+ useRef,
7
+ useState,
8
+ type ReactNode,
9
+ type RefObject,
10
+} from "react";
11
+
12
+export type PageSize = {
13
+ readonly width: number;
14
+ readonly height: number;
15
+ readonly background?: string | undefined;
16
+};
17
+export type PaintPage = (
18
+ index: number,
19
+ canvas: HTMLCanvasElement,
20
+ scale: number,
21
+ signal: AbortSignal,
22
+) => Promise<void>;
23
+
24
+export function OfficePages(props: {
25
+ pages: readonly PageSize[];
26
+ paint: PaintPage;
27
+ label: string;
28
+ overlay?: (index: number) => ReactNode;
29
+ footer?: (index: number) => ReactNode;
30
+ scrollRef?: RefObject<((index: number, y?: number) => void) | null>;
31
+ onPageChange?: (index: number) => void;
32
+ onError: (error: unknown) => void;
33
+}) {
34
+ const scroller = useRef<HTMLDivElement>(null);
35
+ const rows = useRef(new Map<number, HTMLDivElement>());
36
+ const [width, setWidth] = useState(0);
37
+ const [settledWidth, setSettledWidth] = useState(0);
38
+ const [mounted, setMounted] = useState(6);
39
+ // oxlint-disable-next-line t3code/react-effect-budget -- Observe the scroll container width and debounce raster resizing, releasing the observer and timer on unmount.
40
+ useEffect(() => {
41
+ const root = scroller.current;
42
+ if (!root) return;
43
+ let timer: ReturnType<typeof setTimeout>;
44
+ const unobserve = observeResize(root, ([entry]) => {
45
+ if (!entry) return;
46
+ const next = entry.contentRect.width;
47
+ setWidth(next);
48
+ clearTimeout(timer);
49
+ timer = setTimeout(() => setSettledWidth(next), 150);
50
+ });
51
+ return () => {
52
+ clearTimeout(timer);
53
+ unobserve();
54
+ };
55
+ }, []);
56
+ // oxlint-disable-next-line t3code/react-effect-budget -- Yield between page mounting batches with a timer so large documents do not block the browser.
57
+ useEffect(() => {
58
+ if (mounted >= props.pages.length) return;
59
+ const timer = setTimeout(() => setMounted((n) => Math.min(props.pages.length, n + 50)), 0);
60
+ return () => clearTimeout(timer);
61
+ }, [mounted, props.pages.length]);
62
+ useImperativeHandle(
63
+ props.scrollRef,
64
+ () =>
65
+ (index: number, y = 0) => {
66
+ const row = rows.current.get(index);
67
+ const page = props.pages[index];
68
+ if (row && page)
69
+ scroller.current?.scrollTo({
70
+ top: row.offsetTop + y * Math.min(1, Math.max(0, width - 48) / page.width) - 24,
71
+ });
72
+ },
73
+ [props.pages, width],
74
+ );
75
+ return (
76
+ <div
77
+ ref={scroller}
78
+ className="relative min-h-0 flex-1 overflow-auto bg-muted/60"
79
+ data-office-pages
80
+ onScroll={() => {
81
+ const root = scroller.current;
82
+ if (!root || !props.onPageChange) return;
83
+ if (
84
+ root.scrollHeight > root.clientHeight &&
85
+ root.scrollTop + root.clientHeight >= root.scrollHeight - 1
86
+ ) {
87
+ props.onPageChange(Math.min(mounted, props.pages.length) - 1);
88
+ return;
89
+ }
90
+ for (const [index, row] of [...rows.current].sort(([a], [b]) => a - b)) {
91
+ if (row.offsetTop + row.offsetHeight > root.scrollTop + 24) {
92
+ props.onPageChange(index);
93
+ break;
94
+ }
95
+ }
96
+ }}
97
+ >
98
+ <div className="flex flex-col items-center gap-4 py-6">
99
+ {props.pages.slice(0, mounted).map((page, index) => (
100
+ <OfficePage
101
+ key={index}
102
+ page={page}
103
+ index={index}
104
+ root={scroller}
105
+ register={(el) => {
106
+ if (el) rows.current.set(index, el);
107
+ else rows.current.delete(index);
108
+ }}
109
+ scale={Math.min(1, Math.max(0, width - 48) / page.width)}
110
+ rasterScale={Math.min(1, Math.max(0, (settledWidth || width) - 48) / page.width)}
111
+ {...props}
112
+ />
113
+ ))}
114
+ </div>
115
+ </div>
116
+ );
117
+}
118
+
119
+function OfficePage(props: {
120
+ page: PageSize;
121
+ index: number;
122
+ root: RefObject<HTMLDivElement | null>;
123
+ register: (element: HTMLDivElement | null) => void;
124
+ scale: number;
125
+ rasterScale: number;
126
+ paint: PaintPage;
127
+ label: string;
128
+ overlay?: (index: number) => ReactNode;
129
+ footer?: (index: number) => ReactNode;
130
+ onError: (error: unknown) => void;
131
+}) {
132
+ const {
133
+ root,
134
+ rasterScale,
135
+ index,
136
+ onError,
137
+ page,
138
+ paint,
139
+ scale,
140
+ register,
141
+ label,
142
+ overlay,
143
+ footer,
144
+ } = props;
145
+ const row = useRef<HTMLDivElement>(null);
146
+ const canvas = useRef<HTMLCanvasElement>(null);
147
+ const [near, setNear] = useState(false);
148
+ const [ratio, setRatio] = useState(window.devicePixelRatio || 1);
149
+ // oxlint-disable-next-line t3code/react-effect-budget -- Observe the page's viewport proximity to limit painting and text layers to nearby pages.
150
+ useEffect(() => {
151
+ if (!row.current) return;
152
+ const observer = new IntersectionObserver(
153
+ ([entry]) => setNear(entry?.isIntersecting ?? false),
154
+ { root: root.current, rootMargin: "100% 0px" },
155
+ );
156
+ observer.observe(row.current);
157
+ return () => observer.disconnect();
158
+ }, [root]);
159
+ // oxlint-disable-next-line t3code/react-effect-budget -- Subscribe to display density changes so canvas rasters match the current screen.
160
+ useEffect(() => {
161
+ const query = matchMedia(`(resolution: ${ratio}dppx)`);
162
+ const change = () => setRatio(window.devicePixelRatio || 1);
163
+ query.addEventListener("change", change);
164
+ return () => query.removeEventListener("change", change);
165
+ }, [ratio]);
166
+ // oxlint-disable-next-line t3code/react-effect-budget -- Paint the visible page canvas at the current raster scale and cancel obsolete paint requests.
167
+ useEffect(() => {
168
+ const target = canvas.current;
169
+ if (!target || !page || !near || ratio <= 0 || rasterScale <= 0) return;
170
+ const controller = new AbortController();
171
+ void paint(index, target, rasterScale, controller.signal).catch((cause: unknown) => {
172
+ if (!controller.signal.aborted) onError(cause);
173
+ });
174
+ return () => controller.abort();
175
+ }, [near, index, page, paint, rasterScale, onError, ratio]);
176
+ // oxlint-disable-next-line t3code/react-effect-budget -- Release the canvas backing store when its page moves away from the viewport.
177
+ useEffect(() => {
178
+ const target = canvas.current;
179
+ if (!near && target) {
180
+ target.width = 0;
181
+ target.height = 0;
182
+ }
183
+ }, [near]);
184
+ return (
185
+ <div className="flex shrink-0 flex-col gap-3" style={{ width: page.width * scale }}>
186
+ <div
187
+ ref={(el) => {
188
+ row.current = el;
189
+ register(el);
190
+ }}
191
+ role="group"
192
+ aria-label={`${label} ${index + 1}`}
193
+ className="relative shrink-0 shadow-md"
194
+ style={{
195
+ width: page.width * scale,
196
+ height: page.height * scale,
197
+ background: page.background ?? "#fff",
198
+ }}
199
+ >
200
+ <canvas ref={canvas} aria-hidden="true" className="absolute inset-0 block size-full" />
201
+ {near ? overlay?.(index) : null}
202
+ </div>
203
+ {footer?.(index)}
204
+ </div>
205
+ );
206
+}
apps/web/src/components/files/office/Presentation.tsx
new
+187
@@ -0,0 +1,187 @@
1
+/* oxlint-disable react/no-unstable-nested-components -- These callbacks return overlays, and are invoked as render functions. */
2
+import { useEffect, useRef, useState } from "react";
3
+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
4
+import {
5
+ FileSurfaceAction,
6
+ FileSurfaceLoading,
7
+ FILE_SURFACE_SUBHEADER_CLASS,
8
+} from "../fileSurfaceChrome";
9
+import { OfficePages, type PaintPage } from "./OfficePages";
10
+import { createWorkerClient } from "./worker-rpc";
11
+import {
12
+ maxImageSide,
13
+ type SlideMethods,
14
+ type SlideSummary,
15
+ type VectorRequest,
16
+} from "./slide-protocol";
17
+
18
+type Opened = { slides: readonly SlideSummary[]; paint: PaintPage };
19
+export default function Presentation(props: {
20
+ bytes: ArrayBuffer;
21
+ onDetails: (text: string) => void;
22
+ onError: (cause: unknown) => void;
23
+}) {
24
+ const { onError, bytes: source, onDetails } = props;
25
+ const [opened, setOpened] = useState<Opened>();
26
+ const [page, setPage] = useState(0);
27
+ const [failed, setFailed] = useState<Record<number, boolean>>({});
28
+ const scroll = useRef<((index: number, y?: number) => void) | null>(null);
29
+ // oxlint-disable-next-line t3code/react-effect-budget -- Open and paint slides through a worker whose requests and lifetime belong to this presentation.
30
+ useEffect(() => {
31
+ const controller = new AbortController();
32
+ const worker = new Worker(new URL("./presentation.worker.ts", import.meta.url), {
33
+ type: "module",
34
+ });
35
+ const engine = createWorkerClient<SlideMethods>(worker);
36
+ const fail = (cause: unknown) => {
37
+ if (!controller.signal.aborted) onError(cause);
38
+ };
39
+ worker.addEventListener("error", fail);
40
+ worker.addEventListener("messageerror", fail);
41
+ const paint = async (
42
+ index: number,
43
+ canvas: HTMLCanvasElement,
44
+ scale: number,
45
+ signal: AbortSignal,
46
+ again = false,
47
+ ): Promise<void> => {
48
+ const result = await engine.call(
49
+ "paint",
50
+ { index, density: (window.devicePixelRatio || 1) * scale },
51
+ { key: `slide:${index}`, signal },
52
+ );
53
+ if (signal.aborted || result.kind === "cancelled") {
54
+ if (result.kind === "painted") result.bitmap.close();
55
+ return;
56
+ }
57
+ setFailed((previous) => ({ ...previous, [index]: result.kind === "failed" }));
58
+ if (result.kind === "failed") return;
59
+ const context = canvas.getContext("bitmaprenderer");
60
+ if (!context) {
61
+ result.bitmap.close();
62
+ throw new Error("This browser cannot draw slides.");
63
+ }
64
+ canvas.width = result.bitmap.width;
65
+ canvas.height = result.bitmap.height;
66
+ context.transferFromImageBitmap(result.bitmap);
67
+ if (again || !result.vectors.length) return;
68
+ const bitmaps = await Promise.all(result.vectors.map(rasterize));
69
+ if (signal.aborted) {
70
+ bitmaps.forEach((value) => value.bitmap?.close());
71
+ return;
72
+ }
73
+ await engine.call("vectors", bitmaps, {
74
+ transfer: bitmaps.flatMap((value) => (value.bitmap ? [value.bitmap] : [])),
75
+ signal,
76
+ });
77
+ if (!signal.aborted) await paint(index, canvas, scale, signal, true);
78
+ };
79
+ const bytes = source.slice(0);
80
+ void engine
81
+ .call("open", { bytes }, { transfer: [bytes], signal: controller.signal })
82
+ .then((slides) => {
83
+ if (slides.length === 0 || slides.length > 500)
84
+ throw new Error("Preview limited to presentations with 1 to 500 slides.");
85
+ setOpened({ slides, paint });
86
+ onDetails(`${slides.length} slides`);
87
+ })
88
+ .catch(fail);
89
+ return () => {
90
+ controller.abort();
91
+ engine.close();
92
+ };
93
+ }, [source, onDetails, onError]);
94
+ if (!opened) return <FileSurfaceLoading />;
95
+ const select = (index: number) => {
96
+ setPage(index);
97
+ scroll.current?.(index);
98
+ };
99
+ return (
100
+ <div className="flex min-h-0 flex-1 flex-col">
101
+ <div className={FILE_SURFACE_SUBHEADER_CLASS}>
102
+ <FileSurfaceAction
103
+ label="Previous slide"
104
+ disabled={page === 0}
105
+ onPress={() => select(page - 1)}
106
+ >
107
+ <ChevronLeftIcon className="size-3.5" />
108
+ </FileSurfaceAction>
109
+ <span className="flex-1 text-center text-xs tabular-nums" aria-live="polite">
110
+ Slide {page + 1} of {opened.slides.length}
111
+ </span>
112
+ <FileSurfaceAction
113
+ label="Next slide"
114
+ disabled={page + 1 === opened.slides.length}
115
+ onPress={() => select(page + 1)}
116
+ >
117
+ <ChevronRightIcon className="size-3.5" />
118
+ </FileSurfaceAction>
119
+ </div>
120
+ <OfficePages
121
+ pages={opened.slides}
122
+ paint={opened.paint}
123
+ label="Slide"
124
+ scrollRef={scroll}
125
+ onPageChange={setPage}
126
+ onError={onError}
127
+ overlay={(index) => (
128
+ <>
129
+ {opened.slides[index]?.hidden ? (
130
+ <div className="pointer-events-none absolute inset-0 bg-white/50" />
131
+ ) : null}
132
+ {failed[index] ? (
133
+ <p
134
+ role="status"
135
+ className="absolute inset-0 flex items-center justify-center bg-background/80 p-4 text-xs text-foreground"
136
+ >
137
+ This slide could not be drawn.
138
+ </p>
139
+ ) : null}
140
+ </>
141
+ )}
142
+ footer={(index) => {
143
+ const slide = opened.slides[index];
144
+ return slide?.notes || slide?.hidden ? (
145
+ <div className="space-y-1 text-xs text-muted-foreground">
146
+ {slide.hidden ? <p>Hidden slide</p> : null}
147
+ {slide.notes ? (
148
+ <p
149
+ role="note"
150
+ aria-label="Speaker notes"
151
+ className="select-text whitespace-pre-wrap break-words"
152
+ >
153
+ {slide.notes}
154
+ </p>
155
+ ) : null}
156
+ </div>
157
+ ) : null;
158
+ }}
159
+ />
160
+ </div>
161
+ );
162
+}
163
+async function rasterize(request: VectorRequest) {
164
+ const url = URL.createObjectURL(request.blob);
165
+ const image = new Image();
166
+ image.src = url;
167
+ try {
168
+ await image.decode();
169
+ const shrink = Math.min(1, maxImageSide / Math.max(image.naturalWidth, image.naturalHeight));
170
+ const size = request.size ?? {
171
+ width: Math.max(1, Math.round(image.naturalWidth * shrink)),
172
+ height: Math.max(1, Math.round(image.naturalHeight * shrink)),
173
+ };
174
+ return {
175
+ asset: request.asset,
176
+ bitmap: await createImageBitmap(image, {
177
+ resizeWidth: size.width,
178
+ resizeHeight: size.height,
179
+ resizeQuality: "high",
180
+ }),
181
+ };
182
+ } catch {
183
+ return { asset: request.asset, bitmap: undefined };
184
+ } finally {
185
+ URL.revokeObjectURL(url);
186
+ }
187
+}
apps/web/src/components/files/office/Spreadsheet.tsx
new
+588
@@ -0,0 +1,588 @@
1
+import { observeResize } from "~/lib/observeResize";
2
+import { useEffect, useRef, useState } from "react";
3
+import {
4
+ cellAtPoint,
5
+ normalizeRange,
6
+ selectionAt,
7
+ selectionKeyReducer,
8
+ extendTo,
9
+ hyperlinkAtCell,
10
+ safeExternalHyperlink,
11
+ parseHyperlinkLocation,
12
+ type Selection,
13
+ type CellAddr,
14
+} from "@betteroffice/xlsx/headless";
15
+import { FileSurfaceLoading, FileSurfaceNotice } from "../fileSurfaceChrome";
16
+import { createWorkerClient, SupersededError } from "./worker-rpc";
17
+import type { SheetLayout, SheetMethods, SheetFrameRequest, SheetTab } from "./sheet-protocol";
18
+import {
19
+ coverMerges,
20
+ contains,
21
+ lastCell,
22
+ settleMerges,
23
+ skipHidden,
24
+ columnName,
25
+} from "./sheet-cells";
26
+import {
27
+ paintCells,
28
+ paintHeaders,
29
+ paintSelection,
30
+ shiftGrid,
31
+ headerHeight,
32
+ type Painted,
33
+} from "./sheet-paint";
34
+import { externalUrl } from "./links";
35
+
36
+type Client = ReturnType<typeof createWorkerClient<SheetMethods>>;
37
+type Opened = {
38
+ engine: Client;
39
+ tabs: readonly SheetTab[];
40
+ layout: SheetLayout;
41
+ target?: CellAddr | undefined;
42
+};
43
+export default function Spreadsheet(props: {
44
+ bytes: ArrayBuffer;
45
+ onDetails: (text: string) => void;
46
+ onError: (cause: unknown) => void;
47
+}) {
48
+ const { onError, bytes: source, onDetails } = props;
49
+ const [opened, setOpened] = useState<Opened>();
50
+ const [error, setError] = useState("");
51
+ const picking = useRef<AbortController | null>(null);
52
+ // oxlint-disable-next-line t3code/react-effect-budget -- Open the workbook worker and cancel workbook and sheet requests when the source changes or unmounts.
53
+ useEffect(() => {
54
+ const controller = new AbortController();
55
+ const worker = new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), {
56
+ type: "module",
57
+ });
58
+ const engine = createWorkerClient<SheetMethods>(worker);
59
+ const fail = (cause: unknown) => {
60
+ if (!controller.signal.aborted) onError(cause);
61
+ };
62
+ worker.addEventListener("error", fail);
63
+ worker.addEventListener("messageerror", fail);
64
+ const bytes = source.slice(0);
65
+ void engine
66
+ .call("open", { bytes }, { transfer: [bytes], signal: controller.signal })
67
+ .then((value) => {
68
+ if (!value) throw new Error("This workbook has no visible sheets.");
69
+ setOpened({ ...value, engine });
70
+ onDetails(`${value.tabs.length} sheets`);
71
+ })
72
+ .catch(fail);
73
+ return () => {
74
+ controller.abort();
75
+ picking.current?.abort();
76
+ engine.close();
77
+ };
78
+ }, [source, onDetails, onError]);
79
+ const show = (sheet: number, target?: CellAddr) => {
80
+ if (!opened) return;
81
+ picking.current?.abort();
82
+ if (sheet === opened.layout.info.activeSheet) return;
83
+ const controller = new AbortController();
84
+ picking.current = controller;
85
+ void opened.engine
86
+ .call("show", { sheet }, { signal: controller.signal })
87
+ .then((layout) => {
88
+ setError("");
89
+ setOpened({ ...opened, layout, target });
90
+ })
91
+ .catch(() => {
92
+ if (!controller.signal.aborted) setError("This sheet could not be opened.");
93
+ });
94
+ };
95
+ if (!opened) return <FileSurfaceLoading />;
96
+ return (
97
+ <div className="flex min-h-0 flex-1 flex-col">
98
+ {error ? <FileSurfaceNotice>{error}</FileSurfaceNotice> : null}
99
+ <SpreadsheetGrid
100
+ key={opened.layout.info.activeSheet}
101
+ engine={opened.engine}
102
+ layout={opened.layout}
103
+ initialCell={opened.target}
104
+ onNavigate={(name, cell) => {
105
+ const tab = opened.tabs.find((tab) => tab.name.toLowerCase() === name.toLowerCase());
106
+ if (tab) show(tab.index, cell);
107
+ }}
108
+ />
109
+ <div
110
+ role="tablist"
111
+ aria-label="Sheets"
112
+ className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-t border-border px-2"
113
+ onKeyDown={(event) => {
114
+ const current = opened.tabs.findIndex(
115
+ (tab) => tab.index === opened.layout.info.activeSheet,
116
+ );
117
+ const next =
118
+ event.key === "ArrowRight"
119
+ ? (current + 1) % opened.tabs.length
120
+ : event.key === "ArrowLeft"
121
+ ? (current + opened.tabs.length - 1) % opened.tabs.length
122
+ : event.key === "Home"
123
+ ? 0
124
+ : event.key === "End"
125
+ ? opened.tabs.length - 1
126
+ : -1;
127
+ if (next < 0) return;
128
+ event.preventDefault();
129
+ const tab = opened.tabs[next];
130
+ if (tab) show(tab.index);
131
+ event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')[next]?.focus();
132
+ }}
133
+ >
134
+ {opened.tabs.map((tab) => (
135
+ <button
136
+ key={tab.index}
137
+ type="button"
138
+ role="tab"
139
+ aria-selected={tab.index === opened.layout.info.activeSheet}
140
+ tabIndex={tab.index === opened.layout.info.activeSheet ? 0 : -1}
141
+ onClick={() => show(tab.index)}
142
+ className="h-7 shrink-0 rounded-md px-2.5 text-xs text-muted-foreground hover:bg-accent aria-selected:bg-accent aria-selected:text-foreground"
143
+ >
144
+ {tab.name}
145
+ </button>
146
+ ))}
147
+ </div>
148
+ </div>
149
+ );
150
+}
151
+
152
+function SpreadsheetGrid(props: {
153
+ engine: Client;
154
+ layout: SheetLayout;
155
+ initialCell: CellAddr | undefined;
156
+ onNavigate: (sheet: string, cell: CellAddr) => void;
157
+}) {
158
+ const { onNavigate, layout, engine, initialCell } = props;
159
+ const scroller = useRef<HTMLDivElement>(null);
160
+ const canvas = useRef<HTMLCanvasElement>(null);
161
+ const spacer = useRef<HTMLDivElement>(null);
162
+ const [notice, setNotice] = useState("");
163
+ const [reader, setReader] = useState<{ row: number; col: number; text: string }[]>([]);
164
+ const [active, setActive] = useState({ row: 0, col: 0 });
165
+ const navigate = useRef(onNavigate);
166
+ // oxlint-disable-next-line t3code/react-effect-budget -- Keep the installed native pointer listener calling the latest navigation handler without restarting the canvas engine.
167
+ useEffect(() => {
168
+ navigate.current = onNavigate;
169
+ }, [onNavigate]);
170
+ // oxlint-disable-next-line t3code/react-effect-budget -- Own canvas painting, worker requests, resize observation, and native scroll, keyboard, and pointer listeners for this sheet.
171
+ useEffect(() => {
172
+ const root = scroller.current;
173
+ const target = canvas.current;
174
+ const space = spacer.current;
175
+ if (!root || !target || !space) return;
176
+ const context = target.getContext("2d");
177
+ if (!context) return;
178
+ const controller = new AbortController();
179
+ const info = layout.info;
180
+ const sheet = info.activeSheet;
181
+ const frozen = { rows: info.frozenRows, cols: info.frozenCols };
182
+ const headers = { width: 44, height: headerHeight };
183
+ let selection: Selection = selectionAt(initialCell ?? { row: 0, col: 0 });
184
+ let painted: Painted | undefined;
185
+ let grid: ReturnType<typeof shiftGrid> | undefined;
186
+ let raf = 0;
187
+ let requested = "";
188
+ let sent = 0;
189
+ let received = 0;
190
+ let drag = false;
191
+ let header: "row" | "column" | "all" | undefined;
192
+ let pressed: { row: number; col: number } | undefined;
193
+ let end: { x: number; y: number } | undefined;
194
+ let left = info.initialScrollX;
195
+ let top = info.initialScrollY;
196
+ let reachX = 0;
197
+ let reachY = 0;
198
+ let readController: AbortController | undefined;
199
+ const range = () => coverMerges(normalizeRange(selection), layout.merges);
200
+ const at = (cell: { row: number; col: number }) => {
201
+ const merge = layout.merges.find((item) => contains(item, cell));
202
+ return selectionAt(merge ? { row: merge.top, col: merge.left } : cell);
203
+ };
204
+ const schedule = () => {
205
+ if (raf || controller.signal.aborted) return;
206
+ raf = requestAnimationFrame(() => {
207
+ raf = 0;
208
+ paint();
209
+ });
210
+ };
211
+ const resizeArea = () => {
212
+ const width = Math.min(
213
+ (end?.x ?? Infinity) + (painted?.frame.frozen.width ?? 0),
214
+ Math.max(info.contentWidth, layout.chartWidth, reachX, left + root.clientWidth) +
215
+ root.clientWidth,
216
+ );
217
+ const height = Math.min(
218
+ (end?.y ?? Infinity) + (painted?.frame.frozen.height ?? 0),
219
+ Math.max(info.contentHeight, layout.chartHeight, reachY, top + root.clientHeight) +
220
+ root.clientHeight,
221
+ );
222
+ space.style.width = `${headers.width + width}px`;
223
+ space.style.height = `${headers.height + height}px`;
224
+ };
225
+ const paint = () => {
226
+ const ratio = window.devicePixelRatio || 1;
227
+ const width = root.clientWidth;
228
+ const height = root.clientHeight;
229
+ const size = { width: width - headers.width, height: height - headers.height };
230
+ if (size.width <= 0 || size.height <= 0) return;
231
+ left = root.scrollLeft;
232
+ top = root.scrollTop;
233
+ resizeArea();
234
+ const input: SheetFrameRequest = {
235
+ sheet,
236
+ x: left,
237
+ y: top,
238
+ ...size,
239
+ ratio,
240
+ offset: { x: 0, y: 0 },
241
+ wider: undefined,
242
+ };
243
+ const key = JSON.stringify(input);
244
+ if (key !== requested) {
245
+ requested = key;
246
+ sent += 1;
247
+ const order = sent;
248
+ void engine
249
+ .call("frame", input, { key: "frame", signal: controller.signal })
250
+ .then((reply) => {
251
+ if (order < received || controller.signal.aborted) {
252
+ reply?.bitmap.close();
253
+ return;
254
+ }
255
+ received = order;
256
+ if (!reply) {
257
+ setNotice("These cells could not be drawn. Try scrolling to another area.");
258
+ return;
259
+ }
260
+ setNotice("");
261
+ painted?.frame.bitmap.close();
262
+ painted = { request: input, frame: reply };
263
+ end = reply.end;
264
+ schedule();
265
+ })
266
+ .catch((cause: unknown) => {
267
+ if (!(cause instanceof SupersededError) && !controller.signal.aborted)
268
+ setNotice("These cells could not be drawn.");
269
+ });
270
+ }
271
+ if (
272
+ target.width !== Math.round(width * ratio) ||
273
+ target.height !== Math.round(height * ratio)
274
+ ) {
275
+ target.width = Math.round(width * ratio);
276
+ target.height = Math.round(height * ratio);
277
+ target.style.width = `${width}px`;
278
+ target.style.height = `${height}px`;
279
+ }
280
+ if (!painted) {
281
+ context.fillStyle = "#fff";
282
+ context.fillRect(0, 0, target.width, target.height);
283
+ return;
284
+ }
285
+ paintCells(context, painted, { ratio, headers, x: left, y: top, ...size });
286
+ grid =
287
+ painted.frame.grid &&
288
+ shiftGrid(painted.frame.grid, frozen, painted.frame.frozen, {
289
+ x: painted.frame.viewport.x - left,
290
+ y: painted.frame.viewport.y - top,
291
+ });
292
+ if (!grid) return;
293
+ const anchor = selection.anchor;
294
+ paintSelection(context, {
295
+ grid,
296
+ ratio,
297
+ headers,
298
+ ...size,
299
+ range: range(),
300
+ active: coverMerges(
301
+ { top: anchor.row, left: anchor.col, bottom: anchor.row, right: anchor.col },
302
+ layout.merges,
303
+ ),
304
+ });
305
+ paintHeaders(context, { grid, ratio, headers, width, height, selected: range() });
306
+ };
307
+ const read = () => {
308
+ const focus = selection.focus;
309
+ setActive(focus);
310
+ readController?.abort();
311
+ readController = new AbortController();
312
+ const top = Math.max(0, focus.row - 5);
313
+ const left = Math.max(0, focus.col - 3);
314
+ const range = {
315
+ top,
316
+ left,
317
+ bottom: Math.min(lastCell.row, top + 10),
318
+ right: Math.min(lastCell.col, left + 6),
319
+ };
320
+ void engine
321
+ .call("cells", { sheet, range }, { key: "reader", signal: readController.signal })
322
+ .then((rows) => {
323
+ if (!controller.signal.aborted)
324
+ setReader(
325
+ rows.flatMap((row, r) =>
326
+ row.map((text, c) => ({ row: top + r, col: left + c, text })),
327
+ ),
328
+ );
329
+ })
330
+ .catch(() => undefined);
331
+ };
332
+ const select = (next: Selection) => {
333
+ selection = next;
334
+ read();
335
+ schedule();
336
+ };
337
+ const reveal = () => {
338
+ const cell = selection.focus;
339
+ void engine
340
+ .call("position", { sheet, cell }, { key: "position", signal: controller.signal })
341
+ .then((position) => {
342
+ if (!position || controller.signal.aborted) return;
343
+ const panes = painted?.frame.frozen ?? { width: 0, height: 0 };
344
+ const place = (start: number, next: number, current: number, visible: number) =>
345
+ start < current ? start : next > current + visible ? next - visible : current;
346
+ const x =
347
+ cell.col < info.frozenCols
348
+ ? left
349
+ : place(
350
+ position.start.x,
351
+ position.next.x,
352
+ left,
353
+ root.clientWidth - headers.width - panes.width,
354
+ );
355
+ const y =
356
+ cell.row < info.frozenRows
357
+ ? top
358
+ : place(
359
+ position.start.y,
360
+ position.next.y,
361
+ top,
362
+ root.clientHeight - headers.height - panes.height,
363
+ );
364
+ reachX = Math.max(reachX, x + root.clientWidth);
365
+ reachY = Math.max(reachY, y + root.clientHeight);
366
+ resizeArea();
367
+ root.scrollTo({ left: Math.max(0, x), top: Math.max(0, y) });
368
+ schedule();
369
+ })
370
+ .catch(() => undefined);
371
+ };
372
+ const hit = (event: PointerEvent) => {
373
+ if (!grid) return;
374
+ const rect = target.getBoundingClientRect();
375
+ const x = event.clientX - rect.left - headers.width;
376
+ const y = event.clientY - rect.top - headers.height;
377
+ const frame = painted?.frame;
378
+ if (
379
+ frame &&
380
+ ((x >= frame.frozen.width && x < frame.frozen.width + frame.viewport.x - left) ||
381
+ (y >= frame.frozen.height && y < frame.frozen.height + frame.viewport.y - top))
382
+ )
383
+ return;
384
+ const cell = cellAtPoint(
385
+ grid,
386
+ Math.max(0, Math.min(x, root.clientWidth - headers.width - 1)),
387
+ Math.max(0, Math.min(y, root.clientHeight - headers.height - 1)),
388
+ );
389
+ return cell ? { cell, x, y } : undefined;
390
+ };
391
+ const pointerDown = (event: PointerEvent) => {
392
+ if (event.button !== 0) return;
393
+ const found = hit(event);
394
+ if (!found) return;
395
+ root.focus({ preventScroll: true });
396
+ root.setPointerCapture(event.pointerId);
397
+ drag = true;
398
+ header = found.x < 0 ? (found.y < 0 ? "all" : "row") : found.y < 0 ? "column" : undefined;
399
+ pressed = header ? undefined : found.cell;
400
+ if (found.x < 0 && found.y < 0)
401
+ select({ anchor: { row: lastCell.row, col: lastCell.col }, focus: { row: 0, col: 0 } });
402
+ else if (found.x < 0)
403
+ select({
404
+ anchor: { row: found.cell.row, col: lastCell.col },
405
+ focus: { row: found.cell.row, col: 0 },
406
+ });
407
+ else if (found.y < 0)
408
+ select({
409
+ anchor: { row: lastCell.row, col: found.cell.col },
410
+ focus: { row: 0, col: found.cell.col },
411
+ });
412
+ else select(event.shiftKey ? extendTo(selection, found.cell) : at(found.cell));
413
+ };
414
+ const pointerMove = (event: PointerEvent) => {
415
+ if (!drag) return;
416
+ const found = hit(event);
417
+ if (found && header !== "all")
418
+ select(
419
+ extendTo(selection, {
420
+ row: header === "column" ? 0 : found.cell.row,
421
+ col: header === "row" ? 0 : found.cell.col,
422
+ }),
423
+ );
424
+ };
425
+ const pointerUp = (event: PointerEvent) => {
426
+ drag = false;
427
+ const found = hit(event);
428
+ if (!found || !pressed || found.cell.row !== pressed.row || found.cell.col !== pressed.col)
429
+ return;
430
+ const cell = at(found.cell).anchor;
431
+ const list = painted?.frame;
432
+ if (!list) return;
433
+ const link = hyperlinkAtCell(
434
+ { width: 0, height: 0, commands: [], hyperlinks: [...list.hyperlinks] },
435
+ cell.row,
436
+ cell.col,
437
+ );
438
+ if (!link) return;
439
+ const url = safeExternalHyperlink(link);
440
+ const safe = url && externalUrl(url);
441
+ if (safe) {
442
+ window.open(safe, "_blank", "noopener,noreferrer");
443
+ return;
444
+ }
445
+ const internal =
446
+ link.location && parseHyperlinkLocation(link.location, info.sheetNames[sheet] ?? "");
447
+ if (!internal) return;
448
+ if (internal.sheetName.toLowerCase() !== (info.sheetNames[sheet] ?? "").toLowerCase())
449
+ navigate.current(internal.sheetName, { row: internal.row, col: internal.col });
450
+ else {
451
+ select(at({ row: internal.row, col: internal.col }));
452
+ reveal();
453
+ }
454
+ };
455
+ const copy = () => {
456
+ const used = layout.used;
457
+ const selected = range();
458
+ const clipped = {
459
+ ...selected,
460
+ bottom: Math.min(selected.bottom, Math.max(selected.top, used?.bottom ?? 0)),
461
+ right: Math.min(selected.right, Math.max(selected.left, used?.right ?? 0)),
462
+ };
463
+ if ((clipped.bottom - clipped.top + 1) * (clipped.right - clipped.left + 1) > 200_000) {
464
+ setNotice("Select fewer than 200,000 cells to copy.");
465
+ return;
466
+ }
467
+ void engine
468
+ .call("copy", { sheet, range: clipped }, { signal: controller.signal })
469
+ .then((text) => {
470
+ if (text === undefined) throw new Error("No cells");
471
+ return navigator.clipboard.writeText(text);
472
+ })
473
+ .catch(() => {
474
+ if (!controller.signal.aborted) setNotice("The selected cells could not be copied.");
475
+ });
476
+ };
477
+ const key = (event: KeyboardEvent) => {
478
+ const command = event.ctrlKey || event.metaKey;
479
+ if (command && event.key.toLowerCase() === "c") {
480
+ event.preventDefault();
481
+ copy();
482
+ return;
483
+ }
484
+ if (event.key === "Tab" || event.altKey || event.isComposing) return;
485
+ const action = selectionKeyReducer(selection, event, {
486
+ rows: Math.max((layout.used?.bottom ?? 0) + 1, selection.focus.row + 1),
487
+ cols: Math.max((layout.used?.right ?? 0) + 1, selection.focus.col + 1),
488
+ rowsPerPage: Math.max(1, Math.floor((root.clientHeight - headerHeight) / 20)),
489
+ });
490
+ if (action.type !== "move") return;
491
+ event.preventDefault();
492
+ select(
493
+ skipHidden(
494
+ selection.focus,
495
+ settleMerges(selection, action.selection, layout.merges),
496
+ layout.hidden,
497
+ ),
498
+ );
499
+ reveal();
500
+ };
501
+ const cancel = () => {
502
+ drag = false;
503
+ };
504
+ root.addEventListener("scroll", schedule);
505
+ root.addEventListener("keydown", key);
506
+ root.addEventListener("pointerdown", pointerDown);
507
+ root.addEventListener("pointermove", pointerMove);
508
+ root.addEventListener("pointerup", pointerUp);
509
+ root.addEventListener("pointercancel", cancel);
510
+ const unobserve = observeResize(root, schedule);
511
+ window.addEventListener("resize", schedule);
512
+ resizeArea();
513
+ root.scrollTo({ left, top });
514
+ if (initialCell) {
515
+ selection = at(initialCell);
516
+ reveal();
517
+ }
518
+ read();
519
+ schedule();
520
+ return () => {
521
+ controller.abort();
522
+ readController?.abort();
523
+ cancelAnimationFrame(raf);
524
+ unobserve();
525
+ window.removeEventListener("resize", schedule);
526
+ painted?.frame.bitmap.close();
527
+ root.removeEventListener("scroll", schedule);
528
+ root.removeEventListener("keydown", key);
529
+ root.removeEventListener("pointerdown", pointerDown);
530
+ root.removeEventListener("pointermove", pointerMove);
531
+ root.removeEventListener("pointerup", pointerUp);
532
+ root.removeEventListener("pointercancel", cancel);
533
+ };
534
+ }, [engine, layout, initialCell]);
535
+ return (
536
+ <div className="relative flex min-h-0 flex-1">
537
+ <div
538
+ ref={scroller}
539
+ dir="ltr"
540
+ tabIndex={0}
541
+ role="grid"
542
+ aria-label={layout.info.sheetNames[layout.info.activeSheet]}
543
+ aria-readonly="true"
544
+ aria-multiselectable="true"
545
+ aria-rowcount={lastCell.row + 1}
546
+ aria-colcount={lastCell.col + 1}
547
+ aria-activedescendant={`office-cell-${active.row}-${active.col}`}
548
+ className="relative min-h-0 min-w-0 flex-1 select-none overflow-auto bg-white outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
549
+ >
550
+ <div
551
+ ref={spacer}
552
+ aria-hidden="true"
553
+ className="pointer-events-none absolute left-0 top-0"
554
+ />
555
+ <div aria-hidden="true" className="sticky left-0 top-0 h-0 w-0">
556
+ <canvas ref={canvas} className="absolute left-0 top-0 block" />
557
+ </div>
558
+ <div className="sr-only">
559
+ {[...new Set(reader.map((cell) => cell.row))].map((row) => (
560
+ <div key={row} role="row" aria-rowindex={row + 1}>
561
+ {reader
562
+ .filter((cell) => cell.row === row)
563
+ .map((cell) => (
564
+ <span
565
+ key={cell.col}
566
+ role="gridcell"
567
+ id={`office-cell-${cell.row}-${cell.col}`}
568
+ aria-colindex={cell.col + 1}
569
+ aria-label={`${columnName(cell.col)}${cell.row + 1}`}
570
+ >
571
+ {cell.text}
572
+ </span>
573
+ ))}
574
+ </div>
575
+ ))}
576
+ </div>
577
+ </div>
578
+ {notice ? (
579
+ <div
580
+ role="status"
581
+ className="absolute inset-x-3 bottom-3 rounded-md bg-background p-2 text-xs text-foreground shadow-md"
582
+ >
583
+ {notice}
584
+ </div>
585
+ ) : null}
586
+ </div>
587
+ );
588
+}
apps/web/src/components/files/office/WordDocument.tsx
new
+184
@@ -0,0 +1,184 @@
1
+/* oxlint-disable react/no-array-index-key -- Text spans retain their order within an immutable page. */
2
+/* oxlint-disable react/no-unstable-nested-components -- These callbacks return overlays, and are invoked as render functions. */
3
+import { Tooltip, TooltipTrigger, TooltipPopup } from "~/components/ui/tooltip";
4
+import { Fragment, useEffect, useRef, useState } from "react";
5
+import { FileSurfaceLoading } from "../fileSurfaceChrome";
6
+import { OfficePages, type PaintPage } from "./OfficePages";
7
+import { createWorkerClient } from "./worker-rpc";
8
+import {
9
+ layerFont,
10
+ lineHeight,
11
+ type WordMethods,
12
+ type WordPageSize,
13
+ type WordSpan,
14
+ type WordLink,
15
+} from "./word-protocol";
16
+
17
+type Opened = {
18
+ pages: readonly WordPageSize[];
19
+ paint: PaintPage;
20
+ engine: ReturnType<typeof createWorkerClient<WordMethods>>;
21
+};
22
+
23
+export default function WordDocument(props: {
24
+ bytes: ArrayBuffer;
25
+ onDetails: (text: string) => void;
26
+ onError: (cause: unknown) => void;
27
+}) {
28
+ const { onError, bytes, onDetails } = props;
29
+ const [opened, setOpened] = useState<Opened>();
30
+ const scroll = useRef<((index: number, y?: number) => void) | null>(null);
31
+ // oxlint-disable-next-line t3code/react-effect-budget -- Own the document worker and cancel its layout and painting requests when the document changes or unmounts.
32
+ useEffect(() => {
33
+ const controller = new AbortController();
34
+ const worker = new Worker(new URL("./document.worker.ts", import.meta.url), { type: "module" });
35
+ const engine = createWorkerClient<WordMethods>(worker);
36
+ const fail = (error: unknown) => {
37
+ if (!controller.signal.aborted) onError(error);
38
+ };
39
+ worker.addEventListener("error", fail);
40
+ worker.addEventListener("messageerror", fail);
41
+ const buffer = bytes.slice(0);
42
+ const paint: PaintPage = async (index, canvas, scale, signal) => {
43
+ const bitmap = await engine.call(
44
+ "paint",
45
+ { index, scale, ratio: window.devicePixelRatio || 1 },
46
+ { key: `paint:${index}`, signal },
47
+ );
48
+ void engine
49
+ .call("build", { index: index + 1 }, { key: "build", signal })
50
+ .catch(() => undefined);
51
+ if (!bitmap) return;
52
+ const context = canvas.getContext("bitmaprenderer");
53
+ if (!context || signal.aborted) {
54
+ bitmap.close();
55
+ return;
56
+ }
57
+ canvas.width = bitmap.width;
58
+ canvas.height = bitmap.height;
59
+ context.transferFromImageBitmap(bitmap);
60
+ };
61
+ void engine
62
+ .call("open", { bytes: buffer }, { transfer: [buffer], signal: controller.signal })
63
+ .then(async (first) => {
64
+ if (controller.signal.aborted) return;
65
+ setOpened({ pages: first.pages, paint, engine });
66
+ onDetails(`${first.pages.length}${first.loading ? "+" : ""} pages`);
67
+ if (!first.loading) return;
68
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
69
+ while (!controller.signal.aborted) {
70
+ const step = await engine.call("layout", undefined, { signal: controller.signal });
71
+ if (!step.done) continue;
72
+ if (step.pages.length > 1000) throw new Error("Preview limited to 1,000 pages.");
73
+ setOpened({ pages: step.pages, paint, engine });
74
+ onDetails(`${step.pages.length} pages`);
75
+ break;
76
+ }
77
+ })
78
+ .catch(fail);
79
+ return () => {
80
+ controller.abort();
81
+ engine.close();
82
+ };
83
+ }, [bytes, onDetails, onError]);
84
+ if (!opened) return <FileSurfaceLoading />;
85
+ const follow = (link: WordLink) => {
86
+ if (link.kind === "external") {
87
+ window.open(link.url, "_blank", "noopener,noreferrer");
88
+ return;
89
+ }
90
+ void opened.engine
91
+ .call("bookmark", { name: link.bookmark })
92
+ .then((target) => {
93
+ if (target) scroll.current?.(target.index, target.y);
94
+ })
95
+ .catch(onError);
96
+ };
97
+ return (
98
+ <OfficePages
99
+ pages={opened.pages}
100
+ paint={opened.paint}
101
+ label="Page"
102
+ scrollRef={scroll}
103
+ onError={onError}
104
+ overlay={(index) => (
105
+ <WordTextLayer
106
+ engine={opened.engine}
107
+ index={index}
108
+ page={opened.pages[index]}
109
+ follow={follow}
110
+ />
111
+ )}
112
+ />
113
+ );
114
+}
115
+
116
+function WordTextLayer(props: {
117
+ engine: Opened["engine"];
118
+ index: number;
119
+ page: WordPageSize | undefined;
120
+ follow: (link: WordLink) => void;
121
+}) {
122
+ const { engine, index, page, follow } = props;
123
+ const [spans, setSpans] = useState<readonly WordSpan[]>([]);
124
+ // oxlint-disable-next-line t3code/react-effect-budget -- Request selectable text from the document worker and cancel the request when its page leaves the viewport.
125
+ useEffect(() => {
126
+ if (!page) return;
127
+ const controller = new AbortController();
128
+ void engine
129
+ .call("text", { index: index }, { signal: controller.signal })
130
+ .then(setSpans)
131
+ .catch(() => undefined);
132
+ return () => controller.abort();
133
+ }, [engine, index, page]);
134
+ return (
135
+ <div
136
+ className="absolute inset-0 select-text overflow-hidden whitespace-pre text-transparent selection:bg-primary/30 selection:text-transparent"
137
+ style={{ containerType: "inline-size", fontFamily: layerFont, fontSize: 0, lineHeight }}
138
+ >
139
+ {spans.map((span, index) => {
140
+ const text = (
141
+ <span
142
+ dir={span.dir}
143
+ role={span.link ? "link" : undefined}
144
+ tabIndex={span.link ? 0 : undefined}
145
+ aria-label={span.title}
146
+ className="absolute origin-top-left"
147
+ style={{
148
+ left: `${span.left * 100}%`,
149
+ top: `${span.top * 100}%`,
150
+ fontSize: `${span.size * 100}cqw`,
151
+ transform: span.transform,
152
+ cursor: span.link ? "pointer" : "text",
153
+ }}
154
+ onClick={(event) => {
155
+ if (span.link && event.button === 0 && (getSelection()?.isCollapsed ?? true))
156
+ follow(span.link);
157
+ }}
158
+ onKeyDown={(event) => {
159
+ if (span.link && event.key === "Enter") {
160
+ event.preventDefault();
161
+ follow(span.link);
162
+ }
163
+ }}
164
+ >
165
+ {span.text}
166
+ </span>
167
+ );
168
+ return (
169
+ <Fragment key={index}>
170
+ {span.title ? (
171
+ <Tooltip>
172
+ <TooltipTrigger render={text} />
173
+ <TooltipPopup>{span.title}</TooltipPopup>
174
+ </Tooltip>
175
+ ) : (
176
+ text
177
+ )}
178
+ {span.after === "br" ? <br /> : span.after === "tab" ? "\t" : null}
179
+ </Fragment>
180
+ );
181
+ })}
182
+ </div>
183
+ );
184
+}
apps/web/src/components/files/office/document.worker.ts
new
+377
@@ -0,0 +1,377 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import * as Schema from "effect/Schema";
3
+import {
4
+ buildResidentRegionLayoutRequest,
5
+ getLayoutKernelInputs,
6
+ workerLayoutComputation,
7
+} from "@betteroffice/docx/editor";
8
+import { createRustMeasureSource } from "@betteroffice/docx/layout";
9
+import {
10
+ applyFrameDelta,
11
+ decodeFrameDelta,
12
+ encodeDisplayListFrameExtras,
13
+ GlyphCache,
14
+ rasterizeDisplayPageToBackBuffer,
15
+ type DisplayPage,
16
+ type RetainedFrame,
17
+} from "@betteroffice/docx/layout/render";
18
+import {
19
+ createYrsPositionProjection,
20
+ createYrsSession,
21
+ type YrsPositionProjection,
22
+} from "@betteroffice/docx/yrs";
23
+import { wordFonts } from "./fonts";
24
+import { createBitmapImageResolver } from "./word-images";
25
+import { layerFont, type WordMethods, type WordPageSize, type WordSpan } from "./word-protocol";
26
+import { pageText, positionTarget, type TextMeasure } from "./word-text";
27
+import { serveWorker, Transfer } from "./worker-rpc";
28
+
29
+// One worker holds one open Word document: its engine session, fonts, layout, built pages and painting. The window
30
+// terminates the worker when the document closes, which is the only way the engine's memory is given back.
31
+
32
+const FontRequirements = Schema.fromJsonString(
33
+ Schema.Array(
34
+ Schema.Struct({
35
+ key: Schema.String,
36
+ family: Schema.String,
37
+ bold: Schema.Boolean,
38
+ italic: Schema.Boolean,
39
+ scripts: Schema.optional(
40
+ Schema.Array(Schema.Literals(["cjk-sc", "cjk-tc", "cjk-jp", "cjk-kr", "arabic", "hebrew"])),
41
+ ),
42
+ }),
43
+ ),
44
+);
45
+
46
+const decodeFontRequirements = Schema.decodeUnknownSync(FontRequirements);
47
+
48
+/** A prefix layout's reply marks itself provisional when the document goes on past it. */
49
+const decodeLayoutReply = Schema.decodeUnknownSync(
50
+ Schema.fromJsonString(Schema.Struct({ provisional: Schema.optional(Schema.Boolean) })),
51
+);
52
+
53
+/** Pages laid out and built before the first paint; later pages are built as they near the viewport. */
54
+const firstPages = 3;
55
+
56
+/** How long one layout step may hold back a paint that waits behind it, in milliseconds. */
57
+const stepBudget = 24;
58
+
59
+/**
60
+ * How many pages either side of the page painted last stay built. A built page holds about 5 MB in the engine and
61
+ * builds again in about 100 ms. This keeps every page near the viewport, which paints a viewport ahead in both
62
+ * directions, and lets a reader scroll back a few screens without waiting, while a long read holds at most 21 pages.
63
+ */
64
+const keptAround = 10;
65
+
66
+type Opened = Awaited<ReturnType<typeof open>>;
67
+
68
+/** A value built on first use. */
69
+type Lazy<T> = { value: T | undefined };
70
+
71
+/** The document this worker opened, once it has. */
72
+const opened: Lazy<Opened> = { value: undefined };
73
+
74
+serveWorker<WordMethods>({
75
+ open: async (input) => {
76
+ if (opened.value) throw new Error("The worker already holds a document");
77
+
78
+ const loaded = await open(new Uint8Array(input.bytes));
79
+
80
+ opened.value = loaded;
81
+
82
+ return { pages: loaded.pages().map(pageSize), loading: loaded.loading() };
83
+ },
84
+ layout: () => required().step(),
85
+ paint: async (input, signal) => {
86
+ const bitmap = await required().paint(input.index, input.scale, input.ratio, signal);
87
+
88
+ return bitmap ? new Transfer(bitmap, [bitmap]) : undefined;
89
+ },
90
+ build: (input) => {
91
+ required().built(input.index);
92
+
93
+ return undefined;
94
+ },
95
+ text: (input) => required().text(input.index),
96
+ bookmark: (input) => required().target(input.name),
97
+});
98
+
99
+function required() {
100
+ if (!opened.value) throw new Error("The worker holds no document");
101
+
102
+ return opened.value;
103
+}
104
+
105
+/** Opens the document and lays out its first pages; the rest lay out a `step` at a time. */
106
+async function open(bytes: Uint8Array) {
107
+ const session = await createYrsSession();
108
+ const document = session.openDocx(bytes, true, { mediaTokens: true }).document;
109
+ const settings = document.package.settings;
110
+
111
+ const measure = createRustMeasureSource({
112
+ engine: {
113
+ registerFont: (font) => session.registerFont(font),
114
+ registerSubstituteFont: (id, family) => session.registerSubstituteFont(id, family),
115
+ clearFonts: () => session.clearFonts(),
116
+ },
117
+ bundled: wordFonts(),
118
+ });
119
+
120
+ measure.setCompat(settings?.compatibilityFlags);
121
+
122
+ const request = buildResidentRegionLayoutRequest(document, 0, {
123
+ themeColors: Object.fromEntries(
124
+ Object.entries(document.package.theme?.colorScheme ?? {}).filter(
125
+ (entry): entry is [string, string] => entry[1] !== undefined,
126
+ ),
127
+ ),
128
+ defaultTabStopTwips: settings?.defaultTabStop ?? null,
129
+ numericIds: {},
130
+ mediaTokens: true,
131
+ });
132
+
133
+ const requirements = decodeFontRequirements(
134
+ session.layoutFontRequirementsJson(JSON.stringify(request)),
135
+ ).map(({ scripts, ...requirement }) => ({
136
+ ...requirement,
137
+ ...(scripts ? { scripts: [...scripts] } : {}),
138
+ }));
139
+
140
+ await measure.prepareFontRequirements(requirements);
141
+
142
+ const measurement = measure.measurementConfigForRequirements(requirements);
143
+
144
+ if (!measurement) throw new Error("The document's fonts could not be prepared");
145
+
146
+ const input = JSON.stringify({ ...request, measurement });
147
+
148
+ // Word shows resolved comments without the active highlight.
149
+ const resolvedCommentIds = (document.package.document.comments ?? [])
150
+ .filter(
151
+ (comment) =>
152
+ (comment.done || comment.status === "resolved") && comment.parentId === undefined,
153
+ )
154
+ .map((comment) => comment.id);
155
+
156
+ // The session keeps the layout it last ran and builds display frames from it: only the display extras go in, and a
157
+ // binary frame comes back with the window's pages built and every other page a placeholder carrying its geometry.
158
+ const display = (previous: RetainedFrame | null, reply: string) => {
159
+ const layout = workerLayoutComputation(reply).layout;
160
+
161
+ session.setDisplayWindow(0, firstPages);
162
+
163
+ const extras = encodeDisplayListFrameExtras({
164
+ measured: [],
165
+ options: {},
166
+ layout,
167
+ fontChains: measurement.fontChains,
168
+ ...(getLayoutKernelInputs(layout)?.headersFooters
169
+ ? { headersFooters: getLayoutKernelInputs(layout)!.headersFooters! }
170
+ : {}),
171
+ resolvedCommentIds,
172
+ });
173
+
174
+ return applyFrameDelta(
175
+ previous,
176
+ decodeFrameDelta(session.buildDisplayListFrame(extras, previous?.frameEpoch ?? 0)),
177
+ );
178
+ };
179
+
180
+ // Only as much of the body as fills the first pages; a long document goes on past it.
181
+ const prefix = session.layoutDocumentWithRegionsPrefixRetainedJson(input, firstPages);
182
+ const retained = { frame: display(null, prefix) };
183
+
184
+ if (retained.frame.displayList.pages.length === 0)
185
+ throw new Error("The document produced no pages");
186
+
187
+ // The region layout that finishes the document: begun on the first step, `cost` the running average milliseconds a
188
+ // body block takes.
189
+ const layout = { loading: decodeLayoutReply(prefix).provisional ?? false, begun: false, cost: 3 };
190
+
191
+ // Builds a page's content when it is needed and not built, the first time or again after `release`.
192
+ const built = (index: number) => {
193
+ const page = retained.frame.displayList.pages[index];
194
+
195
+ if (!page?.unbuilt) return page;
196
+
197
+ retained.frame = applyFrameDelta(
198
+ retained.frame,
199
+ decodeFrameDelta(session.buildDisplayPagesFrame([index], retained.frame.frameEpoch)),
200
+ );
201
+
202
+ return retained.frame.displayList.pages[index];
203
+ };
204
+
205
+ // Gives back the built pages far from the page about to paint, so a long read keeps only the pages around the
206
+ // viewport. A released page keeps its geometry and document positions, which bookmarks search, and builds again
207
+ // when it is needed.
208
+ const release = (painted: number) => {
209
+ // The engine releases pages of the whole document's layout only, and few pages show before it.
210
+ if (layout.loading) return;
211
+
212
+ const far = retained.frame.displayList.pages.flatMap((page, index) =>
213
+ !page.unbuilt && Math.abs(painted - index) > keptAround ? [index] : [],
214
+ );
215
+
216
+ if (far.length === 0) return;
217
+
218
+ const frame = session.releaseDisplayPagesFrame(far, retained.frame.frameEpoch);
219
+
220
+ // A superseded release changes nothing; the next one tries again.
221
+ if (frame) retained.frame = applyFrameDelta(retained.frame, decodeFrameDelta(frame));
222
+ };
223
+
224
+ // The whole document's layout replaces the prefix's frame.
225
+ const complete = (reply: string) => {
226
+ const before = retained.frame.displayList.pages;
227
+
228
+ retained.frame = display(retained.frame, reply);
229
+ layout.loading = false;
230
+
231
+ const pages = retained.frame.displayList.pages;
232
+
233
+ return {
234
+ done: true as const,
235
+ pages: pages.map(pageSize),
236
+ kept: pages.map((page, index) => {
237
+ const was = before[index];
238
+
239
+ return was === page || (!!was?.unbuilt && !!page.unbuilt);
240
+ }),
241
+ };
242
+ };
243
+
244
+ const glyphCache = new GlyphCache({
245
+ provider: (font, glyph) => session.outlineGlyphJson(font, glyph),
246
+ });
247
+ const images = createBitmapImageResolver((token) => session.mediaSource(token));
248
+ const surface = new OffscreenCanvas(1, 1);
249
+ const textMeasure = layerMeasure();
250
+ const texts = new WeakMap<DisplayPage, readonly WordSpan[]>();
251
+ // Built on the first followed bookmark: most documents are read without one.
252
+ const projection: Lazy<YrsPositionProjection | null> = { value: undefined };
253
+
254
+ return {
255
+ pages: () => retained.frame.displayList.pages,
256
+ loading: () => layout.loading,
257
+ built,
258
+ /**
259
+ * Lays out about `stepBudget` milliseconds more of the body. Blocks vary widely, and sizing a step by the last one
260
+ * alone overshoots after a run of cheap blocks.
261
+ */
262
+ step: () => {
263
+ if (!layout.loading) {
264
+ const pages = retained.frame.displayList.pages;
265
+
266
+ return { done: true as const, pages: pages.map(pageSize), kept: pages.map(() => true) };
267
+ }
268
+
269
+ if (!layout.begun) {
270
+ layout.begun = true;
271
+
272
+ const begun = session.beginRegionLayout(input);
273
+
274
+ return begun.layoutJson === undefined
275
+ ? { done: false as const }
276
+ : complete(begun.layoutJson);
277
+ }
278
+
279
+ const blocks = Math.min(8192, Math.max(1, Math.round(stepBudget / layout.cost)));
280
+ const started = performance.now();
281
+ const progress = session.resumeRegionLayout(blocks);
282
+
283
+ layout.cost = layout.cost * 0.7 + ((performance.now() - started) / blocks) * 0.3;
284
+
285
+ return progress.layoutJson === undefined
286
+ ? { done: false as const }
287
+ : complete(progress.layoutJson);
288
+ },
289
+ paint: async (index: number, scale: number, ratio: number, signal: AbortSignal) => {
290
+ // A page that scrolled away before its paint began, or while it rasterized, needs no bitmap.
291
+ if (signal.aborted) return undefined;
292
+
293
+ // Released first, so the page builds in the memory they free.
294
+ release(index);
295
+
296
+ const page = built(index);
297
+
298
+ if (!page) return undefined;
299
+
300
+ // The window drew image elements, which shrink smoothly at the default quality; a bitmap needs medium quality to
301
+ // look the same. Sizing the surface first keeps the setting: the painter resizes it, which resets the context,
302
+ // only when its size differs.
303
+ const context = surface.getContext("2d");
304
+ const width = Math.ceil(page.width * ratio * scale);
305
+ const height = Math.ceil(page.height * ratio * scale);
306
+
307
+ if (surface.width !== width) surface.width = width;
308
+
309
+ if (surface.height !== height) surface.height = height;
310
+
311
+ if (context) context.imageSmoothingQuality = "medium";
312
+
313
+ await rasterizeDisplayPageToBackBuffer(
314
+ surface,
315
+ page,
316
+ { glyphCache, resolveImage: images.resolve },
317
+ ratio,
318
+ scale,
319
+ );
320
+ images.trim();
321
+
322
+ if (signal.aborted) return undefined;
323
+
324
+ return surface.transferToImageBitmap();
325
+ },
326
+ text: (index: number) => {
327
+ const page = built(index);
328
+
329
+ if (!page || !textMeasure) return [];
330
+
331
+ const cached = texts.get(page);
332
+
333
+ if (cached) return cached;
334
+
335
+ const spans = pageText(page, textMeasure);
336
+
337
+ texts.set(page, spans);
338
+
339
+ return spans;
340
+ },
341
+ target: (name: string) => {
342
+ projection.value ??= createYrsPositionProjection(session, "body");
343
+
344
+ const position = projection.value?.bookmarkPosition(name) ?? undefined;
345
+
346
+ if (position !== undefined)
347
+ return positionTarget(retained.frame.displayList.pages, position, built);
348
+
349
+ // Word's reserved bookmark for the start of the document.
350
+ return name === "_top" ? { index: 0, y: 0 } : undefined;
351
+ },
352
+ };
353
+}
354
+
355
+function pageSize(page: DisplayPage): WordPageSize {
356
+ return { width: page.width, height: page.height, background: page.background };
357
+}
358
+
359
+/** Measures the text layer's font with a detached canvas; undefined where the worker offers no 2D context. */
360
+function layerMeasure(): TextMeasure | undefined {
361
+ const context = new OffscreenCanvas(1, 1).getContext("2d");
362
+
363
+ if (!context) return undefined;
364
+
365
+ // Measured large and scaled down, so rounding stays well below a pixel at any zoom.
366
+ const size = 100;
367
+
368
+ context.font = `${size}px ${layerFont}`;
369
+
370
+ const metrics = context.measureText("Hg");
371
+
372
+ return {
373
+ width: (text) => context.measureText(text).width / size,
374
+ ascent: metrics.fontBoundingBoxAscent / size,
375
+ descent: metrics.fontBoundingBoxDescent / size,
376
+ };
377
+}
apps/web/src/components/files/office/fonts-cjk.ts
new
+4
@@ -0,0 +1,4 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+// `@betteroffice/fonts` imports its optional Chinese, Japanese and Korean add-on on demand. The add-on is about 33 MB,
3
+// so the app aliases it to this module, which offers no faces: those scripts fall back to the bundled Latin faces.
4
+export const CJK_FONT_ASSET_URLS = undefined;
apps/web/src/components/files/office/fonts.ts
new
+85
@@ -0,0 +1,85 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import type { BundledFontProvider } from "@betteroffice/docx/layout";
3
+import {
4
+ loadBundledFontBytes,
5
+ resolveBundledFamilyFace,
6
+ resolveLastResortFace,
7
+ resolveMetricCompatFace,
8
+ resolveScriptFallbackFace,
9
+ type BundledFontFace,
10
+ type BundledFontScript,
11
+} from "@betteroffice/fonts";
12
+
13
+// Every face loads from the app's own files, so no font request leaves the machine. The Chinese, Japanese and Korean
14
+// faces are an add-on the app does not ship (see `fonts-cjk.ts`), yet the font package still maps East Asian families
15
+// such as Microsoft YaHei or Yu Gothic Medium to them, so every lookup passes through `shippedFace`.
16
+function shipped(script: BundledFontScript) {
17
+ return !script.startsWith("cjk-");
18
+}
19
+
20
+/** The faces Word substitutes for a document's fonts: metric-compatible ones first, then Word's own fallbacks. */
21
+export function wordFonts(): BundledFontProvider {
22
+ const loader = (face: BundledFontFace | undefined) => (face ? () => loadFace(face) : undefined);
23
+
24
+ return {
25
+ resolve: (family, bold, italic) =>
26
+ loader(shippedFace(resolveMetricCompatFace(family, bold, italic))),
27
+ resolveFamily: (family, bold, italic) =>
28
+ loader(shippedFace(resolveBundledFamilyFace(family, bold, italic))),
29
+ resolveScriptFallback: (script, bold, italic) => loader(scriptFace(script, bold, italic)),
30
+ resolveLastResort: (family, bold, italic) => () =>
31
+ loadFace(lastResortFace(family, bold, italic, "word")),
32
+ };
33
+}
34
+
35
+/** The face PowerPoint draws a family with: its metric-compatible or bundled face, else PowerPoint's substitute. */
36
+export function presentationFace(family: string, bold: boolean, italic: boolean): BundledFontFace {
37
+ return (
38
+ shippedFace(resolveMetricCompatFace(family, bold, italic)) ??
39
+ shippedFace(resolveBundledFamilyFace(family, bold, italic)) ??
40
+ lastResortFace(family, bold, italic, "powerpoint")
41
+ );
42
+}
43
+
44
+function shippedFace(face: BundledFontFace | undefined) {
45
+ return face && (!face.script || shipped(face.script)) ? face : undefined;
46
+}
47
+
48
+/**
49
+ * The substitute an application picks for a family it lacks. Only a weight variant of an East Asian family, such as
50
+ * Yu Mincho Light, resolves to a face the app does not ship; its name without the weight still tells serif from sans.
51
+ */
52
+function lastResortFace(
53
+ family: string,
54
+ bold: boolean,
55
+ italic: boolean,
56
+ office: "word" | "powerpoint",
57
+) {
58
+ const face = resolveLastResortFace(family, bold, italic, office);
59
+
60
+ if (shippedFace(face)) return face;
61
+
62
+ const base = family
63
+ .trim()
64
+ .split(/[\s-]+/)
65
+ .slice(0, -1)
66
+ .join(" ");
67
+
68
+ return (
69
+ shippedFace(resolveLastResortFace(base, bold, italic, office)) ??
70
+ resolveLastResortFace("", bold, italic, office)
71
+ );
72
+}
73
+
74
+/** The face that covers a script the Latin faces lack, or undefined when the app ships none. */
75
+export function scriptFace(script: BundledFontScript, bold: boolean, italic: boolean) {
76
+ return shipped(script) ? resolveScriptFallbackFace(script, bold, italic) : undefined;
77
+}
78
+
79
+/**
80
+ * A bundled face's bytes. The font package caches them per worker, so a face loads once per open file; the browser's
81
+ * caches, which every worker shares, serve the files to the next.
82
+ */
83
+export function loadFace(face: BundledFontFace) {
84
+ return loadBundledFontBytes(face);
85
+}
apps/web/src/components/files/office/image-bitmap.ts
new
+20
@@ -0,0 +1,20 @@
1
+import {
2
+ IMAGE_DIMENSIONS_HEADER_BYTES,
3
+ readImageDimensions,
4
+} from "@t3tools/shared/imageDimensions";
5
+
6
+export async function officeImageBitmap(blob: Blob) {
7
+ const bytes = new Uint8Array(await blob.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer());
8
+ let size = readImageDimensions(bytes);
9
+ if (!size && bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4d) {
10
+ const view = new DataView(bytes.buffer);
11
+ size =
12
+ view.getUint32(14, true) === 12
13
+ ? { width: view.getUint16(18, true), height: view.getUint16(20, true) }
14
+ : { width: view.getInt32(18, true), height: Math.abs(view.getInt32(22, true)) };
15
+ }
16
+ // Unknown dimensions cannot be decoded safely: compressed bytes do not bound pixel memory.
17
+ if (!size || size.width <= 0 || size.height <= 0 || size.width > 16_777_216 / size.height)
18
+ throw new Error("This embedded image exceeds the preview pixel limit.");
19
+ return createImageBitmap(blob);
20
+}
apps/web/src/components/files/office/links.ts
new
+24
@@ -0,0 +1,24 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import type { WordLink } from "./word-protocol";
3
+
4
+/** The schemes the host opens outside the app; it refuses any other, such as `javascript:`, `file:` or `tel:`. */
5
+const schemes = new Set(["http:", "https:", "mailto:"]);
6
+
7
+/** A document's link address, normalized, when the host may open it; undefined otherwise, so the link stays text. */
8
+export function externalUrl(href: string) {
9
+ const url = URL.parse(href);
10
+
11
+ return url && schemes.has(url.protocol) ? url.href : undefined;
12
+}
13
+
14
+/** Where a Word link leads, if it is one a reader may follow: a bookmark in the document, or an `externalUrl`. */
15
+export function wordLink(href: string | undefined): WordLink | undefined {
16
+ if (!href) return undefined;
17
+
18
+ if (href.startsWith("#"))
19
+ return href.length > 1 ? { kind: "internal", bookmark: href.slice(1) } : undefined;
20
+
21
+ const url = externalUrl(href);
22
+
23
+ return url ? { kind: "external", url } : undefined;
24
+}
apps/web/src/components/files/office/presentation.worker.ts
new
+428
@@ -0,0 +1,428 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import {
3
+ initWasm,
4
+ needsElementDecode,
5
+ openPresentation,
6
+ paintSlide,
7
+ presentationImageBlob,
8
+ type PresentationHandle,
9
+ type SlideDisplayList,
10
+ type SlidePrimitive,
11
+} from "@betteroffice/pptx";
12
+import { slideFonts } from "./slide-fonts";
13
+import {
14
+ maxImageSide,
15
+ type SlideMethods,
16
+ type SlidePainted,
17
+ type SlideSummary,
18
+ type VectorBitmap,
19
+ type VectorRequest,
20
+} from "./slide-protocol";
21
+import { deckText } from "./slide-text";
22
+import { officeImageBitmap } from "./image-bitmap";
23
+import { serveWorker, Transfer } from "./worker-rpc";
24
+
25
+// One worker holds one open PowerPoint deck: its engine, fonts, laid-out slides, decoded pictures and painting. The
26
+// window terminates the worker when the deck closes, which is the only way the engine's memory is given back.
27
+
28
+/** English Metric Units per CSS pixel. */
29
+const emuPerPixel = 9525;
30
+
31
+/** The most device pixels one slide's bitmap holds, about a 4K screen: a zoomed slide stays sharp up to it. */
32
+const maxBitmapPixels = 3840 * 2160;
33
+
34
+/** The longest side a canvas takes in every browser. */
35
+const maxBitmapSide = 16384;
36
+
37
+/**
38
+ * Shadow pixels a slide may blur, per pixel of its bitmap: sixteen slide-sized shadows before they are dropped. Past
39
+ * it a slide gives up its shadows within about half a second, rather than painting for many seconds.
40
+ */
41
+const shadowPixelsPerPixel = 16;
42
+
43
+/**
44
+ * How many bytes of decoded pictures stay for repaints; the least recently drawn go first past it. A deck of camera
45
+ * photos holds about 17 MB per picture, even scaled down to `maxImageSide`.
46
+ */
47
+const pictureBudget = 128 * 1024 * 1024;
48
+
49
+type Size = { readonly width: number; readonly height: number };
50
+
51
+/**
52
+ * A picture as the painter draws it: a bitmap, an SVG that the window rasterizes (a worker has no SVG decoder) with
53
+ * the bitmap it last returned, or nothing when the browser cannot decode it.
54
+ */
55
+type Picture =
56
+ | { readonly kind: "bitmap"; readonly bitmap: ImageBitmap; readonly size: Size }
57
+ | {
58
+ readonly kind: "vector";
59
+ readonly blob: Blob;
60
+ bitmap: ImageBitmap | undefined;
61
+ failed: boolean;
62
+ }
63
+ | { readonly kind: "missing" };
64
+
65
+type Deck = ReturnType<typeof createDeck>;
66
+
67
+/** The deck this worker opened, once it has. */
68
+type WorkerState = { deck: Deck | undefined };
69
+
70
+const state: WorkerState = { deck: undefined };
71
+
72
+serveWorker<SlideMethods>({
73
+ open: async (input) => {
74
+ if (state.deck) throw new Error("The worker already holds a deck");
75
+
76
+ await initWasm();
77
+
78
+ const bytes = new Uint8Array(input.bytes);
79
+ const handle = openPresentation(bytes);
80
+ const snapshot = handle.snapshot();
81
+ const text = deckText(bytes, snapshot);
82
+ const fonts = slideFonts(handle, workerFonts());
83
+
84
+ await fonts.load(text);
85
+
86
+ state.deck = createDeck(handle, fonts.layout);
87
+
88
+ const size = {
89
+ width: snapshot.widthEmu / emuPerPixel,
90
+ height: snapshot.heightEmu / emuPerPixel,
91
+ };
92
+
93
+ return snapshot.slides.map((slide, index): SlideSummary => ({
94
+ ...size,
95
+ hidden: text.hidden[index] ?? false,
96
+ notes: slide.notes?.trim() || undefined,
97
+ }));
98
+ },
99
+ paint: async (input, signal) => {
100
+ const deck = required();
101
+ const painted = await deck.paint(input.index, input.density, signal).finally(deck.trim);
102
+
103
+ return painted.kind === "painted" ? new Transfer(painted, [painted.bitmap]) : painted;
104
+ },
105
+ vectors: (input) => required().vectors(input),
106
+});
107
+
108
+function required() {
109
+ if (!state.deck) throw new Error("The worker holds no deck");
110
+
111
+ return state.deck;
112
+}
113
+
114
+/** The worker's own font set, which its canvases draw text with. */
115
+function workerFonts() {
116
+ if (!("fonts" in self)) throw new Error("This browser has no fonts in workers");
117
+
118
+ // SAFETY: a worker's global scope is a FontFaceSource, whose `fonts` is a FontFaceSet (CSS Font Loading, exposed to
119
+ // workers). The window's types declare it on documents only, and workers expose no FontFaceSet to check against.
120
+ return self.fonts as FontFaceSet;
121
+}
122
+
123
+function createDeck(
124
+ handle: PresentationHandle,
125
+ layout: (index: number) => Promise<SlideDisplayList>,
126
+) {
127
+ // A frame depends on the slide alone, so a new scale or pixel ratio paints the frame laid out before.
128
+ const frames = new Map<number, Promise<SlideDisplayList | undefined>>();
129
+ const pictures = new Map<string, Promise<Picture>>();
130
+ // The decoded bitmaps, least recently drawn first, which `trim` keeps within `pictureBudget`.
131
+ const drawn = new Map<string, ImageBitmap>();
132
+ const surface = new OffscreenCanvas(1, 1);
133
+
134
+ const frame = (index: number) => {
135
+ const cached = frames.get(index);
136
+
137
+ if (cached) return cached;
138
+
139
+ const laid = layout(index).catch(() => undefined);
140
+
141
+ frames.set(index, laid);
142
+
143
+ return laid;
144
+ };
145
+
146
+ const decode = async (asset: string): Promise<Picture> => {
147
+ const blob = presentationImageBlob(handle.mediaBytes(asset));
148
+
149
+ // SVG decodes through an image element, which a worker lacks.
150
+ if (needsElementDecode(blob)) return { kind: "vector", blob, bitmap: undefined, failed: false };
151
+
152
+ const source = await officeImageBitmap(blob).catch(() => undefined);
153
+
154
+ if (!source) return { kind: "missing" };
155
+ const size = { width: source.width, height: source.height };
156
+ return { kind: "bitmap", bitmap: await bounded(source), size };
157
+ };
158
+
159
+ const picture = (asset: string) => {
160
+ const cached = pictures.get(asset);
161
+
162
+ if (cached) return cached;
163
+
164
+ const decoded = decode(asset).catch((): Picture => ({ kind: "missing" }));
165
+
166
+ pictures.set(asset, decoded);
167
+
168
+ return decoded;
169
+ };
170
+
171
+ const tileScale = async (primitive: SlidePrimitive): Promise<SlidePrimitive> => {
172
+ if (primitive.kind === "table" || primitive.kind === "chart") {
173
+ const primitives: SlidePrimitive[] = [];
174
+ for (const child of primitive.primitives) primitives.push(await tileScale(child));
175
+ return { ...primitive, primitives };
176
+ }
177
+ if (primitive.kind !== "image" || !primitive.tile || !primitive.assetId) return primitive;
178
+ const found = await picture(primitive.assetId);
179
+ if (found.kind !== "bitmap") return primitive;
180
+ return {
181
+ ...primitive,
182
+ tile: {
183
+ ...primitive.tile,
184
+ scaleX: primitive.tile.scaleX * (found.size.width / found.bitmap.width),
185
+ scaleY: primitive.tile.scaleY * (found.size.height / found.bitmap.height),
186
+ },
187
+ };
188
+ };
189
+
190
+ return {
191
+ paint: async (index: number, density: number, signal: AbortSignal): Promise<SlidePainted> => {
192
+ const laid = await frame(index);
193
+
194
+ if (!laid) return { kind: "failed" };
195
+
196
+ if (signal.aborted) return { kind: "cancelled" };
197
+
198
+ const scale = Math.min(
199
+ density,
200
+ Math.sqrt(maxBitmapPixels / (laid.width * laid.height)),
201
+ maxBitmapSide / Math.max(laid.width, laid.height),
202
+ );
203
+
204
+ // One canvas paints every slide: a paint that was withdrawn leaves its pixels for the next to clear, rather than a
205
+ // slide-sized canvas each until the worker collects garbage. A reset context starts as a new canvas's does.
206
+ const canvas = surface;
207
+ const width = Math.max(1, Math.round(laid.width * scale));
208
+ const height = Math.max(1, Math.round(laid.height * scale));
209
+
210
+ if (canvas.width !== width) canvas.width = width;
211
+
212
+ if (canvas.height !== height) canvas.height = height;
213
+
214
+ const context = canvas.getContext("2d");
215
+
216
+ if (!context) return { kind: "failed" };
217
+
218
+ context.reset();
219
+
220
+ const needs = vectorSizes(laid.primitives, scale);
221
+ const wanted = new Map<string, VectorRequest>();
222
+
223
+ const resolveImage = async (asset: string) => {
224
+ // A paint that was withdrawn finishes without pictures, and its reply is dropped.
225
+ if (signal.aborted) return null;
226
+
227
+ const found = await picture(asset);
228
+
229
+ if (found.kind === "bitmap") {
230
+ drawn.delete(asset);
231
+ drawn.set(asset, found.bitmap);
232
+
233
+ return found.bitmap;
234
+ }
235
+
236
+ if (found.kind === "missing" || found.failed) return null;
237
+
238
+ const need = needs.get(asset);
239
+
240
+ if (!covers(found.bitmap, need)) wanted.set(asset, { asset, blob: found.blob, size: need });
241
+
242
+ if (found.bitmap) {
243
+ drawn.delete(asset);
244
+ drawn.set(asset, found.bitmap);
245
+ }
246
+
247
+ return found.bitmap ?? null;
248
+ };
249
+
250
+ const options = {
251
+ resolveImage,
252
+ maxShadowPixels: canvas.width * canvas.height * shadowPixelsPerPixel,
253
+ };
254
+
255
+ const attempt = (list: SlideDisplayList) =>
256
+ // SAFETY: the painter draws through the members a worker's 2D context shares with the window's, and makes its
257
+ // scratch canvases with OffscreenCanvas wherever it exists, as it does in a worker. Only the window's context
258
+ // type is declared, and it has two focus and attribute members the worker's lacks, hence the double cast.
259
+ paintSlide(context as unknown as CanvasRenderingContext2D, list, scale, 1, options).then(
260
+ () => true,
261
+ () => false,
262
+ );
263
+
264
+ const primitives: SlidePrimitive[] = [];
265
+ for (const primitive of laid.primitives) primitives.push(await tileScale(primitive));
266
+ const scaled = { ...laid, primitives };
267
+ const shadowed = await attempt(scaled);
268
+
269
+ // Past its shadow budget a slide throws, and paints again without shadows rather than not at all. It first lets
270
+ // through a cancellation that arrived meanwhile, such as a scroll that moved the slide away.
271
+ if (!shadowed) await new Promise((resolve) => setTimeout(resolve));
272
+
273
+ if (signal.aborted) return { kind: "cancelled" };
274
+
275
+ const done = shadowed || (await attempt(withoutShadows(scaled)));
276
+
277
+ if (!done) return { kind: "failed" };
278
+
279
+ if (signal.aborted) return { kind: "cancelled" };
280
+
281
+ return {
282
+ kind: "painted",
283
+ bitmap: canvas.transferToImageBitmap(),
284
+ vectors: [...wanted.values()],
285
+ };
286
+ },
287
+
288
+ /** Closes the least recently drawn pictures past the budget; they decode again when drawn. Call it between paints. */
289
+ trim: () => {
290
+ [...drawn].reduce(
291
+ (total, [asset, bitmap]) => {
292
+ if (total <= pictureBudget) return total;
293
+
294
+ const freed = pixelBytes(bitmap);
295
+
296
+ bitmap.close();
297
+ drawn.delete(asset);
298
+ pictures.delete(asset);
299
+
300
+ return total - freed;
301
+ },
302
+ [...drawn.values()].reduce((total, bitmap) => total + pixelBytes(bitmap), 0),
303
+ );
304
+ },
305
+
306
+ /**
307
+ * Keeps the window's rasterized SVG pictures in place of coarser ones. A finer one that a paint at a larger scale
308
+ * returned stays, and so does any one when the window could not rasterize the picture again.
309
+ */
310
+ vectors: (bitmaps: readonly VectorBitmap[]) =>
311
+ Promise.all(
312
+ bitmaps.map(async (entry) => {
313
+ const found = await picture(entry.asset);
314
+
315
+ if (found.kind !== "vector") return entry.bitmap?.close();
316
+
317
+ if (found.bitmap && (!entry.bitmap || covers(found.bitmap, entry.bitmap)))
318
+ return entry.bitmap?.close();
319
+
320
+ found.bitmap?.close();
321
+ drawn.delete(entry.asset);
322
+ found.bitmap = entry.bitmap;
323
+ found.failed = !entry.bitmap;
324
+ if (entry.bitmap) drawn.set(entry.asset, entry.bitmap);
325
+ }),
326
+ ).then(() => undefined),
327
+ };
328
+}
329
+
330
+/**
331
+ * The bitmap size each SVG picture on a slide needs at `scale`: its drawn size in device pixels, before cropping and
332
+ * up to `maxImageSide`. A tiled picture repeats at its own size, so it needs exactly that (undefined).
333
+ */
334
+function vectorSizes(primitives: readonly SlidePrimitive[], scale: number) {
335
+ const sizes = new Map<string, Size | undefined>();
336
+
337
+ const visit = (primitive: SlidePrimitive): void => {
338
+ if (primitive.kind === "table" || primitive.kind === "chart")
339
+ return primitive.primitives.forEach(visit);
340
+
341
+ if (primitive.kind !== "image" || !primitive.assetId) return;
342
+
343
+ const asset = primitive.assetId;
344
+ const previous = sizes.get(asset);
345
+
346
+ if (primitive.tile || (sizes.has(asset) && !previous)) return void sizes.set(asset, undefined);
347
+
348
+ const visibleX = 1 - fraction(primitive.crop?.left) - fraction(primitive.crop?.right);
349
+ const visibleY = 1 - fraction(primitive.crop?.top) - fraction(primitive.crop?.bottom);
350
+
351
+ if (visibleX <= 0 || visibleY <= 0) return;
352
+
353
+ const width = Math.max(previous?.width ?? 0, (primitive.w * scale) / visibleX);
354
+ const height = Math.max(previous?.height ?? 0, (primitive.h * scale) / visibleY);
355
+ const shrink = Math.min(1, maxImageSide / Math.max(width, height));
356
+
357
+ sizes.set(asset, {
358
+ width: Math.max(1, Math.ceil(width * shrink)),
359
+ height: Math.max(1, Math.ceil(height * shrink)),
360
+ });
361
+ };
362
+
363
+ primitives.forEach(visit);
364
+
365
+ return sizes;
366
+}
367
+
368
+function pixelBytes(bitmap: ImageBitmap) {
369
+ return bitmap.width * bitmap.height * 4;
370
+}
371
+
372
+/** Whether a rasterized SVG picture is as fine as `need`; undefined needs the picture's own size, rasterized once. */
373
+function covers(bitmap: ImageBitmap | undefined, need: Size | undefined) {
374
+ if (!bitmap) return false;
375
+
376
+ if (!need) return true;
377
+
378
+ return bitmap.width >= need.width && bitmap.height >= need.height;
379
+}
380
+
381
+/** A crop fraction as the painter reads it. */
382
+function fraction(value: number | undefined) {
383
+ return value === undefined || !Number.isFinite(value) ? 0 : Math.min(Math.max(value, 0), 1);
384
+}
385
+
386
+function withoutShadows(frame: SlideDisplayList): SlideDisplayList {
387
+ const strip = (primitive: SlidePrimitive): SlidePrimitive => {
388
+ if (primitive.kind === "shape" || primitive.kind === "image") {
389
+ const { shadow: _shadow, ...rest } = primitive;
390
+ return rest;
391
+ }
392
+
393
+ if (primitive.kind === "textBox") {
394
+ const { textShadow: _shadow, ...rest } = primitive;
395
+ return rest;
396
+ }
397
+
398
+ if (primitive.kind === "table" || primitive.kind === "chart")
399
+ return { ...primitive, primitives: primitive.primitives.map(strip) };
400
+
401
+ return primitive;
402
+ };
403
+
404
+ return { ...frame, primitives: frame.primitives.map(strip) };
405
+}
406
+
407
+/**
408
+ * The picture scaled down to `maxImageSide` when it is larger. Decks of camera photos would otherwise hold about 100 MB
409
+ * per decoded picture for as long as the deck is open.
410
+ */
411
+async function bounded(source: ImageBitmap) {
412
+ const shrink = maxImageSide / Math.max(source.width, source.height);
413
+
414
+ if (shrink >= 1) return source;
415
+
416
+ return createImageBitmap(source, {
417
+ resizeWidth: Math.max(1, Math.round(source.width * shrink)),
418
+ resizeHeight: Math.max(1, Math.round(source.height * shrink)),
419
+ resizeQuality: "high",
420
+ }).then(
421
+ (resized) => {
422
+ source.close();
423
+
424
+ return resized;
425
+ },
426
+ () => source,
427
+ );
428
+}
apps/web/src/components/files/office/sheet-cells.ts
new
+217
@@ -0,0 +1,217 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import type { XlsxAnchor } from "@betteroffice/xlsx";
3
+import {
4
+ selectionAt,
5
+ type CellAddr,
6
+ type CellRange,
7
+ type Selection,
8
+} from "@betteroffice/xlsx/headless";
9
+
10
+/** The sheet's last cell, zero-based: row 1,048,576 in column XFD. */
11
+export const lastCell = { row: 1048575, col: 16383 };
12
+
13
+/** A column's letters, such as "A", "Z" or "AA". */
14
+export function columnName(index: number): string {
15
+ return (
16
+ (index < 26 ? "" : columnName(Math.floor(index / 26) - 1)) +
17
+ String.fromCharCode(65 + (index % 26))
18
+ );
19
+}
20
+
21
+/** The cells an export anchor names: one range for a cell or range anchor, none for any other kind. */
22
+export function anchorRange(anchor: XlsxAnchor): CellRange[] {
23
+ if (anchor.kind !== "cell" && anchor.kind !== "range") return [];
24
+
25
+ const range = parseRange(anchor.a1);
26
+
27
+ return range ? [range] : [];
28
+}
29
+
30
+/** An A1 cell or range, such as "B2" or "A1:F20"; undefined for anything else. */
31
+export function parseRange(a1: string): CellRange | undefined {
32
+ // A lone cell is its own last corner; an empty one, as in "A1:", names no range.
33
+ const corners = a1.split(":");
34
+ const first = parseCell(corners[0] ?? "");
35
+ const last = corners.length === 1 ? first : parseCell(corners[1] ?? "");
36
+
37
+ if (!first || !last) return undefined;
38
+
39
+ return {
40
+ top: Math.min(first.row, last.row),
41
+ left: Math.min(first.col, last.col),
42
+ bottom: Math.max(first.row, last.row),
43
+ right: Math.max(first.col, last.col),
44
+ };
45
+}
46
+
47
+/** Grows a range until it covers every merged cell it touches, as Excel selects. */
48
+export function coverMerges(range: CellRange, merges: readonly CellRange[]): CellRange {
49
+ const grown = merges.reduce(
50
+ (current, merge) =>
51
+ overlaps(current, merge)
52
+ ? {
53
+ top: Math.min(current.top, merge.top),
54
+ left: Math.min(current.left, merge.left),
55
+ bottom: Math.max(current.bottom, merge.bottom),
56
+ right: Math.max(current.right, merge.right),
57
+ }
58
+ : current,
59
+ range,
60
+ );
61
+
62
+ // A merge the range grew into can touch another one it did not reach before.
63
+ if (same(grown, range)) return grown;
64
+
65
+ return coverMerges(grown, merges);
66
+}
67
+
68
+/**
69
+ * Moves a collapsed selection the way Excel moves its active cell around merged cells: landing in one selects its
70
+ * first cell, and a step that stays inside the merged cell it started from steps past it.
71
+ */
72
+export function settleMerges(
73
+ previous: Selection,
74
+ next: Selection,
75
+ merges: readonly CellRange[],
76
+): Selection {
77
+ if (!collapsed(next)) return next;
78
+
79
+ const merge = merges.find((candidate) => contains(candidate, next.focus));
80
+
81
+ if (!merge) return next;
82
+
83
+ if (!collapsed(previous) || !contains(merge, previous.focus))
84
+ return selectionAt({ row: merge.top, col: merge.left });
85
+
86
+ const cell = {
87
+ row: Math.min(
88
+ lastCell.row,
89
+ Math.max(0, past(previous.focus.row, next.focus.row, merge.top, merge.bottom)),
90
+ ),
91
+ col: Math.min(
92
+ lastCell.col,
93
+ Math.max(0, past(previous.focus.col, next.focus.col, merge.left, merge.right)),
94
+ ),
95
+ };
96
+
97
+ const landed = merges.find((candidate) => contains(candidate, cell));
98
+
99
+ return selectionAt(landed ? { row: landed.top, col: landed.left } : cell);
100
+}
101
+
102
+/** A run of hidden rows or columns, zero-based and inclusive. */
103
+export type Span = { readonly start: number; readonly end: number };
104
+
105
+/** Hidden row spans such as "5:7", or column spans such as "C:D", as the export lists them. */
106
+export function parseSpans(spans: readonly string[], axis: "rows" | "columns"): Span[] {
107
+ return spans.flatMap((span) => {
108
+ const [first = "", last = first] = span.split(":");
109
+ const start = axis === "rows" ? Number(first) - 1 : columnIndex(first);
110
+ const end = axis === "rows" ? Number(last) - 1 : columnIndex(last);
111
+
112
+ return Number.isInteger(start) && Number.isInteger(end) && start >= 0 && end >= start
113
+ ? [{ start, end }]
114
+ : [];
115
+ });
116
+}
117
+
118
+/**
119
+ * Moves a selection's focus off hidden rows and columns, on in the direction it moved, as Excel's arrow keys skip
120
+ * them. A move that would leave the sheet stays where it started.
121
+ */
122
+export function skipHidden(
123
+ from: CellAddr,
124
+ selection: Selection,
125
+ hidden: { readonly rows: readonly Span[]; readonly columns: readonly Span[] },
126
+): Selection {
127
+ const focus = {
128
+ row: clear(from.row, selection.focus.row, hidden.rows, lastCell.row),
129
+ col: clear(from.col, selection.focus.col, hidden.columns, lastCell.col),
130
+ };
131
+
132
+ if (focus.row === selection.focus.row && focus.col === selection.focus.col) return selection;
133
+
134
+ if (collapsed(selection)) return selectionAt(focus);
135
+
136
+ return { anchor: selection.anchor, focus };
137
+}
138
+
139
+/** Runs an engine call that throws on input it cannot take, such as a viewport with too many cells to draw. */
140
+export function attempt<T>(run: () => T): T | undefined {
141
+ try {
142
+ return run();
143
+ } catch {
144
+ return undefined;
145
+ }
146
+}
147
+
148
+/** Whether a range holds a cell. */
149
+export function contains(range: CellRange, cell: CellAddr) {
150
+ return (
151
+ cell.row >= range.top &&
152
+ cell.row <= range.bottom &&
153
+ cell.col >= range.left &&
154
+ cell.col <= range.right
155
+ );
156
+}
157
+
158
+function parseCell(a1: string): CellAddr | undefined {
159
+ const match = /^\$?([A-Z]{1,3})\$?([1-9]\d*)$/i.exec(a1);
160
+
161
+ if (!match) return undefined;
162
+
163
+ const col = columnIndex(match[1]!);
164
+ const row = Number(match[2]) - 1;
165
+
166
+ if (col > lastCell.col || row > lastCell.row) return undefined;
167
+
168
+ return { row, col };
169
+}
170
+
171
+/** A column's zero-based index from its letters; NaN for anything but one to three letters. */
172
+function columnIndex(letters: string) {
173
+ if (!/^[A-Z]{1,3}$/i.test(letters)) return Number.NaN;
174
+
175
+ return (
176
+ [...letters.toUpperCase()].reduce(
177
+ (total, letter) => total * 26 + letter.charCodeAt(0) - 64,
178
+ 0,
179
+ ) - 1
180
+ );
181
+}
182
+
183
+/** Where a move along one axis lands once past any hidden span it ended in. */
184
+function clear(from: number, to: number, spans: readonly Span[], last: number): number {
185
+ const span = spans.find((candidate) => to >= candidate.start && to <= candidate.end);
186
+
187
+ if (!span || to === from) return to;
188
+
189
+ const next = to > from ? span.end + 1 : span.start - 1;
190
+
191
+ if (next < 0 || next > last) return from;
192
+
193
+ return clear(from, next, spans, last);
194
+}
195
+
196
+/** One step along an axis: past the merge's far edge in the direction of the move, or where it was. */
197
+function past(from: number, to: number, low: number, high: number) {
198
+ if (to > from) return high + 1;
199
+
200
+ if (to < from) return low - 1;
201
+
202
+ return from;
203
+}
204
+
205
+function collapsed(selection: Selection) {
206
+ return (
207
+ selection.anchor.row === selection.focus.row && selection.anchor.col === selection.focus.col
208
+ );
209
+}
210
+
211
+function overlaps(a: CellRange, b: CellRange) {
212
+ return a.left <= b.right && a.right >= b.left && a.top <= b.bottom && a.bottom >= b.top;
213
+}
214
+
215
+function same(a: CellRange, b: CellRange) {
216
+ return a.top === b.top && a.left === b.left && a.bottom === b.bottom && a.right === b.right;
217
+}
apps/web/src/components/files/office/sheet-frame.ts
new
+215
@@ -0,0 +1,215 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import {
3
+ paintDisplayList,
4
+ type DisplayList,
5
+ type GridMeta,
6
+ type WorkbookHandle,
7
+} from "@betteroffice/xlsx";
8
+import { attempt } from "./sheet-cells";
9
+import { frozenSize } from "./sheet-paint";
10
+import type { SheetViewport } from "./sheet-protocol";
11
+
12
+// The workbook worker's frames: the display lists of one viewport, split into tiles where the engine refuses it whole,
13
+// and their painting.
14
+
15
+/** The most tiles a side of a frame splits into before the frame gives up. */
16
+const maxSplit = 8;
17
+
18
+/**
19
+ * How far a tile reaches past each of its seams, in CSS pixels. The engine draws pane dividers and cut tracks at a
20
+ * frame's edges, which the next tile has to cover, and the seam falls inside a device pixel.
21
+ */
22
+const seamOverlap = 8;
23
+
24
+/** Part of a frame: its display list, where its origin sits in the frame, and where it starts to show. */
25
+type Tile = {
26
+ readonly list: DisplayList;
27
+ readonly x: number;
28
+ readonly y: number;
29
+ readonly clipX: number;
30
+ readonly clipY: number;
31
+};
32
+
33
+/**
34
+ * A frame of cells: the tiles that draw it, one display list for its grid and links, without draw commands, and the
35
+ * viewport it shows.
36
+ */
37
+export type Frame = {
38
+ readonly list: DisplayList;
39
+ readonly tiles: readonly Tile[];
40
+ readonly viewport: SheetViewport;
41
+};
42
+
43
+/**
44
+ * The cells of one viewport, as the engine draws them; `undefined` when even its smallest tiles fail. A `wider`
45
+ * viewport around it is drawn instead when the engine takes it whole.
46
+ */
47
+export function drawFrame(
48
+ workbook: WorkbookHandle,
49
+ viewport: SheetViewport,
50
+ frozen: { readonly rows: number; readonly cols: number },
51
+ wider?: SheetViewport,
52
+): Frame | undefined {
53
+ const around = wider && attempt(() => workbook.displayList(wider));
54
+
55
+ if (wider && around)
56
+ return {
57
+ list: around,
58
+ tiles: [{ list: around, x: 0, y: 0, clipX: 0, clipY: 0 }],
59
+ viewport: wider,
60
+ };
61
+
62
+ const whole = attempt(() => workbook.displayList(viewport));
63
+
64
+ if (whole)
65
+ return { list: whole, tiles: [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }], viewport };
66
+
67
+ // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. One row and one column of
68
+ // the frame give its tracks, and so where its frozen panes end.
69
+ const columns = attempt(() => workbook.displayList({ ...viewport, height: 1 }).grid);
70
+ const rows = attempt(() => workbook.displayList({ ...viewport, width: 1 }).grid);
71
+
72
+ if (!columns || !rows) return undefined;
73
+
74
+ const grid = {
75
+ startRow: rows.startRow,
76
+ ...(rows.rowIndices ? { rowIndices: rows.rowIndices } : {}),
77
+ rowOffsets: rows.rowOffsets,
78
+ startCol: columns.startCol,
79
+ ...(columns.colIndices ? { colIndices: columns.colIndices } : {}),
80
+ colOffsets: columns.colOffsets,
81
+ };
82
+
83
+ return tiled(workbook, viewport, frozenSize(grid, frozen), grid, 2);
84
+}
85
+
86
+/**
87
+ * Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a
88
+ * tile covers the panes it repeats.
89
+ */
90
+export function paintFrame(
91
+ context: OffscreenCanvasRenderingContext2D,
92
+ frame: Frame,
93
+ input: { readonly ratio: number; readonly origin: { readonly x: number; readonly y: number } },
94
+) {
95
+ const ratio = input.ratio;
96
+ const origin = input.origin;
97
+ // SAFETY: the painter draws through the members a worker's 2D context shares with the window's. Only the window's
98
+ // context type is declared, and it has focus and attribute members the worker's lacks, hence the double cast.
99
+ const painter = context as unknown as CanvasRenderingContext2D;
100
+ const tiled = frame.tiles.length > 1;
101
+ const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined;
102
+ const textContext = text?.getContext("2d");
103
+
104
+ frame.tiles.forEach((tile) => {
105
+ const at = { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio };
106
+ const list = tiled
107
+ ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") }
108
+ : tile.list;
109
+
110
+ if (tile.clipX === 0 && tile.clipY === 0) return paintDisplayList(painter, list, ratio, at);
111
+
112
+ context.save();
113
+ context.setTransform(1, 0, 0, 1, 0, 0);
114
+ context.beginPath();
115
+ context.rect(
116
+ Math.round(origin.x + tile.clipX * ratio),
117
+ Math.round(origin.y + tile.clipY * ratio),
118
+ context.canvas.width,
119
+ context.canvas.height,
120
+ );
121
+ context.clip();
122
+ paintDisplayList(painter, list, ratio, at);
123
+ context.restore();
124
+ });
125
+ // Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds.
126
+ if (text && textContext)
127
+ frame.tiles.forEach((tile) => {
128
+ textContext.reset();
129
+ paintDisplayList(
130
+ textContext as unknown as CanvasRenderingContext2D,
131
+ {
132
+ ...tile.list,
133
+ width: frame.viewport.width - tile.x,
134
+ height: frame.viewport.height - tile.y,
135
+ commands: tile.list.commands.filter((command) => command.op === "text"),
136
+ },
137
+ ratio,
138
+ { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio },
139
+ );
140
+ context.save();
141
+ context.setTransform(1, 0, 0, 1, 0, 0);
142
+ context.beginPath();
143
+ context.rect(
144
+ Math.round(origin.x + tile.clipX * ratio),
145
+ Math.round(origin.y + tile.clipY * ratio),
146
+ context.canvas.width,
147
+ context.canvas.height,
148
+ );
149
+ context.clip();
150
+ context.drawImage(text, 0, 0);
151
+ context.restore();
152
+ });
153
+}
154
+
155
+/**
156
+ * A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for
157
+ * the frozen panes too, as every viewport has them, so the cells past them start just before its seam.
158
+ */
159
+function tiled(
160
+ workbook: WorkbookHandle,
161
+ viewport: SheetViewport,
162
+ panes: { readonly width: number; readonly height: number },
163
+ grid: GridMeta,
164
+ split: number,
165
+): Frame | undefined {
166
+ const columns = segments(viewport.width, panes.width, split);
167
+ const rows = segments(viewport.height, panes.height, split);
168
+ const tiles: Tile[] = [];
169
+
170
+ const complete = rows.every((row) =>
171
+ columns.every((column) => {
172
+ const x = column.start === 0 ? 0 : column.start - seamOverlap - panes.width;
173
+ const y = row.start === 0 ? 0 : row.start - seamOverlap - panes.height;
174
+ // A tile but the last along an axis reaches past its end, which the next tile paints over.
175
+ const right = column.end === viewport.width ? column.end : column.end + seamOverlap;
176
+ const bottom = row.end === viewport.height ? row.end : row.end + seamOverlap;
177
+
178
+ const list = attempt(() =>
179
+ workbook.displayList({
180
+ x: viewport.x + x,
181
+ y: viewport.y + y,
182
+ width: right - x,
183
+ height: bottom - y,
184
+ }),
185
+ );
186
+
187
+ if (list) tiles.push({ list, x, y, clipX: column.start, clipY: row.start });
188
+
189
+ return !!list;
190
+ }),
191
+ );
192
+
193
+ if (complete) {
194
+ const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []);
195
+
196
+ return {
197
+ list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks },
198
+ tiles,
199
+ viewport,
200
+ };
201
+ }
202
+
203
+ if (split >= maxSplit) return undefined;
204
+
205
+ return tiled(workbook, viewport, panes, grid, split + 1);
206
+}
207
+
208
+/** Even spans of a side, the first holding the frozen panes whole; a seam inside them is dropped. */
209
+function segments(size: number, panes: number, split: number) {
210
+ const starts = Array.from({ length: split }, (_, part) =>
211
+ Math.round((part * size) / split),
212
+ ).filter((start, part) => part === 0 || (start >= panes + seamOverlap && start < size));
213
+
214
+ return starts.map((start, part) => ({ start, end: starts[part + 1] ?? size }));
215
+}
apps/web/src/components/files/office/sheet-paint.ts
new
+396
@@ -0,0 +1,396 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import { rangeRect, type CellRange, type GridMeta } from "@betteroffice/xlsx/headless";
3
+import { columnName } from "./sheet-cells";
4
+import type { SheetFrame, SheetFrameRequest } from "./sheet-protocol";
5
+
6
+/** Excel's light headers and green selection. The sheet keeps them on its white paper in every theme. */
7
+const colours = {
8
+ header: "#f5f5f5",
9
+ label: "#5c5c5c",
10
+ line: "#d4d4d4",
11
+ edge: "#bdbdbd",
12
+ corner: "#c8c8c8",
13
+ selectedHeader: "#d3ecdd",
14
+ selectedLabel: "#185c37",
15
+ accent: "#217346",
16
+ selection: "rgba(33, 115, 70, 0.12)",
17
+};
18
+
19
+const font = "11px ui-sans-serif, system-ui, sans-serif";
20
+
21
+/** The height of the column headers, in CSS pixels. */
22
+export const headerHeight = 20;
23
+
24
+/** The sizes of the header strips, in CSS pixels: the row headers' width and the column headers' height. */
25
+export type Headers = { readonly width: number; readonly height: number };
26
+
27
+/**
28
+ * The frozen panes' size in a frame: the offset of the first track past them. Without panes, the first track can start
29
+ * before the frame, part of it scrolled away.
30
+ */
31
+export function frozenSize(
32
+ grid: GridMeta | undefined,
33
+ frozen: { readonly rows: number; readonly cols: number },
34
+) {
35
+ if (!grid) return { width: 0, height: 0 };
36
+
37
+ const pane = (
38
+ offsets: readonly number[],
39
+ start: number,
40
+ indices: readonly number[] | undefined,
41
+ count: number,
42
+ ) => {
43
+ if (count === 0) return 0;
44
+
45
+ const first = offsets.findIndex(
46
+ (_, position) =>
47
+ position === offsets.length - 1 || trackIndex(start, indices, position) >= count,
48
+ );
49
+
50
+ return Math.max(0, offsets[first] ?? 0);
51
+ };
52
+
53
+ return {
54
+ width: pane(grid.colOffsets, grid.startCol, grid.colIndices, frozen.cols),
55
+ height: pane(grid.rowOffsets, grid.startRow, grid.rowIndices, frozen.rows),
56
+ };
57
+}
58
+
59
+/** A frame from the workbook worker and the request it answers, which says where its cells sit. */
60
+export type Painted = { readonly request: SheetFrameRequest; readonly frame: SheetFrame };
61
+
62
+/**
63
+ * Draws a frame's cells beside the headers at the current scroll position. A frame painted at another position, as one
64
+ * is while the next renders, moves with the scroll: the frozen panes stay put and the cells past them shift, leaving
65
+ * the paper where the frame has no cells yet.
66
+ */
67
+export function paintCells(
68
+ context: CanvasRenderingContext2D,
69
+ painted: Painted,
70
+ input: {
71
+ readonly ratio: number;
72
+ readonly headers: Headers;
73
+ readonly x: number;
74
+ readonly y: number;
75
+ readonly width: number;
76
+ readonly height: number;
77
+ },
78
+) {
79
+ const request = painted.request;
80
+ const bitmap = painted.frame.bitmap;
81
+ const panes = painted.frame.frozen;
82
+ const ratio = input.ratio;
83
+ const scale = ratio / request.ratio;
84
+ const origin = { x: input.headers.width * ratio, y: input.headers.height * ratio };
85
+
86
+ // Each side splits at the frozen panes: the panes stay put, the cells past them follow the scroll.
87
+ const columns = [
88
+ { start: 0, end: Math.min(panes.width, input.width), shift: 0 },
89
+ { start: panes.width, end: input.width, shift: painted.frame.viewport.x - input.x },
90
+ ];
91
+
92
+ const rows = [
93
+ { start: 0, end: Math.min(panes.height, input.height), shift: 0 },
94
+ { start: panes.height, end: input.height, shift: painted.frame.viewport.y - input.y },
95
+ ];
96
+
97
+ // The whole canvas clears, headers included: their edges cover part of a device pixel, which would darken with every
98
+ // paint drawn over the last.
99
+ context.save();
100
+ context.setTransform(1, 0, 0, 1, 0, 0);
101
+ context.clearRect(0, 0, context.canvas.width, context.canvas.height);
102
+
103
+ rows.forEach((row) =>
104
+ columns.forEach((column) => {
105
+ if (row.end <= row.start || column.end <= column.start) return;
106
+
107
+ const left = Math.round(origin.x + column.start * ratio);
108
+ const top = Math.round(origin.y + row.start * ratio);
109
+
110
+ context.save();
111
+ context.beginPath();
112
+ context.rect(
113
+ left,
114
+ top,
115
+ Math.round(origin.x + column.end * ratio) - left,
116
+ Math.round(origin.y + row.end * ratio) - top,
117
+ );
118
+ context.clip();
119
+ // Whole device pixels, so a frame at its own position lands exactly where the worker painted its cells.
120
+ context.drawImage(
121
+ bitmap,
122
+ Math.round(origin.x + column.shift * ratio - request.offset.x * scale),
123
+ Math.round(origin.y + row.shift * ratio - request.offset.y * scale),
124
+ bitmap.width * scale,
125
+ bitmap.height * scale,
126
+ );
127
+ context.restore();
128
+ }),
129
+ );
130
+
131
+ context.restore();
132
+}
133
+
134
+/**
135
+ * A frame's grid at another scroll position, moved as `paintCells` moves its cells: the tracks past the frozen panes
136
+ * shift by `shift`, and never under the panes, so headers, selection and hit tests follow the cells on screen.
137
+ */
138
+export function shiftGrid(
139
+ grid: GridMeta,
140
+ frozen: { readonly rows: number; readonly cols: number },
141
+ panes: { readonly width: number; readonly height: number },
142
+ shift: { readonly x: number; readonly y: number },
143
+): GridMeta {
144
+ if (shift.x === 0 && shift.y === 0) return grid;
145
+
146
+ const axis = (
147
+ offsets: readonly number[],
148
+ start: number,
149
+ indices: readonly number[] | undefined,
150
+ count: number,
151
+ edge: number,
152
+ by: number,
153
+ ) => {
154
+ // The offsets up to the panes' far edge belong to the panes; without panes, every track moves.
155
+ const fixed =
156
+ count === 0
157
+ ? -1
158
+ : offsets.findIndex((_, position) => trackIndex(start, indices, position) >= count);
159
+
160
+ return offsets.map((offset, position) => {
161
+ if (fixed === -1 && count > 0) return offset;
162
+
163
+ if (position <= fixed) return offset;
164
+
165
+ return count === 0 ? offset + by : Math.max(edge, offset + by);
166
+ });
167
+ };
168
+
169
+ return {
170
+ ...grid,
171
+ colOffsets: axis(
172
+ grid.colOffsets,
173
+ grid.startCol,
174
+ grid.colIndices,
175
+ frozen.cols,
176
+ panes.width,
177
+ shift.x,
178
+ ),
179
+ rowOffsets: axis(
180
+ grid.rowOffsets,
181
+ grid.startRow,
182
+ grid.rowIndices,
183
+ frozen.rows,
184
+ panes.height,
185
+ shift.y,
186
+ ),
187
+ };
188
+}
189
+
190
+/** The sheet row or column at a position in a frame's grid: its indices when tracks are skipped, else consecutive. */
191
+function trackIndex(start: number, indices: readonly number[] | undefined, position: number) {
192
+ return indices?.[position] ?? start + position;
193
+}
194
+
195
+/**
196
+ * Draws the column letters and row numbers of a frame's tracks, frozen panes first, along the top and left edges.
197
+ * Hidden tracks have no width in the grid, so they get no header.
198
+ */
199
+export function paintHeaders(
200
+ context: CanvasRenderingContext2D,
201
+ input: {
202
+ readonly grid: GridMeta;
203
+ readonly ratio: number;
204
+ readonly headers: Headers;
205
+ readonly width: number;
206
+ readonly height: number;
207
+ readonly selected: CellRange | undefined;
208
+ },
209
+) {
210
+ const grid = input.grid;
211
+ const headers = input.headers;
212
+ const selected = input.selected;
213
+
214
+ context.save();
215
+ context.setTransform(input.ratio, 0, 0, input.ratio, 0, 0);
216
+ context.fillStyle = colours.header;
217
+ context.fillRect(0, 0, input.width, headers.height);
218
+ context.fillRect(0, 0, headers.width, input.height);
219
+ context.font = font;
220
+ context.textAlign = "center";
221
+ context.textBaseline = "middle";
222
+
223
+ grid.colOffsets.slice(0, -1).forEach((offset, position) => {
224
+ const index = trackIndex(grid.startCol, grid.colIndices, position);
225
+
226
+ paintHeader(context, {
227
+ x: headers.width + offset,
228
+ y: 0,
229
+ width: grid.colOffsets[position + 1]! - offset,
230
+ height: headers.height,
231
+ label: columnName(index),
232
+ selected: !!selected && index >= selected.left && index <= selected.right,
233
+ clip: { x: headers.width, width: input.width - headers.width },
234
+ });
235
+ });
236
+ grid.rowOffsets.slice(0, -1).forEach((offset, position) => {
237
+ const index = trackIndex(grid.startRow, grid.rowIndices, position);
238
+
239
+ paintHeader(context, {
240
+ x: 0,
241
+ y: headers.height + offset,
242
+ width: headers.width,
243
+ height: grid.rowOffsets[position + 1]! - offset,
244
+ label: String(index + 1),
245
+ selected: !!selected && index >= selected.top && index <= selected.bottom,
246
+ clip: { y: headers.height, height: input.height - headers.height },
247
+ });
248
+ });
249
+
250
+ line(context, colours.edge, 0, headers.height, input.width, headers.height);
251
+ line(context, colours.edge, headers.width, 0, headers.width, input.height);
252
+ // Excel's select-all corner: a small triangle pointing at the cells.
253
+ context.fillStyle = colours.corner;
254
+ context.beginPath();
255
+ context.moveTo(headers.width - 4, headers.height - 12);
256
+ context.lineTo(headers.width - 4, headers.height - 4);
257
+ context.lineTo(headers.width - 12, headers.height - 4);
258
+ context.closePath();
259
+ context.fill();
260
+ context.restore();
261
+}
262
+
263
+/** Outlines the selected range and tints it, leaving its active cell clear, in the cells beside the headers. */
264
+export function paintSelection(
265
+ context: CanvasRenderingContext2D,
266
+ input: {
267
+ readonly grid: GridMeta;
268
+ readonly ratio: number;
269
+ readonly headers: Headers;
270
+ readonly width: number;
271
+ readonly height: number;
272
+ readonly range: CellRange;
273
+ readonly active: CellRange;
274
+ },
275
+) {
276
+ const range = rangeRect(input.grid, input.range);
277
+
278
+ if (!range) return;
279
+
280
+ const active = rangeRect(input.grid, input.active);
281
+
282
+ context.save();
283
+ context.setTransform(
284
+ input.ratio,
285
+ 0,
286
+ 0,
287
+ input.ratio,
288
+ input.headers.width * input.ratio,
289
+ input.headers.height * input.ratio,
290
+ );
291
+ context.beginPath();
292
+ context.rect(0, 0, input.width, input.height);
293
+ context.clip();
294
+
295
+ if (!sameRect(range, active)) {
296
+ context.beginPath();
297
+ context.rect(range.x, range.y, range.w, range.h);
298
+
299
+ if (active) context.rect(active.x, active.y, active.w, active.h);
300
+
301
+ context.fillStyle = colours.selection;
302
+ context.fill("evenodd");
303
+ }
304
+
305
+ context.strokeStyle = colours.accent;
306
+ context.lineWidth = 2;
307
+ context.strokeRect(range.x, range.y, range.w, range.h);
308
+ context.restore();
309
+}
310
+
311
+function paintHeader(
312
+ context: CanvasRenderingContext2D,
313
+ header: {
314
+ readonly x: number;
315
+ readonly y: number;
316
+ readonly width: number;
317
+ readonly height: number;
318
+ readonly label: string;
319
+ readonly selected: boolean;
320
+ readonly clip: {
321
+ readonly x?: number;
322
+ readonly y?: number;
323
+ readonly width?: number;
324
+ readonly height?: number;
325
+ };
326
+ },
327
+) {
328
+ if (header.width <= 0 || header.height <= 0) return;
329
+
330
+ const columns = header.y === 0;
331
+
332
+ context.save();
333
+ context.beginPath();
334
+ context.rect(
335
+ header.clip.x ?? header.x,
336
+ header.clip.y ?? header.y,
337
+ header.clip.width ?? header.width,
338
+ header.clip.height ?? header.height,
339
+ );
340
+ context.clip();
341
+
342
+ // A selected header is tinted, with a bar on the edge that meets the cells.
343
+ if (header.selected) {
344
+ context.fillStyle = colours.selectedHeader;
345
+ context.fillRect(header.x, header.y, header.width, header.height);
346
+ context.fillStyle = colours.accent;
347
+ context.fillRect(
348
+ columns ? header.x : header.x + header.width - 2,
349
+ columns ? header.y + header.height - 2 : header.y,
350
+ columns ? header.width : 2,
351
+ columns ? 2 : header.height,
352
+ );
353
+ }
354
+
355
+ // A track too small for its label shows none, rather than labels piled over each other.
356
+ if (columns ? context.measureText(header.label).width + 2 <= header.width : header.height >= 9) {
357
+ context.fillStyle = header.selected ? colours.selectedLabel : colours.label;
358
+ context.fillText(header.label, header.x + header.width / 2, header.y + header.height / 2 + 0.5);
359
+ }
360
+
361
+ context.restore();
362
+
363
+ // The line after the header, where the gridline between its cells and the next ones meets it.
364
+ const x = columns ? header.x + header.width : header.x;
365
+ const y = columns ? header.y : header.y + header.height;
366
+
367
+ line(
368
+ context,
369
+ colours.line,
370
+ x,
371
+ y,
372
+ columns ? x : x + header.width,
373
+ columns ? y + header.height : y,
374
+ );
375
+}
376
+
377
+/** A one-pixel line centred on its coordinates, as the display list draws gridlines, so the two meet. */
378
+function line(
379
+ context: CanvasRenderingContext2D,
380
+ colour: string,
381
+ x1: number,
382
+ y1: number,
383
+ x2: number,
384
+ y2: number,
385
+) {
386
+ context.strokeStyle = colour;
387
+ context.lineWidth = 1;
388
+ context.beginPath();
389
+ context.moveTo(x1, y1);
390
+ context.lineTo(x2, y2);
391
+ context.stroke();
392
+}
393
+
394
+function sameRect(a: { x: number; y: number; w: number; h: number }, b: typeof a | null) {
395
+ return !!b && a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;
396
+}
apps/web/src/components/files/office/sheet-protocol.ts
new
+93
@@ -0,0 +1,93 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import type { SheetInfo } from "@betteroffice/xlsx";
3
+import type { CellAddr, CellRange, GridMeta, HyperlinkRegion } from "@betteroffice/xlsx/headless";
4
+import type { Span } from "./sheet-cells";
5
+import type { Method } from "./worker-rpc";
6
+
7
+// What the Excel preview's window and its workbook worker say to each other. The window keeps the selection, the
8
+// headers and the scroll area; the engine, its recalculation, the display lists and the cells' painting live in the
9
+// worker.
10
+
11
+/** A visible sheet: its index in the workbook and its tab name. */
12
+export type SheetTab = { readonly index: number; readonly name: string };
13
+
14
+/** What a sheet's grid needs from the workbook before its first frame. */
15
+export type SheetLayout = {
16
+ readonly info: SheetInfo;
17
+ /** The used range; undefined for an empty sheet. */
18
+ readonly used: CellRange | undefined;
19
+ readonly merges: readonly CellRange[];
20
+ readonly hidden: { readonly rows: readonly Span[]; readonly columns: readonly Span[] };
21
+ /** How far the charts reach, in the engine's scroll coordinates. */
22
+ readonly chartWidth: number;
23
+ readonly chartHeight: number;
24
+};
25
+
26
+/** A viewport, in CSS pixels and the engine's scroll coordinates: the frozen panes, then the cells past them from `x`, `y`. */
27
+export type SheetViewport = {
28
+ readonly x: number;
29
+ readonly y: number;
30
+ readonly width: number;
31
+ readonly height: number;
32
+};
33
+
34
+/** The cells of one viewport. */
35
+export type SheetFrameRequest = {
36
+ readonly sheet: number;
37
+ readonly x: number;
38
+ readonly y: number;
39
+ readonly width: number;
40
+ readonly height: number;
41
+ /** Device pixels per CSS pixel. */
42
+ readonly ratio: number;
43
+ /** Where the cells start inside the bitmap's first device pixel, so a frame lands where a direct paint would. */
44
+ readonly offset: { readonly x: number; readonly y: number };
45
+ /**
46
+ * A larger viewport around this one to draw instead, so the frame still covers the screen after a scroll that
47
+ * outruns the next frame. The worker draws the requested viewport alone where the engine refuses the larger one.
48
+ */
49
+ readonly wider: SheetViewport | undefined;
50
+};
51
+
52
+/** A painted frame: the bitmap and the little geometry the window needs to draw headers, select and follow links. */
53
+export type SheetFrame = {
54
+ /** The cells, `offset` device pixels in from its top-left corner. */
55
+ readonly bitmap: ImageBitmap;
56
+ /** The viewport the bitmap shows: the requested one, or a wider one with the margin. */
57
+ readonly viewport: SheetViewport;
58
+ readonly grid: GridMeta | undefined;
59
+ readonly hyperlinks: readonly HyperlinkRegion[];
60
+ /** The frozen panes' size in the frame. */
61
+ readonly frozen: { readonly width: number; readonly height: number };
62
+ /** Where the sheet's last cell ends, past the frozen panes; undefined when the engine cannot tell. */
63
+ readonly end: { readonly x: number; readonly y: number } | undefined;
64
+};
65
+
66
+/** The workbook worker's methods. Every method but `open` needs the workbook `open` opened. */
67
+export type SheetMethods = {
68
+ /**
69
+ * Opens the file's bytes and the sheet to show first: the active one, or the first visible one when the workbook was
70
+ * saved on a hidden sheet. Undefined when no sheet is visible.
71
+ */
72
+ readonly open: Method<
73
+ { readonly bytes: ArrayBuffer },
74
+ { readonly tabs: readonly SheetTab[]; readonly layout: SheetLayout } | undefined
75
+ >;
76
+ /** Makes a sheet the active one; rejects, leaving the sheet before it active, when it cannot open. */
77
+ readonly show: Method<{ readonly sheet: number }, SheetLayout>;
78
+ /** Paints a frame; undefined when even its smallest tiles cannot be drawn. */
79
+ readonly frame: Method<SheetFrameRequest, SheetFrame | undefined>;
80
+ /** Where a cell starts and where the cell past it starts, to scroll it into view. */
81
+ readonly position: Method<
82
+ { readonly sheet: number; readonly cell: CellAddr },
83
+ | { readonly start: { x: number; y: number }; readonly next: { x: number; y: number } }
84
+ | undefined
85
+ >;
86
+ /** The cells' text as they show, row by row, for screen readers. */
87
+ readonly cells: Method<
88
+ { readonly sheet: number; readonly range: CellRange },
89
+ readonly (readonly string[])[]
90
+ >;
91
+ /** The cells as they show, as tab-separated text to paste; undefined when they cannot be read. */
92
+ readonly copy: Method<{ readonly sheet: number; readonly range: CellRange }, string | undefined>;
93
+};
apps/web/src/components/files/office/slide-fonts.ts
new
+202
@@ -0,0 +1,202 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import type {
3
+ PositionedTextRun,
4
+ PresentationHandle,
5
+ SlideDisplayList,
6
+ SlidePrimitive,
7
+} from "@betteroffice/pptx";
8
+import { loadFace, presentationFace, scriptFace } from "./fonts";
9
+import type { DeckText, FallbackScript, FontStyle } from "./slide-text";
10
+
11
+/** A face the deck asks for: a family it names, or the fallback for a script the Latin faces lack. */
12
+type Want =
13
+ | { readonly family: string; readonly script?: undefined }
14
+ | { readonly script: FallbackScript; readonly family?: undefined };
15
+
16
+/** A face registered with both the engine and the browser. */
17
+type Face = { readonly want: Want; readonly style: FontStyle; readonly css: string };
18
+
19
+/**
20
+ * The faces one open deck draws with, added to `fonts`: the font set of the deck's own worker, which paints it. The
21
+ * engine shapes each face under the family name the deck uses, and the browser holds the same bytes under a private
22
+ * name that the laid-out frames are renamed to. Painting then matches shaping, and the deck's names (such as Inter or
23
+ * Segoe UI) never replace a font the painter itself needs.
24
+ */
25
+export function slideFonts(deck: PresentationHandle, fonts: FontFaceSet) {
26
+ const faces = new Map<number, Face>();
27
+ const names = new Map<string, string>();
28
+ const registered = new Set<string>();
29
+ const loads = new Map<string, Promise<void>>();
30
+ const settled = new Set<string>();
31
+
32
+ /** Loads a face's bytes and browser face; the returned function registers both, so callers choose the order. */
33
+ const prepare = async (want: Want, requested: FontStyle) => {
34
+ const source = want.script
35
+ ? scriptFace(want.script, requested.bold, requested.italic)
36
+ : presentationFace(want.family, requested.bold, requested.italic);
37
+
38
+ if (!source) return;
39
+
40
+ // A family without the requested style gets the face it has, which the browser then slants or emboldens.
41
+ const style = { bold: source.weight === 700, italic: source.style === "italic" };
42
+ // The worker holds this deck's faces alone, so the names only need to differ from each other.
43
+ const css = names.get(wantKey(want)) ?? `slide-${names.size}`;
44
+ const key = faceKey(want, style);
45
+
46
+ names.set(wantKey(want), css);
47
+
48
+ if (registered.has(key)) return;
49
+
50
+ const buffer = await loadFace(source).catch(() => undefined);
51
+
52
+ if (!buffer) return;
53
+
54
+ const browser = await new FontFace(css, buffer, {
55
+ weight: style.bold ? "700" : "400",
56
+ style: style.italic ? "italic" : "normal",
57
+ })
58
+ .load()
59
+ .catch(() => undefined);
60
+
61
+ if (!browser) return;
62
+
63
+ return () => {
64
+ if (registered.has(key)) return;
65
+
66
+ registered.add(key);
67
+ fonts.add(browser);
68
+
69
+ const face = {
70
+ family: want.script ? css : want.family,
71
+ ...style,
72
+ bytes: new Uint8Array(buffer),
73
+ };
74
+
75
+ faces.set(want.script ? deck.registerFallbackFont(face) : deck.registerFont(face), {
76
+ want,
77
+ style,
78
+ css,
79
+ });
80
+ };
81
+ };
82
+
83
+ /** Loads and registers one face once; later requests share the first. */
84
+ const request = (want: Want, style: FontStyle) => {
85
+ const key = faceKey(want, style);
86
+ const existing = loads.get(key);
87
+
88
+ if (existing) return existing;
89
+
90
+ const load = prepare(want, style).then((register) => {
91
+ register?.();
92
+ settled.add(key);
93
+ });
94
+
95
+ loads.set(key, load);
96
+
97
+ return load;
98
+ };
99
+
100
+ /** The faces a frame drew in a substitute style whose own face has not loaded or failed yet. */
101
+ const missing = (primitives: readonly SlidePrimitive[]) =>
102
+ textRuns(primitives).flatMap((run) => {
103
+ const face = faces.get(run.fontId);
104
+ const style = { bold: run.bold, italic: run.italic };
105
+
106
+ if (!face || sameStyle(face.style, style) || settled.has(faceKey(face.want, style)))
107
+ return [];
108
+
109
+ return [{ want: face.want, style }];
110
+ });
111
+
112
+ const rename = (primitive: SlidePrimitive): SlidePrimitive => {
113
+ if (primitive.kind === "textBox")
114
+ return {
115
+ ...primitive,
116
+ lines: primitive.lines.map((line) => ({
117
+ ...line,
118
+ runs: line.runs.map((run) => ({
119
+ ...run,
120
+ fontFamily: faces.get(run.fontId)?.css ?? run.fontFamily,
121
+ })),
122
+ })),
123
+ };
124
+
125
+ if (primitive.kind === "table" || primitive.kind === "chart")
126
+ return { ...primitive, primitives: primitive.primitives.map(rename) };
127
+
128
+ return primitive;
129
+ };
130
+
131
+ return {
132
+ /**
133
+ * Registers the faces the deck's text names, in the order `text` ranks them: the engine draws every family it
134
+ * cannot find with the first. Resolves once each face has loaded or failed.
135
+ */
136
+ load: async (text: DeckText) => {
137
+ const regular = { bold: false, italic: false };
138
+ // The engine lays no text out without a face, so a deck that names none gets PowerPoint's own default.
139
+ const families =
140
+ text.families.length > 0 ? text.families : [{ name: "Calibri", styles: [regular] }];
141
+
142
+ const wants: { want: Want; style: FontStyle }[] = [
143
+ ...families.flatMap((family) =>
144
+ family.styles.map((style) => ({ want: { family: family.name }, style })),
145
+ ),
146
+ ...text.scripts.map((script) => ({ want: { script }, style: regular })),
147
+ ];
148
+
149
+ const registers = await Promise.all(wants.map((entry) => prepare(entry.want, entry.style)));
150
+
151
+ registers.forEach((register) => register?.());
152
+ wants.forEach((entry) => {
153
+ const key = faceKey(entry.want, entry.style);
154
+
155
+ loads.set(key, Promise.resolve());
156
+ settled.add(key);
157
+ });
158
+ },
159
+
160
+ /**
161
+ * Lays a slide out. When its text asks for a style a registered face lacks, such as a bold the title style
162
+ * inherits, that face loads and the slide lays out again. The frame names the browser's faces, ready to paint.
163
+ */
164
+ layout: async (index: number) => {
165
+ const settle = async (rounds: number): Promise<SlideDisplayList> => {
166
+ const frame = deck.layoutSlide(index);
167
+ const wanted = rounds === 0 ? [] : missing(frame.primitives);
168
+
169
+ if (wanted.length === 0) return { ...frame, primitives: frame.primitives.map(rename) };
170
+
171
+ await Promise.all(wanted.map((entry) => request(entry.want, entry.style)));
172
+
173
+ return settle(rounds - 1);
174
+ };
175
+
176
+ return settle(2);
177
+ },
178
+ };
179
+}
180
+
181
+function textRuns(primitives: readonly SlidePrimitive[]): PositionedTextRun[] {
182
+ return primitives.flatMap((primitive) => {
183
+ if (primitive.kind === "textBox") return primitive.lines.flatMap((line) => line.runs);
184
+
185
+ if (primitive.kind === "table" || primitive.kind === "chart")
186
+ return textRuns(primitive.primitives);
187
+
188
+ return [];
189
+ });
190
+}
191
+
192
+function wantKey(want: Want) {
193
+ return want.script ? `script:${want.script}` : `family:${want.family.toLowerCase()}`;
194
+}
195
+
196
+function faceKey(want: Want, style: FontStyle) {
197
+ return `${wantKey(want)}|${style.bold}|${style.italic}`;
198
+}
199
+
200
+function sameStyle(left: FontStyle, right: FontStyle) {
201
+ return left.bold === right.bold && left.italic === right.italic;
202
+}
apps/web/src/components/files/office/slide-protocol.ts
new
+47
@@ -0,0 +1,47 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import type { Method } from "./worker-rpc";
3
+
4
+/** The longest side a decoded picture keeps: enough for a full-width slide on a high-density screen. */
5
+export const maxImageSide = 2560;
6
+
7
+/** What the window shows of one slide besides its bitmap. */
8
+export type SlideSummary = {
9
+ /** In CSS pixels. */
10
+ readonly width: number;
11
+ readonly height: number;
12
+ readonly hidden: boolean;
13
+ readonly notes: string | undefined;
14
+};
15
+
16
+/** An SVG picture the worker cannot decode, which the window rasterizes at `size`, or at its own size when absent. */
17
+export type VectorRequest = {
18
+ readonly asset: string;
19
+ readonly blob: Blob;
20
+ readonly size: { readonly width: number; readonly height: number } | undefined;
21
+};
22
+
23
+/** A rasterized SVG picture, or none when the window could not decode it either. */
24
+export type VectorBitmap = { readonly asset: string; readonly bitmap: ImageBitmap | undefined };
25
+
26
+export type SlidePainted =
27
+ | {
28
+ readonly kind: "painted";
29
+ /** The slide at the requested density, or less when that would exceed the bitmap caps. */
30
+ readonly bitmap: ImageBitmap;
31
+ /** SVG pictures the slide drew without, or too coarse: paint again once the worker has them. */
32
+ readonly vectors: readonly VectorRequest[];
33
+ }
34
+ /** The slide does not lay out, or does not paint even without shadows. */
35
+ | { readonly kind: "failed" }
36
+ /** The caller aborted the paint while it ran. */
37
+ | { readonly kind: "cancelled" };
38
+
39
+/** The PowerPoint worker's methods. */
40
+export type SlideMethods = {
41
+ /** Opens the deck once per worker, its fonts included. Rejects when the engine cannot read it. */
42
+ readonly open: Method<{ readonly bytes: ArrayBuffer }, readonly SlideSummary[]>;
43
+ /** Paints one slide at `density` device pixels per CSS pixel. */
44
+ readonly paint: Method<{ readonly index: number; readonly density: number }, SlidePainted>;
45
+ /** Hands over SVG pictures rasterized for `VectorRequest`s. */
46
+ readonly vectors: Method<readonly VectorBitmap[], void>;
47
+};
apps/web/src/components/files/office/slide-text.ts
new
+401
@@ -0,0 +1,401 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import * as Option from "effect/Option";
3
+import * as Schema from "effect/Schema";
4
+import { inspectPresentation, type DeckSnapshot } from "@betteroffice/pptx";
5
+
6
+/** A text style a deck draws with. */
7
+export type FontStyle = { readonly bold: boolean; readonly italic: boolean };
8
+
9
+/** A family the deck names, with the styles its text asks for. */
10
+export type DeckFamily = { readonly name: string; readonly styles: readonly FontStyle[] };
11
+
12
+/** The scripts the bundled Latin faces may lack, which have a bundled fallback face. */
13
+export type FallbackScript = "hebrew" | "arabic";
14
+
15
+/** What a deck's text needs from the fonts, and which slides it hides. */
16
+export type DeckText = {
17
+ /** Most important first: the face registered first also draws every family the deck names but nobody found. */
18
+ readonly families: readonly DeckFamily[];
19
+ readonly scripts: readonly FallbackScript[];
20
+ /** One flag per slide, in deck order. */
21
+ readonly hidden: readonly boolean[];
22
+};
23
+
24
+const RunStyle = Schema.Struct({
25
+ bold: Schema.optional(Schema.NullOr(Schema.Boolean)),
26
+ italic: Schema.optional(Schema.NullOr(Schema.Boolean)),
27
+ fontFamily: Schema.optional(Schema.NullOr(Schema.String)),
28
+});
29
+
30
+const Body = Schema.Struct({
31
+ paragraphs: Schema.Array(
32
+ Schema.Struct({
33
+ properties: Schema.optional(
34
+ Schema.NullOr(
35
+ Schema.Struct({
36
+ defaultRun: Schema.optional(Schema.NullOr(RunStyle)),
37
+ }),
38
+ ),
39
+ ),
40
+ runs: Schema.Array(
41
+ Schema.Struct({
42
+ text: Schema.String,
43
+ properties: Schema.optional(Schema.NullOr(RunStyle)),
44
+ }),
45
+ ),
46
+ }),
47
+ ),
48
+});
49
+
50
+type Drawing = {
51
+ readonly text?: typeof Body.Type | null | undefined;
52
+ readonly children?: readonly Drawing[] | undefined;
53
+ readonly data?: typeof Table.Type | null | undefined;
54
+};
55
+
56
+const Table = Schema.Struct({
57
+ rows: Schema.optional(
58
+ Schema.Array(
59
+ Schema.Struct({
60
+ cells: Schema.Array(Schema.Struct({ text: Schema.optional(Schema.NullOr(Body)) })),
61
+ }),
62
+ ),
63
+ ),
64
+});
65
+
66
+/** A slide object: a shape, group, picture or graphic frame. */
67
+const Drawing: Schema.Codec<Drawing> = Schema.Struct({
68
+ text: Schema.optional(Schema.NullOr(Body)),
69
+ children: Schema.optional(Schema.Array(Schema.suspend((): Schema.Codec<Drawing> => Drawing))),
70
+ // A table's cells; other frames, such as charts, carry no rows.
71
+ data: Schema.optional(Schema.NullOr(Table)),
72
+});
73
+
74
+const ThemeFont = Schema.Struct({ latin: Schema.String });
75
+
76
+const Inspected = Schema.Struct({
77
+ slides: Schema.Array(
78
+ Schema.Struct({
79
+ hidden: Schema.optional(Schema.Boolean),
80
+ drawings: Schema.Array(Drawing),
81
+ }).pipe(Schema.encodeKeys({ drawings: "shapes" })),
82
+ ),
83
+ layouts: Schema.optional(
84
+ Schema.Array(
85
+ Schema.Struct({ drawings: Schema.Array(Drawing) }).pipe(
86
+ Schema.encodeKeys({ drawings: "shapes" }),
87
+ ),
88
+ ),
89
+ ),
90
+ masters: Schema.optional(
91
+ Schema.Array(
92
+ Schema.Struct({
93
+ drawings: Schema.Array(Drawing),
94
+ textStyles: Schema.optional(
95
+ Schema.NullOr(
96
+ Schema.Record(
97
+ Schema.String,
98
+ Schema.Array(Schema.Struct({ defaultRun: Schema.optional(Schema.NullOr(RunStyle)) })),
99
+ ),
100
+ ),
101
+ ),
102
+ }).pipe(Schema.encodeKeys({ drawings: "shapes" })),
103
+ ),
104
+ ),
105
+ themes: Schema.optional(
106
+ Schema.Array(
107
+ Schema.Struct({
108
+ theme: Schema.optional(
109
+ Schema.NullOr(
110
+ Schema.Struct({
111
+ fontScheme: Schema.optional(
112
+ Schema.NullOr(Schema.Struct({ majorFont: ThemeFont, minorFont: ThemeFont })),
113
+ ),
114
+ }),
115
+ ),
116
+ ),
117
+ }),
118
+ ),
119
+ ),
120
+});
121
+
122
+const decodeInspected = Schema.decodeUnknownOption(Inspected);
123
+
124
+const scriptRanges: readonly (readonly [FallbackScript, RegExp])[] = [
125
+ ["hebrew", /[\u0590-\u05FF\uFB1D-\uFB4F]/u],
126
+ ["arabic", /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/u],
127
+];
128
+
129
+/**
130
+ * Reads the families, styles and scripts a deck's text uses, from its slides, layouts, masters and theme. When the
131
+ * engine's inspection does not decode, the slides' own runs stand in, without theme fonts or hidden flags.
132
+ */
133
+export function deckText(bytes: Uint8Array, snapshot: DeckSnapshot): DeckText {
134
+ return Option.match(decodeInspected(inspectPresentation(withoutMedia(bytes))), {
135
+ onNone: () => fromSnapshot(snapshot),
136
+ onSome: (inspected) => {
137
+ const schemes =
138
+ inspected.themes?.flatMap((theme) =>
139
+ theme.theme?.fontScheme ? [theme.theme.fontScheme] : [],
140
+ ) ?? [];
141
+ const minor = schemes[0]?.minorFont.latin ?? "";
142
+
143
+ const drawings = [
144
+ ...inspected.slides.flatMap((slide) => slide.drawings),
145
+ ...(inspected.layouts ?? []).flatMap((layout) => layout.drawings),
146
+ ...(inspected.masters ?? []).flatMap((master) => master.drawings),
147
+ ];
148
+
149
+ const defaults = (inspected.masters ?? []).flatMap((master) =>
150
+ Object.values(master.textStyles ?? {}).flatMap((levels) =>
151
+ levels.flatMap((level) =>
152
+ level.defaultRun ? [{ text: "", style: level.defaultRun }] : [],
153
+ ),
154
+ ),
155
+ );
156
+
157
+ return summarize(
158
+ [...drawings.flatMap(drawingRuns), ...defaults].flatMap((run) => {
159
+ const family = run.style?.fontFamily;
160
+ if (!schemes.length || (family && !family.startsWith("+mn") && !family.startsWith("+mj")))
161
+ return [run];
162
+ return schemes.map((scheme) => ({
163
+ ...run,
164
+ style: {
165
+ ...run.style,
166
+ fontFamily: family?.startsWith("+mj")
167
+ ? scheme.majorFont.latin
168
+ : scheme.minorFont.latin,
169
+ },
170
+ }));
171
+ }),
172
+ (family) => (family?.startsWith("+") ? "" : (family ?? "")),
173
+ minor,
174
+ inspected.slides.map((slide) => slide.hidden ?? false),
175
+ );
176
+ },
177
+ });
178
+}
179
+
180
+/** A file in the deck's zip package: where its central directory record and its local data sit. */
181
+type Entry = {
182
+ readonly name: string;
183
+ readonly record: number;
184
+ readonly length: number;
185
+ readonly local: number;
186
+};
187
+
188
+/**
189
+ * The package without its pictures and media. The inspection reads only the deck's text and styles, but returns every
190
+ * picture as base64, which for a deck of photos costs tens of megabytes of engine memory the worker never gives back.
191
+ * Entries keep their compressed bytes. A package this cannot read, such as a ZIP64 one, stays as it is.
192
+ */
193
+function withoutMedia(bytes: Uint8Array): Uint8Array {
194
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
195
+ const end = endOfDirectory(view);
196
+
197
+ if (end === undefined) return bytes;
198
+
199
+ const count = view.getUint16(end + 10, true);
200
+ const directory = view.getUint32(end + 16, true);
201
+
202
+ if (count === 0xffff || directory === 0xffffffff || directory > end) return bytes;
203
+
204
+ const entries = readEntries(view, directory, end, count);
205
+
206
+ if (!entries || !entries.some((entry) => entry.name.startsWith("ppt/media/"))) return bytes;
207
+
208
+ // An entry's local header and data run up to the next entry's, or to the central directory.
209
+ const starts = entries.map((entry) => entry.local).toSorted((left, right) => left - right);
210
+
211
+ const kept = entries
212
+ .filter((entry) => !entry.name.startsWith("ppt/media/"))
213
+ .map((entry) => ({
214
+ entry,
215
+ start: entry.local,
216
+ end: starts.find((start) => start > entry.local) ?? directory,
217
+ }));
218
+
219
+ // Where each kept entry's local data and directory record land in the new package.
220
+ const locals = offsets(kept.map((part) => part.end - part.start));
221
+ const records = offsets(kept.map((part) => part.entry.length));
222
+ const size = locals.at(-1) ?? 0;
223
+ const directorySize = records.at(-1) ?? 0;
224
+ const out = new Uint8Array(size + directorySize + 22);
225
+ const writer = new DataView(out.buffer);
226
+
227
+ kept.forEach((part, index) => {
228
+ const local = locals[index] ?? 0;
229
+ const record = size + (records[index] ?? 0);
230
+
231
+ out.set(bytes.subarray(part.start, part.end), local);
232
+ out.set(bytes.subarray(part.entry.record, part.entry.record + part.entry.length), record);
233
+ writer.setUint32(record + 42, local, true);
234
+ });
235
+
236
+ const tail = size + directorySize;
237
+
238
+ out.set(bytes.subarray(end, end + 22), tail);
239
+ writer.setUint16(tail + 8, kept.length, true);
240
+ writer.setUint16(tail + 10, kept.length, true);
241
+ writer.setUint32(tail + 12, directorySize, true);
242
+ writer.setUint32(tail + 16, size, true);
243
+ writer.setUint16(tail + 20, 0, true);
244
+
245
+ return out;
246
+}
247
+
248
+/** Where each length starts when they are laid end to end, then where the last ends. */
249
+function offsets(lengths: readonly number[]) {
250
+ return lengths.reduce(
251
+ (list, length) => {
252
+ list.push((list.at(-1) ?? 0) + length);
253
+
254
+ return list;
255
+ },
256
+ [0],
257
+ );
258
+}
259
+
260
+/** Where the end of central directory record starts, searched back from the end past any comment. */
261
+function endOfDirectory(view: DataView) {
262
+ const last = view.byteLength - 22;
263
+ const first = Math.max(0, last - 0xffff);
264
+
265
+ for (let at = last; at >= first; at--) if (view.getUint32(at, true) === 0x06054b50) return at;
266
+
267
+ return undefined;
268
+}
269
+
270
+/**
271
+ * The central directory's records, from `directory` up to the end record at `end`; undefined when one is malformed: it
272
+ * runs past the directory, or its local header does not sit before it.
273
+ */
274
+function readEntries(view: DataView, directory: number, end: number, count: number) {
275
+ const decoder = new TextDecoder();
276
+
277
+ return Array.from({ length: count }).reduce<{ at: number; entries: Entry[] } | undefined>(
278
+ (state) => {
279
+ if (!state || state.at + 46 > end || view.getUint32(state.at, true) !== 0x02014b50)
280
+ return undefined;
281
+
282
+ const nameLength = view.getUint16(state.at + 28, true);
283
+ const length =
284
+ 46 + nameLength + view.getUint16(state.at + 30, true) + view.getUint16(state.at + 32, true);
285
+ const local = view.getUint32(state.at + 42, true);
286
+
287
+ // A local header is 30 bytes before its name and data.
288
+ if (state.at + length > end || local + 30 > directory) return undefined;
289
+
290
+ const name = decoder.decode(
291
+ new Uint8Array(view.buffer, view.byteOffset + state.at + 46, nameLength),
292
+ );
293
+
294
+ state.entries.push({ name, record: state.at, length, local });
295
+
296
+ return { at: state.at + length, entries: state.entries };
297
+ },
298
+ { at: directory, entries: [] },
299
+ )?.entries;
300
+}
301
+
302
+type Run = { readonly text: string; readonly style: typeof RunStyle.Type | null | undefined };
303
+
304
+function drawingRuns(drawing: Drawing): Run[] {
305
+ return [
306
+ ...bodyRuns(drawing.text),
307
+ ...(drawing.data?.rows ?? []).flatMap((row) =>
308
+ row.cells.flatMap((cell) => bodyRuns(cell.text)),
309
+ ),
310
+ ...(drawing.children ?? []).flatMap(drawingRuns),
311
+ ];
312
+}
313
+
314
+function bodyRuns(body: typeof Body.Type | null | undefined): Run[] {
315
+ return (body?.paragraphs ?? []).flatMap((paragraph) =>
316
+ paragraph.runs.map((run) => ({
317
+ text: run.text,
318
+ style: {
319
+ fontFamily: run.properties?.fontFamily ?? paragraph.properties?.defaultRun?.fontFamily,
320
+ bold: run.properties?.bold ?? paragraph.properties?.defaultRun?.bold,
321
+ italic: run.properties?.italic ?? paragraph.properties?.defaultRun?.italic,
322
+ },
323
+ })),
324
+ );
325
+}
326
+
327
+function fromSnapshot(snapshot: DeckSnapshot): DeckText {
328
+ const runs = (drawings: DeckSnapshot["slides"][number]["shapes"]): Run[] =>
329
+ drawings.flatMap((drawing) => [
330
+ ...drawing.textStories.flatMap((story) =>
331
+ story.paragraphs.flatMap((paragraph) =>
332
+ paragraph.runs.map((run) => ({ text: run.text, style: run.style })),
333
+ ),
334
+ ),
335
+ ...runs(drawing.children),
336
+ ]);
337
+
338
+ return summarize(
339
+ snapshot.slides.flatMap((slide) => runs(slide.shapes)),
340
+ (family) => family ?? "",
341
+ "",
342
+ snapshot.slides.map(() => false),
343
+ );
344
+}
345
+
346
+/**
347
+ * Groups runs by the family they resolve to: the theme's body font first, then by how much text each draws. The
348
+ * masters' default runs count too, so a theme font that placeholders inherit without naming it is still found.
349
+ */
350
+function summarize(
351
+ runs: readonly Run[],
352
+ resolve: (family: string | null | undefined) => string,
353
+ theme: string,
354
+ hidden: readonly boolean[],
355
+): DeckText {
356
+ const families = new Map<
357
+ string,
358
+ { name: string; weight: number; styles: Map<string, FontStyle> }
359
+ >();
360
+ const body = theme.trim().toLowerCase();
361
+ const text = runs.map((run) => run.text).join("");
362
+
363
+ runs.forEach((run) => {
364
+ const name = resolve(run.style?.fontFamily).trim();
365
+
366
+ if (!name) return;
367
+
368
+ const style = { bold: run.style?.bold ?? false, italic: run.style?.italic ?? false };
369
+ const family = families.get(name.toLowerCase()) ?? {
370
+ name,
371
+ weight: 0,
372
+ styles: new Map<string, FontStyle>(),
373
+ };
374
+
375
+ family.weight += run.text.length;
376
+ family.styles.set(`${style.bold}|${style.italic}`, style);
377
+ families.set(name.toLowerCase(), family);
378
+ });
379
+
380
+ return {
381
+ families: [...families.entries()]
382
+ .toSorted((left, right) => rank(right, body) - rank(left, body))
383
+ .map((entry) => ({
384
+ name: entry[1].name,
385
+ // Regular first, so a family's first face is the one its unstyled text draws with.
386
+ styles: [...entry[1].styles.values()].toSorted(
387
+ (left, right) => styleRank(left) - styleRank(right),
388
+ ),
389
+ })),
390
+ scripts: scriptRanges.flatMap((entry) => (entry[1].test(text) ? [entry[0]] : [])),
391
+ hidden,
392
+ };
393
+}
394
+
395
+function rank(entry: readonly [string, { readonly weight: number }], body: string) {
396
+ return entry[0] === body ? Number.POSITIVE_INFINITY : entry[1].weight;
397
+}
398
+
399
+function styleRank(style: FontStyle) {
400
+ return (style.bold ? 1 : 0) + (style.italic ? 2 : 0);
401
+}
apps/web/src/components/files/office/spreadsheet.worker.ts
new
+309
@@ -0,0 +1,309 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import {
3
+ initWasm,
4
+ openWorkbook,
5
+ toTsv,
6
+ type SheetInfo,
7
+ type WorkbookHandle,
8
+ type XlsxCellRead,
9
+ type XlsxRangeTarget,
10
+} from "@betteroffice/xlsx";
11
+import type { CellRange } from "@betteroffice/xlsx/headless";
12
+import { anchorRange, attempt, lastCell, parseRange, parseSpans } from "./sheet-cells";
13
+import { drawFrame, paintFrame } from "./sheet-frame";
14
+import { frozenSize } from "./sheet-paint";
15
+import type { SheetLayout, SheetMethods, SheetTab } from "./sheet-protocol";
16
+import { serveWorker, Transfer } from "./worker-rpc";
17
+
18
+// One worker holds one open workbook: its engine, recalculation, display lists and the painting of its cells. The
19
+// window terminates the worker when the workbook closes, which is the only way the engine's memory is given back.
20
+
21
+type Opened = {
22
+ readonly workbook: WorkbookHandle;
23
+ /** The active sheet's metadata; the engine draws only the active sheet. */
24
+ info: SheetInfo;
25
+ /** Where each sheet's last cell ends, by sheet and frozen panes' size; measured once, as it costs a frame. */
26
+ readonly ends: Map<string, { readonly x: number; readonly y: number } | undefined>;
27
+ /** The one canvas every frame paints on and hands over as a bitmap. */
28
+ readonly surface: OffscreenCanvas;
29
+};
30
+
31
+/** The workbook this worker opened, once it has. */
32
+type State = { opened: Opened | undefined };
33
+
34
+const state: State = { opened: undefined };
35
+
36
+serveWorker<SheetMethods>({
37
+ open: async (input) => {
38
+ if (state.opened) throw new Error("The worker already holds a workbook");
39
+
40
+ await initWasm();
41
+
42
+ const workbook = openWorkbook(new Uint8Array(input.bytes));
43
+ const info = workbook.sheetInfo();
44
+
45
+ state.opened = { workbook, info, ends: new Map(), surface: new OffscreenCanvas(1, 1) };
46
+
47
+ const tabs = visibleTabs(workbook, info);
48
+ // A workbook saved on a hidden sheet opens on the first visible one, as Excel does.
49
+ const first = tabs.find((tab) => tab.index === info.activeSheet) ?? tabs[0];
50
+
51
+ if (!first) return undefined;
52
+
53
+ return { tabs, layout: show(state.opened, first.index) };
54
+ },
55
+ show: (input) => {
56
+ const opened = required();
57
+ const current = opened.info.activeSheet;
58
+ const layout = attempt(() => show(opened, input.sheet));
59
+
60
+ if (layout) return layout;
61
+
62
+ // One sheet that fails to open leaves the others readable: go back to the sheet on show.
63
+ attempt(() => show(opened, current));
64
+
65
+ throw new Error(`Sheet ${input.sheet} could not open`);
66
+ },
67
+ frame: (input) => {
68
+ const opened = active(input.sheet);
69
+ const frozen = { rows: opened.info.frozenRows, cols: opened.info.frozenCols };
70
+ const viewport = { x: input.x, y: input.y, width: input.width, height: input.height };
71
+ const drawn = drawFrame(opened.workbook, viewport, frozen, input.wider);
72
+
73
+ if (!drawn) return undefined;
74
+
75
+ const surface = opened.surface;
76
+ const width = Math.ceil(input.offset.x + drawn.viewport.width * input.ratio);
77
+ const height = Math.ceil(input.offset.y + drawn.viewport.height * input.ratio);
78
+
79
+ if (surface.width !== width) surface.width = width;
80
+
81
+ if (surface.height !== height) surface.height = height;
82
+
83
+ const context = surface.getContext("2d");
84
+
85
+ if (!context) return undefined;
86
+
87
+ paintFrame(context, drawn, { ratio: input.ratio, origin: input.offset });
88
+
89
+ const bitmap = surface.transferToImageBitmap();
90
+ const grid = drawn.list.grid;
91
+ const panes = frozenSize(grid, frozen);
92
+
93
+ return new Transfer(
94
+ {
95
+ bitmap,
96
+ viewport: drawn.viewport,
97
+ grid,
98
+ hyperlinks: drawn.list.hyperlinks ?? [],
99
+ frozen: panes,
100
+ end: end(opened, input.sheet, panes),
101
+ },
102
+ [bitmap],
103
+ );
104
+ },
105
+ position: (input) => {
106
+ const workbook = required().workbook;
107
+ const cell = input.cell;
108
+ const start = attempt(() => workbook.cellPosition(input.sheet, cell.row, cell.col));
109
+
110
+ const next = attempt(() =>
111
+ workbook.cellPosition(
112
+ input.sheet,
113
+ Math.min(cell.row + 1, lastCell.row),
114
+ Math.min(cell.col + 1, lastCell.col),
115
+ ),
116
+ );
117
+
118
+ return start && next ? { start, next } : undefined;
119
+ },
120
+ cells: (input) => {
121
+ const cells = read(required(), input.sheet, input.range);
122
+ const range = input.range;
123
+
124
+ return Array.from({ length: range.bottom - range.top + 1 }, (_, row) =>
125
+ Array.from(
126
+ { length: range.right - range.left + 1 },
127
+ (_, col) => cells?.[row]?.[col]?.displayText ?? "",
128
+ ),
129
+ );
130
+ },
131
+ // Copies the cells as they show, which is what a reader expects to paste, not the formulas behind them.
132
+ copy: (input) => {
133
+ const cells = read(required(), input.sheet, input.range);
134
+
135
+ if (!cells) return undefined;
136
+
137
+ return toTsv(
138
+ cells.map((row) =>
139
+ row.map((cell) => ({ input: cell.displayText, isFormula: literal(cell) })),
140
+ ),
141
+ );
142
+ },
143
+});
144
+
145
+function required() {
146
+ if (!state.opened) throw new Error("The worker holds no workbook");
147
+
148
+ return state.opened;
149
+}
150
+
151
+/** The workbook with `sheet` active, as a frame from a grid that has since given way to another sheet may ask. */
152
+function active(sheet: number) {
153
+ const opened = required();
154
+
155
+ if (opened.info.activeSheet !== sheet) show(opened, sheet);
156
+
157
+ return opened;
158
+}
159
+
160
+/** Makes a sheet the active one and reads what its grid needs. */
161
+function show(opened: Opened, sheet: number): SheetLayout {
162
+ opened.workbook.setActiveSheet(sheet);
163
+ opened.info = opened.workbook.sheetInfo();
164
+
165
+ return { info: opened.info, ...layout(opened.workbook, sheet) };
166
+}
167
+
168
+/**
169
+ * The used range, the merged cells, the hidden rows and columns, and how far the charts reach, from one export of the
170
+ * sheet's metadata. One cell is enough: the lists before the cells are complete however soon the export stops.
171
+ */
172
+function layout(workbook: WorkbookHandle, sheet: number) {
173
+ const result = attempt(() =>
174
+ workbook.exportStructured({
175
+ scope: [{ sheet, range: "A1:XFD1048576" }],
176
+ maxCells: 1,
177
+ includeDefinedNames: false,
178
+ }),
179
+ );
180
+
181
+ const exported = result?.ok ? result.content.sheets[0] : undefined;
182
+
183
+ const charts = (exported?.objects ?? [])
184
+ .filter((object) => object.kind === "chart" && !object.hidden)
185
+ .flatMap((object) => (object.anchor ? anchorRange(object.anchor) : []))
186
+ // The corner cell holds the chart's edge somewhere inside it, so the cell past it bounds the chart.
187
+ .flatMap((range) => {
188
+ const corner = attempt(() =>
189
+ workbook.cellPosition(
190
+ sheet,
191
+ Math.min(range.bottom + 1, lastCell.row),
192
+ Math.min(range.right + 1, lastCell.col),
193
+ ),
194
+ );
195
+
196
+ return corner ? [corner] : [];
197
+ });
198
+
199
+ return {
200
+ used: exported?.usedRange ? parseRange(exported.usedRange) : undefined,
201
+ merges: (exported?.merges ?? []).flatMap((merge) => anchorRange(merge.anchor)),
202
+ hidden: {
203
+ rows: parseSpans(exported?.hiddenRows ?? [], "rows"),
204
+ columns: parseSpans(exported?.hiddenColumns ?? [], "columns"),
205
+ },
206
+ chartWidth: Math.max(0, ...charts.map((corner) => corner.x)),
207
+ chartHeight: Math.max(0, ...charts.map((corner) => corner.y)),
208
+ };
209
+}
210
+
211
+/** Where the sheet's last cell ends, past the frozen panes. A viewport past it makes the engine throw. */
212
+function end(
213
+ opened: Opened,
214
+ sheet: number,
215
+ frozen: { readonly width: number; readonly height: number },
216
+) {
217
+ const key = `${sheet}:${frozen.width}:${frozen.height}`;
218
+
219
+ if (opened.ends.has(key)) return opened.ends.get(key);
220
+
221
+ const measured = measureEnd(opened.workbook, sheet, frozen);
222
+
223
+ opened.ends.set(key, measured);
224
+
225
+ return measured;
226
+}
227
+
228
+function measureEnd(
229
+ workbook: WorkbookHandle,
230
+ sheet: number,
231
+ frozen: { readonly width: number; readonly height: number },
232
+) {
233
+ const last = attempt(() => workbook.cellPosition(sheet, lastCell.row, lastCell.col));
234
+
235
+ if (!last) return undefined;
236
+
237
+ // A viewport one pixel past the frozen panes, on the last cell, reports where that cell ends.
238
+ const grid = attempt(
239
+ () =>
240
+ workbook.displayList({
241
+ x: last.x,
242
+ y: last.y,
243
+ width: frozen.width + 1,
244
+ height: frozen.height + 1,
245
+ }).grid,
246
+ );
247
+
248
+ // The engine works in single precision there, so stay a little short of the edge.
249
+ const margin = 2;
250
+
251
+ return {
252
+ x:
253
+ last.x +
254
+ Math.max(0, (grid ? (grid.colOffsets[grid.colOffsets.length - 1] ?? 0) : 0) - frozen.width) -
255
+ margin,
256
+ y:
257
+ last.y +
258
+ Math.max(0, (grid ? (grid.rowOffsets[grid.rowOffsets.length - 1] ?? 0) : 0) - frozen.height) -
259
+ margin,
260
+ };
261
+}
262
+
263
+/** The cells of a range on a sheet as the engine reads them, row by row; undefined when it cannot. */
264
+function read(opened: Opened, sheet: number, range: CellRange) {
265
+ if ((range.bottom - range.top + 1) * (range.right - range.left + 1) > 200_000) return undefined;
266
+ const target: XlsxRangeTarget = {
267
+ sheetId: opened.info.sheetIds[sheet]!,
268
+ range: {
269
+ kind: "rowCol",
270
+ start: { row: range.top, col: range.left },
271
+ end: { row: range.bottom, col: range.right },
272
+ },
273
+ };
274
+
275
+ const result = attempt(() => opened.workbook.readCells({ ranges: [target] }));
276
+
277
+ return result?.ok ? result.ranges[0]?.cells : undefined;
278
+}
279
+
280
+/** The workbook's sheets but its hidden and very hidden ones, which Excel lists only to unhide. */
281
+function visibleTabs(workbook: WorkbookHandle, info: SheetInfo): SheetTab[] {
282
+ const names = info.sheetNames;
283
+
284
+ const result = attempt(() =>
285
+ workbook.exportStructured({
286
+ includeHiddenSheets: true,
287
+ includeDefinedNames: false,
288
+ scope: names.map((_, sheet) => ({ sheet, range: "A1" })),
289
+ }),
290
+ );
291
+
292
+ const hidden = new Set(
293
+ (result?.ok ? result.content.sheets : [])
294
+ .filter((sheet) => sheet.visibility === "hidden" || sheet.visibility === "veryHidden")
295
+ .flatMap((sheet) => (sheet.anchor.kind === "sheet" ? [sheet.anchor.sheet.index] : [])),
296
+ );
297
+
298
+ return names.flatMap((name, index) => (hidden.has(index) ? [] : [{ index, name }]));
299
+}
300
+
301
+/**
302
+ * Whether a cell's text pastes as it is. `toTsv` quotes text that a spreadsheet would read as a formula; a number shown
303
+ * with a sign, such as "-12.50", is safe, and quoting it would paste text instead of the number.
304
+ */
305
+function literal(cell: XlsxCellRead) {
306
+ return (
307
+ cell.value.kind === "number" && /^[-+][\d\s.,%\p{Sc}]+(?:e[-+]\d+)?$/iu.test(cell.displayText)
308
+ );
309
+}
apps/web/src/components/files/office/word-images.ts
new
+107
@@ -0,0 +1,107 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import type { ImageResolver } from "@betteroffice/docx/layout/render";
3
+import type { YrsMediaSource } from "@betteroffice/docx/yrs";
4
+import { officeImageBitmap } from "./image-bitmap";
5
+
6
+/** An embedded image's source, which names a part of the package the session reads. */
7
+const mediaToken = /^media:(0|[1-9]\d*)$/u;
8
+
9
+/** How many bytes of decoded images stay for repaints; the least recently drawn go first past it. */
10
+const budget = 256 * 1024 * 1024;
11
+
12
+type Decoded = {
13
+ readonly image: Promise<CanvasImageSource | null>;
14
+ /** The decoded image once it is one; the shared placeholder is never closed. */
15
+ bitmap: ImageBitmap | undefined;
16
+};
17
+
18
+/**
19
+ * Resolves the display list's images in a worker, where there is no `Image` element: a `media:{n}` source decodes
20
+ * from the bytes the session reads, and a `data:` or `blob:` source decodes in place. Anything else, such as a remote
21
+ * address, resolves to nothing, so painting never makes a request. A part that is missing or cannot be decoded paints a
22
+ * grey box, as the window's resolver does. Decoded images stay for repaints within `budget`.
23
+ */
24
+export function createBitmapImageResolver(media: (token: string) => YrsMediaSource | null) {
25
+ const cache = new Map<string, Decoded>();
26
+ const placeholder = greyBox();
27
+
28
+ const decode = (source: string): Promise<CanvasImageSource | null> => {
29
+ const token = mediaToken.test(source);
30
+ const found = token ? media(source) : undefined;
31
+
32
+ if (token && !found) return Promise.resolve(placeholder);
33
+
34
+ const blob = found
35
+ ? Promise.resolve(new Blob([new Uint8Array(found.bytes)], { type: found.mimeType }))
36
+ : fetch(source).then((response) => response.blob());
37
+
38
+ return blob.then(officeImageBitmap).then(
39
+ (bitmap): CanvasImageSource => bitmap,
40
+ () => (token ? placeholder : null),
41
+ );
42
+ };
43
+
44
+ const resolve: ImageResolver = (source) => {
45
+ if (!mediaToken.test(source) && !source.startsWith("blob:") && !source.startsWith("data:"))
46
+ return null;
47
+
48
+ const cached = cache.get(source);
49
+
50
+ if (cached) {
51
+ // Map order is drawing order: the least recently drawn come first.
52
+ cache.delete(source);
53
+ cache.set(source, cached);
54
+
55
+ return cached.image;
56
+ }
57
+
58
+ const entry: Decoded = {
59
+ image: decode(source).then((image) => {
60
+ if (image instanceof ImageBitmap) entry.bitmap = image;
61
+
62
+ return image;
63
+ }),
64
+ bitmap: undefined,
65
+ };
66
+
67
+ cache.set(source, entry);
68
+
69
+ return entry.image;
70
+ };
71
+
72
+ return {
73
+ resolve,
74
+ /** Closes the least recently drawn images past the budget. Call it between paints, never during one. */
75
+ trim() {
76
+ const size = (entry: Decoded) =>
77
+ entry.bitmap ? entry.bitmap.width * entry.bitmap.height * 4 : 0;
78
+
79
+ [...cache].reduce(
80
+ (total, [source, entry]) => {
81
+ if (total <= budget || !entry.bitmap) return total;
82
+
83
+ const freed = size(entry);
84
+
85
+ entry.bitmap.close();
86
+ cache.delete(source);
87
+
88
+ return total - freed;
89
+ },
90
+ [...cache.values()].reduce((total, entry) => total + size(entry), 0),
91
+ );
92
+ },
93
+ };
94
+}
95
+
96
+/** The grey box a missing image paints: one pixel the painter stretches over the image's place. */
97
+function greyBox() {
98
+ const canvas = new OffscreenCanvas(1, 1);
99
+ const context = canvas.getContext("2d");
100
+
101
+ if (!context) return null;
102
+
103
+ context.fillStyle = "#e6e6e6";
104
+ context.fillRect(0, 0, 1, 1);
105
+
106
+ return canvas;
107
+}
apps/web/src/components/files/office/word-protocol.ts
new
+87
@@ -0,0 +1,87 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import type { Method } from "./worker-rpc";
3
+
4
+// What the Word preview's window and its document worker say to each other. The window keeps only the page column, the
5
+// text layer's DOM and the painted bitmaps; the engine, its fonts, the layout and the painting live in the worker.
6
+
7
+/** Where a link in the document leads. */
8
+export type WordLink =
9
+ /** A web or mail address the system browser opens. */
10
+ | { readonly kind: "external"; readonly url: string }
11
+ /** A bookmark in the same document, such as a table of contents entry's heading. */
12
+ | { readonly kind: "internal"; readonly bookmark: string };
13
+
14
+/**
15
+ * One transparent piece of the text layer, in units that scale with the page: positions are fractions of the page and
16
+ * lengths are ems of `size`, so the layer follows any page width without being rebuilt.
17
+ */
18
+export type WordSpan = {
19
+ readonly text: string;
20
+ /** Left and top edges, as fractions of the page's width and height. */
21
+ readonly left: number;
22
+ readonly top: number;
23
+ /** The font size, as a fraction of the page's width. */
24
+ readonly size: number;
25
+ /** Stretches the layer font's natural width to the painted glyphs' width, about the left edge. */
26
+ readonly transform: string;
27
+ readonly dir: "ltr" | "rtl";
28
+ readonly link: WordLink | undefined;
29
+ readonly title: string | undefined;
30
+ /**
31
+ * What separates it from the next span in copied text: a line break between paragraphs, table cells and regions, a
32
+ * tab across a gap with no painted space, such as a tab stop or after a list number.
33
+ */
34
+ readonly after: "br" | "tab" | undefined;
35
+};
36
+
37
+/** What the page column needs to lay a page out before its content is built. */
38
+export type WordPageSize = {
39
+ readonly width: number;
40
+ readonly height: number;
41
+ readonly background: string | undefined;
42
+};
43
+
44
+/** The layer's line height, in ems: the height a painted line's glyph box takes, descenders included. */
45
+export const lineHeight = 1.2;
46
+
47
+/** The family the text layer measures and sets its text in; it stays transparent, so only its widths matter. */
48
+export const layerFont = "sans-serif";
49
+
50
+/** One step of the rest of the layout. */
51
+export type WordLayoutStep =
52
+ /** More of the document is left to lay out. */
53
+ | { readonly done: false }
54
+ /**
55
+ * The whole document is laid out. `kept` tells, per page, whether the page is the one shown so far, so its row and
56
+ * bitmap can stay; a page the full layout changed paints again.
57
+ */
58
+ | {
59
+ readonly done: true;
60
+ readonly pages: readonly WordPageSize[];
61
+ readonly kept: readonly boolean[];
62
+ };
63
+
64
+/** The document worker's methods. Every method but `open` needs a document `open` opened. */
65
+export type WordMethods = {
66
+ /** Opens the file's bytes and lays out its first pages; the reply lists them and whether more follow. */
67
+ readonly open: Method<
68
+ { readonly bytes: ArrayBuffer },
69
+ { readonly pages: readonly WordPageSize[]; readonly loading: boolean }
70
+ >;
71
+ /** Lays out a short step more of the document. */
72
+ readonly layout: Method<undefined, WordLayoutStep>;
73
+ /** Paints a page at `scale` page pixels per CSS pixel times `ratio` device pixels per CSS pixel. */
74
+ readonly paint: Method<
75
+ { readonly index: number; readonly scale: number; readonly ratio: number },
76
+ ImageBitmap | undefined
77
+ >;
78
+ /** Builds a page's content ahead of its paint. */
79
+ readonly build: Method<{ readonly index: number }, undefined>;
80
+ /** A page's text layer. */
81
+ readonly text: Method<{ readonly index: number }, readonly WordSpan[]>;
82
+ /** Where a bookmark sits in the pages laid out so far: its page and the height on it, in page pixels. */
83
+ readonly bookmark: Method<
84
+ { readonly name: string },
85
+ { readonly index: number; readonly y: number } | undefined
86
+ >;
87
+};
apps/web/src/components/files/office/word-text.ts
new
+297
@@ -0,0 +1,297 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import {
3
+ fontSizePxFromShorthand,
4
+ glyphRunRect,
5
+ textRunRect,
6
+ type DisplayPage,
7
+ type DisplayPrimitive,
8
+ type GeoRect,
9
+ type GlyphRunPrimitive,
10
+ type TextRunPrimitive,
11
+} from "@betteroffice/docx/layout/render";
12
+import { wordLink } from "./links";
13
+import { lineHeight, type WordSpan } from "./word-protocol";
14
+
15
+/** Measures text in the layer's font. */
16
+export type TextMeasure = {
17
+ /** The natural width of `text` at a font size of 1. */
18
+ readonly width: (text: string) => number;
19
+ /** The font's ascent and descent, at a font size of 1. */
20
+ readonly ascent: number;
21
+ readonly descent: number;
22
+};
23
+
24
+/**
25
+ * Builds a page's text layer from its display list: its header, body, notes and footer in reading order. Each glyph
26
+ * run's text sits over its painted glyphs, merged with its neighbours on the line while their text runs on, so
27
+ * selection, find and screen readers see whole words and lines.
28
+ */
29
+export function pageText(page: DisplayPage, measure: TextMeasure): WordSpan[] {
30
+ const body = page.primitives.slice(
31
+ Math.min(page.watermarkPrimitiveCount ?? 0, page.primitives.length),
32
+ );
33
+ const notes = (page.noteAreas ?? []).map((area) => area.primitives ?? []);
34
+
35
+ return [page.header?.primitives ?? [], body, ...notes, page.footer?.primitives ?? []].flatMap(
36
+ (region) => regionText(region, page, measure),
37
+ );
38
+}
39
+
40
+/**
41
+ * The page and height of the first body text at or after a document position, such as a bookmark's: the heading a
42
+ * table of contents entry points to. Undefined when no text follows it. A page whose content is not built yet is
43
+ * built through `build` only when its body reaches the position.
44
+ */
45
+export function positionTarget(
46
+ pages: readonly DisplayPage[],
47
+ position: number,
48
+ build: (index: number) => DisplayPage | undefined,
49
+) {
50
+ for (const [index, listed] of pages.entries()) {
51
+ const page = listed.unbuilt
52
+ ? (listed.positionSpan?.[1] ?? -1) >= position
53
+ ? build(index)
54
+ : undefined
55
+ : listed;
56
+ const first =
57
+ page && bodyAfter(page, position).toSorted((left, right) => left.start - right.start)[0];
58
+
59
+ if (first) return { index, y: first.y };
60
+ }
61
+
62
+ return undefined;
63
+}
64
+
65
+function bodyAfter(page: DisplayPage, position: number) {
66
+ return page.primitives.flatMap((primitive) => {
67
+ const piece = toPiece(primitive);
68
+
69
+ return piece?.start !== undefined && piece.start >= position
70
+ ? [{ start: piece.start, y: piece.rect.y }]
71
+ : [];
72
+ });
73
+}
74
+
75
+type Piece = {
76
+ readonly text: string;
77
+ readonly rect: GeoRect;
78
+ readonly baseline: number;
79
+ readonly size: number;
80
+ readonly dir: "ltr" | "rtl";
81
+ readonly href: string | undefined;
82
+ readonly title: string | undefined;
83
+ readonly rotation: number;
84
+ readonly line: string;
85
+ /** A list item's number or bullet, which Word follows with a tab. */
86
+ readonly marker: boolean;
87
+ readonly start: number | undefined;
88
+ readonly end: number | undefined;
89
+};
90
+
91
+function regionText(
92
+ primitives: readonly DisplayPrimitive[],
93
+ page: DisplayPage,
94
+ measure: TextMeasure,
95
+): WordSpan[] {
96
+ const lines = primitives
97
+ .flatMap((primitive) => {
98
+ const piece = toPiece(primitive);
99
+
100
+ return piece ? [piece] : [];
101
+ })
102
+ .reduce<Piece[][]>((groups, piece) => {
103
+ const line = groups.at(-1);
104
+ const first = line?.[0];
105
+
106
+ if (
107
+ line &&
108
+ first &&
109
+ first.line === piece.line &&
110
+ Math.abs(first.baseline - piece.baseline) < first.size * 0.6
111
+ ) {
112
+ line.push(piece);
113
+
114
+ return groups;
115
+ }
116
+
117
+ groups.push([piece]);
118
+
119
+ return groups;
120
+ }, [])
121
+ .map((line) => mergeLine(logical(line)));
122
+
123
+ return lines.flatMap((line, index) => {
124
+ const next = lines[index + 1]?.[0];
125
+ const last = line.at(-1);
126
+ // A line that wraps inside its paragraph runs on into the next: copied text joins them as one paragraph.
127
+ const wraps = !!next && last?.end !== undefined && next.start === last.end;
128
+
129
+ return line.map((piece, at) => {
130
+ const following = line[at + 1];
131
+
132
+ if (!following) return toSpan(piece, page, measure, wraps ? undefined : "br");
133
+
134
+ return toSpan(piece, page, measure, separated(piece, following) ? "tab" : undefined);
135
+ });
136
+ });
137
+}
138
+
139
+/** Neighbours on a line with a gap between them and no space on either side of it read as separate words. */
140
+function separated(previous: Piece, next: Piece) {
141
+ if (/\s$/u.test(previous.text) || /^\s/u.test(next.text)) return false;
142
+
143
+ // A number's painted width runs up to its text, over the tab between them.
144
+ if (previous.marker) return true;
145
+
146
+ const gap = Math.max(
147
+ next.rect.x - (previous.rect.x + previous.rect.w),
148
+ previous.rect.x - (next.rect.x + next.rect.w),
149
+ );
150
+
151
+ return gap > next.size * 0.35;
152
+}
153
+
154
+function toPiece(primitive: DisplayPrimitive): Piece | undefined {
155
+ if (primitive.kind === "glyphRun") return glyphPiece(primitive);
156
+
157
+ if (primitive.kind === "text") return textPiece(primitive);
158
+
159
+ return undefined;
160
+}
161
+
162
+function glyphPiece(primitive: GlyphRunPrimitive): Piece | undefined {
163
+ if (!primitive.text || primitive.glyphs.length === 0 || primitive.decorative) return undefined;
164
+
165
+ // Marks sit off the baseline with no advance; the first glyph that advances sits on it.
166
+ const base = primitive.glyphs.find((glyph) => glyph.advance) ?? primitive.glyphs[0];
167
+
168
+ return {
169
+ ...common(primitive),
170
+ text: primitive.text,
171
+ rect: glyphRunRect(primitive),
172
+ baseline: base?.y ?? 0,
173
+ size: primitive.size,
174
+ };
175
+}
176
+
177
+function textPiece(primitive: TextRunPrimitive): Piece | undefined {
178
+ if (!primitive.text || primitive.decorative) return undefined;
179
+
180
+ return {
181
+ ...common(primitive),
182
+ text: primitive.text,
183
+ rect: textRunRect(primitive),
184
+ baseline: primitive.baselineY,
185
+ size: fontSizePxFromShorthand(primitive.font),
186
+ };
187
+}
188
+
189
+function common(primitive: GlyphRunPrimitive | TextRunPrimitive) {
190
+ const link = wordLink(primitive.href);
191
+
192
+ return {
193
+ dir:
194
+ primitive.rtl || (primitive.bidiLevel ?? 0) % 2 === 1 ? ("rtl" as const) : ("ltr" as const),
195
+ href: link ? primitive.href : undefined,
196
+ title:
197
+ primitive.linkTitle ??
198
+ primitive.tooltip ??
199
+ (link?.kind === "external" ? link.url : undefined),
200
+ rotation: primitive.rotationDeg ?? 0,
201
+ line: `${primitive.lineIndex ?? ""}|${primitive.cell?.cellId ?? `${primitive.cell?.row ?? ""},${primitive.cell?.col ?? ""}`}`,
202
+ marker: primitive.listMarker ?? false,
203
+ start: primitive.docStart,
204
+ end: primitive.docEnd,
205
+ };
206
+}
207
+
208
+/** A line paints right-to-left runs in visual order; document positions restore the order they are read in. */
209
+function logical(line: Piece[]) {
210
+ if (line.some((piece) => piece.start === undefined)) return line;
211
+
212
+ return line.toSorted((left, right) => (left.start ?? 0) - (right.start ?? 0));
213
+}
214
+
215
+/**
216
+ * Joins pieces whose text runs on: same link, direction and size, next in the document and touching on the page. A wide
217
+ * gap, such as a tab or a justified space, starts a new span, so each span's text stays close to its glyphs.
218
+ */
219
+function mergeLine(line: Piece[]) {
220
+ return line.reduce<Piece[]>((merged, piece) => {
221
+ const previous = merged.at(-1);
222
+
223
+ if (!previous || !joins(previous, piece)) {
224
+ merged.push(piece);
225
+
226
+ return merged;
227
+ }
228
+
229
+ const left = Math.min(previous.rect.x, piece.rect.x);
230
+ const right = Math.max(previous.rect.x + previous.rect.w, piece.rect.x + piece.rect.w);
231
+
232
+ merged[merged.length - 1] = {
233
+ ...previous,
234
+ text: previous.text + piece.text,
235
+ rect: { ...previous.rect, x: left, w: right - left },
236
+ end: piece.end,
237
+ };
238
+
239
+ return merged;
240
+ }, []);
241
+}
242
+
243
+function joins(previous: Piece, piece: Piece) {
244
+ if (previous.marker || piece.marker) return false;
245
+
246
+ if (previous.href !== piece.href || previous.dir !== piece.dir || previous.title !== piece.title)
247
+ return false;
248
+
249
+ if (
250
+ previous.rotation !== 0 ||
251
+ piece.rotation !== 0 ||
252
+ Math.abs(previous.size - piece.size) > 0.01
253
+ )
254
+ return false;
255
+
256
+ if (previous.end === undefined || previous.end !== piece.start) return false;
257
+
258
+ const gap =
259
+ piece.dir === "rtl"
260
+ ? previous.rect.x - (piece.rect.x + piece.rect.w)
261
+ : piece.rect.x - (previous.rect.x + previous.rect.w);
262
+
263
+ return Math.abs(gap) < piece.size * 0.35;
264
+}
265
+
266
+function toSpan(
267
+ piece: Piece,
268
+ page: DisplayPage,
269
+ measure: TextMeasure,
270
+ after: WordSpan["after"],
271
+): WordSpan {
272
+ const natural = measure.width(piece.text);
273
+ const stretch = natural > 0 && piece.rect.w > 0 ? piece.rect.w / (natural * piece.size) : 1;
274
+ // The line box puts the baseline this many ems below its top.
275
+ const above = (lineHeight + measure.ascent - measure.descent) / 2;
276
+ const top = piece.baseline - piece.size * above;
277
+ const width = piece.rect.w / piece.size;
278
+ const middle = (piece.rect.y + piece.rect.h / 2 - top) / piece.size;
279
+
280
+ // A rotated run turns about its painted box's centre; ems keep the turn in step with the page's scale.
281
+ const rotation =
282
+ piece.rotation === 0
283
+ ? ""
284
+ : `translate(${width / 2}em, ${middle}em) rotate(${piece.rotation}deg) translate(${-width / 2}em, ${-middle}em) `;
285
+
286
+ return {
287
+ text: piece.text,
288
+ left: piece.rect.x / page.width,
289
+ top: top / page.height,
290
+ size: piece.size / page.width,
291
+ transform: `${rotation}scaleX(${stretch})`,
292
+ dir: piece.dir,
293
+ link: wordLink(piece.href),
294
+ title: piece.title,
295
+ after,
296
+ };
297
+}
apps/web/src/components/files/office/worker-rpc.ts
new
+292
@@ -0,0 +1,292 @@
1
+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+// The engines run in a worker per open file, so no layout, recalculation or painting holds the window. These are the
3
+// two ends of that worker's protocol: typed calls by method name, a key that lets a newer call replace a queued one
4
+// (as the markdown worker's queue does), transferable payloads, and a worker that fails every pending call when it dies.
5
+
6
+/** What one method takes and returns. */
7
+export type Method<Input, Output> = { readonly input: Input; readonly output: Output };
8
+
9
+/** A worker's methods by name. */
10
+export type Methods = { readonly [name: string]: Method<unknown, unknown> };
11
+
12
+type Request = {
13
+ readonly id: number;
14
+ readonly method: string;
15
+ readonly key?: string | undefined;
16
+ readonly input: unknown;
17
+};
18
+
19
+/** Withdraws a call whose caller aborted it. */
20
+type Cancel = { readonly cancel: number };
21
+
22
+type Response =
23
+ /** `transferred` lists the objects the reply moved, so a reply nobody waits for can close its bitmaps. */
24
+ | {
25
+ readonly id: number;
26
+ readonly ok: true;
27
+ readonly value: unknown;
28
+ readonly transferred: readonly Transferable[];
29
+ }
30
+ | {
31
+ readonly id: number;
32
+ readonly ok: false;
33
+ readonly superseded: boolean;
34
+ readonly message: string;
35
+ };
36
+
37
+/** A value a method returns with the buffers to move to the caller rather than copy. */
38
+export class Transfer<T> {
39
+ constructor(
40
+ readonly value: T,
41
+ readonly transfer: readonly Transferable[],
42
+ ) {}
43
+}
44
+
45
+/** A call that a newer call with the same key replaced before it ran. */
46
+export class SupersededError extends Error {}
47
+
48
+/** A call made after the worker failed or was closed, or pending when that happened. */
49
+class WorkerClosedError extends Error {}
50
+
51
+type CallOptions = {
52
+ /** A newer call with the same key replaces this one while it waits to run. */
53
+ readonly key?: string;
54
+ /** Buffers to move to the worker rather than copy, such as the file's bytes or a transferred canvas. */
55
+ readonly transfer?: readonly Transferable[];
56
+ /** Drops the reply and a call still queued; a call that has started sees its handler's signal abort. */
57
+ readonly signal?: AbortSignal;
58
+};
59
+
60
+/** A call waiting for its reply. */
61
+type Pending = {
62
+ readonly settle: (response: Response) => void;
63
+ readonly reject: (error: Error) => void;
64
+};
65
+
66
+/** The next call id, and why the worker stopped answering once it has. */
67
+type ClientState = { next: number; failure: Error | undefined };
68
+
69
+/** The window's end: starts the worker and calls its methods. */
70
+export function createWorkerClient<M extends Methods>(worker: Worker) {
71
+ const pending = new Map<number, Pending>();
72
+ const state: ClientState = { next: 0, failure: undefined };
73
+
74
+ const fail = (error: Error) => {
75
+ state.failure ??= error;
76
+ pending.forEach((call) => call.reject(error));
77
+ pending.clear();
78
+ worker.terminate();
79
+ };
80
+
81
+ worker.addEventListener("message", (event: MessageEvent<Response>) => {
82
+ const call = pending.get(event.data.id);
83
+
84
+ // A reply that crossed its call's cancel on the way: its bitmaps would hold their memory until collected.
85
+ if (!call) {
86
+ if (event.data.ok) closeBitmaps(event.data.transferred);
87
+
88
+ return;
89
+ }
90
+
91
+ pending.delete(event.data.id);
92
+ call.settle(event.data);
93
+ });
94
+
95
+ worker.addEventListener("error", (event) =>
96
+ fail(new WorkerClosedError(event.message || "The Office engine stopped")),
97
+ );
98
+ worker.addEventListener("messageerror", () =>
99
+ fail(new WorkerClosedError("The Office engine sent an unreadable reply")),
100
+ );
101
+
102
+ return {
103
+ call<K extends keyof M & string>(
104
+ method: K,
105
+ input: M[K]["input"],
106
+ options: CallOptions = {},
107
+ ): Promise<M[K]["output"]> {
108
+ if (state.failure) return Promise.reject(state.failure);
109
+
110
+ if (options.signal?.aborted)
111
+ return Promise.reject(new WorkerClosedError("The call was aborted"));
112
+
113
+ const id = ++state.next;
114
+
115
+ return new Promise<M[K]["output"]>((resolve, reject) => {
116
+ const timeout = setTimeout(
117
+ () =>
118
+ fail(
119
+ new WorkerClosedError(
120
+ "This document took too long to preview. Open it in another app.",
121
+ ),
122
+ ),
123
+ 30_000,
124
+ );
125
+ const abort = () => {
126
+ clearTimeout(timeout);
127
+ pending.delete(id);
128
+ reject(new WorkerClosedError("The call was aborted"));
129
+ worker.postMessage({ cancel: id } satisfies Cancel, []);
130
+ };
131
+
132
+ options.signal?.addEventListener("abort", abort, { once: true });
133
+ pending.set(id, {
134
+ settle: (response) => {
135
+ clearTimeout(timeout);
136
+ options.signal?.removeEventListener("abort", abort);
137
+
138
+ if (!response.ok)
139
+ return reject(
140
+ response.superseded
141
+ ? new SupersededError(response.message)
142
+ : new Error(response.message),
143
+ );
144
+
145
+ // SAFETY: the worker answers each id with the output of the method that id called (see `serveWorker`).
146
+ resolve(response.value as M[K]["output"]);
147
+ },
148
+ reject: (error) => {
149
+ clearTimeout(timeout);
150
+ options.signal?.removeEventListener("abort", abort);
151
+ reject(error);
152
+ },
153
+ });
154
+ worker.postMessage({ id, method, key: options.key, input } satisfies Request, [
155
+ ...(options.transfer ?? []),
156
+ ]);
157
+ });
158
+ },
159
+ /** Stops the worker, which frees its engine's memory, and fails every pending call. */
160
+ close() {
161
+ fail(new WorkerClosedError("The Office engine was closed"));
162
+ },
163
+ };
164
+}
165
+
166
+/** Whether a call runs, and which call it is, so its caller can abort it. */
167
+type ServerState = {
168
+ running: boolean;
169
+ current: { readonly id: number; readonly controller: AbortController } | undefined;
170
+};
171
+
172
+/**
173
+ * The worker's end: runs calls one at a time, in order, letting messages through between them. A handler's signal
174
+ * aborts when its caller aborts the call.
175
+ */
176
+export function serveWorker<M extends Methods>(handlers: {
177
+ readonly [K in keyof M]: (
178
+ input: M[K]["input"],
179
+ signal: AbortSignal,
180
+ ) =>
181
+ | M[K]["output"]
182
+ | Transfer<M[K]["output"]>
183
+ | Promise<M[K]["output"] | Transfer<M[K]["output"]>>;
184
+}) {
185
+ const queue: Request[] = [];
186
+
187
+ const state: ServerState = { running: false, current: undefined };
188
+
189
+ const reply = (response: Response, transfer: readonly Transferable[] = []) =>
190
+ self.postMessage(response, { transfer: [...transfer] });
191
+
192
+ const run = async () => {
193
+ if (state.running) return;
194
+
195
+ state.running = true;
196
+
197
+ // Each call returns to the event loop before it leaves the queue, so calls that arrived meanwhile can replace it.
198
+ while (queue.length > 0) {
199
+ await new Promise((resolve) => setTimeout(resolve));
200
+
201
+ const request = queue.shift();
202
+
203
+ if (!request) break;
204
+
205
+ const handler = handlers[request.method];
206
+ const controller = new AbortController();
207
+
208
+ state.current = { id: request.id, controller };
209
+
210
+ if (!handler) {
211
+ reply({
212
+ id: request.id,
213
+ ok: false,
214
+ superseded: false,
215
+ message: `Unknown method ${request.method}`,
216
+ });
217
+ continue;
218
+ }
219
+
220
+ // SAFETY: the client sends each method the input its `Methods` entry declares (see `createWorkerClient`).
221
+ const input = request.input as never;
222
+
223
+ await Promise.resolve()
224
+ .then(() => handler(input, controller.signal))
225
+ .then(
226
+ (result) => {
227
+ const transfer = result instanceof Transfer ? result.transfer : [];
228
+
229
+ // The caller already settled a call it aborted, so nothing would take the reply or its bitmaps.
230
+ if (controller.signal.aborted) return closeBitmaps(transfer);
231
+
232
+ reply(
233
+ {
234
+ id: request.id,
235
+ ok: true,
236
+ value: result instanceof Transfer ? result.value : result,
237
+ transferred: transfer,
238
+ },
239
+ transfer,
240
+ );
241
+ },
242
+ (cause: unknown) => {
243
+ if (controller.signal.aborted) return;
244
+
245
+ reply({
246
+ id: request.id,
247
+ ok: false,
248
+ superseded: false,
249
+ message: cause instanceof Error ? cause.message : String(cause),
250
+ });
251
+ },
252
+ );
253
+ }
254
+
255
+ state.running = false;
256
+ state.current = undefined;
257
+ };
258
+
259
+ self.addEventListener("message", (event: MessageEvent<Request | Cancel>) => {
260
+ // The caller already settled a cancelled call, so it gets no reply.
261
+ if ("cancel" in event.data) {
262
+ const id = event.data.cancel;
263
+ const queued = queue.findIndex((request) => request.id === id);
264
+
265
+ if (queued !== -1) queue.splice(queued, 1);
266
+
267
+ if (state.current?.id === id) state.current.controller.abort();
268
+
269
+ return;
270
+ }
271
+
272
+ const key = event.data.key;
273
+ const replaced = key === undefined ? -1 : queue.findIndex((request) => request.key === key);
274
+
275
+ if (replaced !== -1) {
276
+ const [old] = queue.splice(replaced, 1);
277
+
278
+ if (old)
279
+ reply({ id: old.id, ok: false, superseded: true, message: "Replaced by a newer call" });
280
+ }
281
+
282
+ queue.push(event.data);
283
+ void run();
284
+ });
285
+}
286
+
287
+/** Frees the bitmaps among objects that were moved for a reply nobody takes. */
288
+function closeBitmaps(transfer: readonly Transferable[]) {
289
+ transfer.forEach((item) => {
290
+ if (item instanceof ImageBitmap) item.close();
291
+ });
292
+}
apps/web/src/components/files/officeArchive.ts
new
+1190
@@ -0,0 +1,1190 @@
1
+import JSZip from "jszip";
2
+import { checkZipDirectory } from "./zipDirectory";
3
+import { SaxesParser } from "saxes";
4
+import { externalUrl } from "./office/links";
5
+
6
+import {
7
+ OFFICE_PREVIEW_MAX_BYTES,
8
+ OFFICE_PREVIEW_MAX_COLUMNS,
9
+ OFFICE_PREVIEW_MAX_ROWS,
10
+ type OfficeWorkerRequest,
11
+} from "./officePreviewProtocol";
12
+
13
+function xmlParser() {
14
+ const parser = new SaxesParser({ xmlns: true });
15
+ parser.on("doctype", () => {
16
+ throw new Error("This document contains unsupported XML declarations.");
17
+ });
18
+ return parser;
19
+}
20
+
21
+function officeXmlDecoder(bytes: Uint8Array) {
22
+ if ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0x3c && bytes[1] === 0))
23
+ return new TextDecoder("utf-16le");
24
+ if ((bytes[0] === 0xfe && bytes[1] === 0xff) || (bytes[0] === 0 && bytes[1] === 0x3c))
25
+ return new TextDecoder("utf-16be");
26
+ const declaration = new TextDecoder().decode(bytes.subarray(0, 256));
27
+ return new TextDecoder(/^<\?xml\s[^?]*\bencoding\s*=\s*["']([^"']+)["']/i.exec(declaration)?.[1]);
28
+}
29
+
30
+function officeXml(bytes: Uint8Array) {
31
+ // Repacked XML is UTF-8, regardless of the source part's encoding.
32
+ return officeXmlDecoder(bytes)
33
+ .decode(bytes)
34
+ .replace(/^(<\?xml\s[^?]*\bencoding\s*=\s*)["'][^"']+["']/i, '$1"UTF-8"');
35
+}
36
+
37
+// Section properties terminate the section they describe, so the kept prefix
38
+// may depend on a paragraph or body section beyond the retained input window.
39
+function wordSections() {
40
+ const parser = xmlParser();
41
+ const names: string[] = [];
42
+ const namespaceScopes: Record<string, string>[] = [];
43
+ const sections: { end: number; xml: string; body: boolean }[] = [];
44
+ let window = "";
45
+ let offset = 0;
46
+ let capture: {
47
+ start: number;
48
+ insert: number;
49
+ namespaces: string;
50
+ body: boolean;
51
+ depth: number;
52
+ } | null = null;
53
+ let bytes = 0;
54
+ let tags = 0;
55
+ let nextParagraph = false;
56
+ let paragraphSection = false;
57
+ const escape = (value: string) =>
58
+ value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<");
59
+ parser.on("opentag", (tag) => {
60
+ names.push(tag.local);
61
+ namespaceScopes.push(tag.ns);
62
+ if (names.length > 64) throw new Error("This Word document has excessive XML nesting.");
63
+ const body = names.length === 3 && names[1] === "body";
64
+ if (
65
+ tag.local === "sectPr" &&
66
+ tag.uri === "http://schemas.openxmlformats.org/wordprocessingml/2006/main" &&
67
+ (body || (names.length === 5 && names[2] === "p" && names[3] === "pPr" && !nextParagraph))
68
+ ) {
69
+ let namespaces = "";
70
+ const scope = Object.assign({}, ...namespaceScopes) as Record<string, string>;
71
+ for (const prefix in scope) {
72
+ const name = prefix ? `xmlns:${prefix}` : "xmlns";
73
+ if (prefix !== "xml" && !tag.attributes[name])
74
+ namespaces += ` ${name}="${escape(scope[prefix]!)}"`;
75
+ }
76
+ const start = window.lastIndexOf("<", parser.position - offset - 1);
77
+ if (start < 0) throw new Error("This Word document has too much section markup.");
78
+ capture = {
79
+ start: start + offset,
80
+ insert: parser.position - (tag.isSelfClosing ? 2 : 1),
81
+ namespaces,
82
+ body,
83
+ depth: names.length,
84
+ };
85
+ }
86
+ if (capture && ++tags > 2_000)
87
+ throw new Error("Preview limited: this Word document has too much section markup.");
88
+ });
89
+ parser.on("closetag", (tag) => {
90
+ if (capture && tag.local === "sectPr" && names.length === capture.depth) {
91
+ const xml =
92
+ window.slice(capture.start - offset, capture.insert - offset) +
93
+ capture.namespaces +
94
+ window.slice(capture.insert - offset, parser.position - offset);
95
+ bytes += xml.length;
96
+ if (bytes > 128 * 1024)
97
+ throw new Error("Preview limited: this Word document has too much section markup.");
98
+ sections.push({ end: parser.position, xml, body: capture.body });
99
+ paragraphSection = !capture.body;
100
+ if (!capture.body && parser.position > 4 * 1024 * 1024) nextParagraph = true;
101
+ capture = null;
102
+ }
103
+ if (names.length === 3 && tag.local === "p" && paragraphSection) {
104
+ sections[sections.length - 1]!.end = parser.position;
105
+ paragraphSection = false;
106
+ }
107
+ names.pop();
108
+ namespaceScopes.pop();
109
+ });
110
+ return {
111
+ write(chunk: string) {
112
+ window += chunk;
113
+ parser.write(chunk);
114
+ if (capture && parser.position - capture.start > 128 * 1024)
115
+ throw new Error("Preview limited: this Word document has too much section markup.");
116
+ const keep = capture?.start ?? Math.max(offset, parser.position - 128 * 1024);
117
+ window = window.slice(keep - offset);
118
+ offset = keep;
119
+ },
120
+ finish() {
121
+ parser.close();
122
+ return sections;
123
+ },
124
+ };
125
+}
126
+
127
+// Keep whole body elements so every prefix and render batch is valid Word XML.
128
+// Individual tables/paragraphs are bounded too: one giant element must not
129
+// bypass the budget between yields on the main thread.
130
+function wordDocuments(
131
+ xml: string,
132
+ incomplete: boolean,
133
+ sections: ReturnType<ReturnType<typeof wordSections>["finish"]>,
134
+) {
135
+ const parser = xmlParser();
136
+ const names: string[] = [];
137
+ const batches: { content: string; end: number }[] = [];
138
+ let prefix = "";
139
+ let suffix = "";
140
+ let boundary = 0;
141
+ let batchStart = 0;
142
+ let tags = 0;
143
+ let elementTags = 0;
144
+ let batchTags = 0;
145
+ let elements = 0;
146
+ let truncated = incomplete;
147
+ const limit = Symbol("Word preview limit");
148
+ parser.on("opentag", (tag) => {
149
+ names.push(tag.name);
150
+ if (names.length === 2 && tag.local === "body") {
151
+ prefix = xml.slice(0, parser.position).replace(/\/>$/, ">");
152
+ suffix = `</${tag.name}></${names[0]}>`;
153
+ boundary = batchStart = parser.position;
154
+ } else if (prefix && names.length > 2) {
155
+ if (names.length === 3 && ++elements > 5_000) throw limit;
156
+ tags++;
157
+ elementTags++;
158
+ batchTags++;
159
+ if (tags > 100_000 || elementTags > 2_000 || parser.position - boundary > 128 * 1024)
160
+ throw limit;
161
+ }
162
+ if (names.length > 64) throw limit;
163
+ });
164
+ parser.on("closetag", (tag) => {
165
+ if (prefix && names.length === 3 && tag.local !== "sectPr") {
166
+ if (parser.position - prefix.length > 3 * 1024 * 1024) throw limit;
167
+ boundary = parser.position;
168
+ elementTags = 0;
169
+ if (batchTags >= 500) {
170
+ batches.push({ content: xml.slice(batchStart, boundary), end: boundary });
171
+ batchStart = boundary;
172
+ batchTags = 0;
173
+ }
174
+ }
175
+ names.pop();
176
+ });
177
+ try {
178
+ for (let offset = 0; offset < xml.length; offset += 16 * 1024) {
179
+ parser.write(xml.slice(offset, offset + 16 * 1024));
180
+ if (prefix && parser.position - boundary > 128 * 1024) throw limit;
181
+ }
182
+ if (!incomplete) parser.close();
183
+ } catch (cause) {
184
+ if (cause !== limit) throw cause;
185
+ truncated = true;
186
+ }
187
+ if (!prefix) throw new Error("This Word document has no readable body.");
188
+ if (boundary > batchStart || batches.length === 0)
189
+ batches.push({ content: xml.slice(batchStart, boundary), end: boundary });
190
+ const documents: string[] = [];
191
+ let length = 0;
192
+ let markup = 0;
193
+ for (const batch of batches) {
194
+ const section = sections.find((section) => section.body || section.end >= batch.end);
195
+ const document = prefix + batch.content + (section?.xml ?? "") + suffix;
196
+ length += batch.content.length;
197
+ markup += batch.content.match(/<(?![!?/])/g)?.length ?? 0;
198
+ if (length > 3 * 1024 * 1024 || markup > 100_000) {
199
+ truncated = true;
200
+ break;
201
+ }
202
+ documents.push(document);
203
+ }
204
+ if (documents.length === 0) throw new Error("This Word document has too much section markup.");
205
+ return { documents, truncated };
206
+}
207
+
208
+function boundedWorksheet(xml: string, strings: readonly string[], budget: { remaining: number }) {
209
+ const parser = xmlParser();
210
+ const rows = new Map<number, Map<number, string>>();
211
+ const rowTags = new Map<number, string>();
212
+ const metadataAttributes = new Map<
213
+ string,
214
+ { ref: string | undefined; min: string | undefined; max: string | undefined }
215
+ >();
216
+ let dataStart = 0;
217
+ let dataEnd = 0;
218
+ let emptyData = false;
219
+ let depth = 0;
220
+ let row = 0;
221
+ let explicitRow = false;
222
+ let rowTag = "";
223
+ let column = 0;
224
+ let cells = new Map<number, string>();
225
+ let cell: {
226
+ start: number;
227
+ opening: string;
228
+ name: string;
229
+ prefix: string;
230
+ selfClosing: boolean;
231
+ text: string;
232
+ value: string;
233
+ reading: string;
234
+ shared: boolean;
235
+ } | null = null;
236
+ let truncated = false;
237
+ const coordinate = (ref: string) => {
238
+ const match = /^([A-Z]{1,3})([1-9]\d{0,6})$/.exec(ref);
239
+ if (!match) throw new Error("This workbook contains invalid cell coordinates.");
240
+ let col = 0;
241
+ for (const letter of match[1]!) col = col * 26 + letter.charCodeAt(0) - 64;
242
+ const line = Number(match[2]);
243
+ if (col > 16384 || line > 1048576)
244
+ throw new Error("This workbook contains invalid worksheet dimensions.");
245
+ return { col, line };
246
+ };
247
+ parser.on("opentag", (tag) => {
248
+ depth++;
249
+ if (depth > 64) throw new Error("This workbook contains excessive XML nesting.");
250
+ if (
251
+ (tag.local === "row" && depth !== 3) ||
252
+ (tag.local === "c" && depth !== 4) ||
253
+ ((tag.local === "dimension" || tag.local === "sheetData") && depth !== 2)
254
+ )
255
+ throw new Error("This workbook contains invalid worksheet structure.");
256
+ const attribute = (name: string) => tag.attributes[name]?.value;
257
+ if (["dimension", "mergeCell", "col"].includes(tag.local))
258
+ metadataAttributes.set(
259
+ xml.slice(xml.lastIndexOf("<", parser.position - 1), parser.position),
260
+ {
261
+ ref: attribute("ref"),
262
+ min: attribute("min"),
263
+ max: attribute("max"),
264
+ },
265
+ );
266
+ if (depth === 2 && tag.local === "sheetData") {
267
+ dataStart = parser.position;
268
+ emptyData = tag.isSelfClosing;
269
+ }
270
+ if (depth === 2 && tag.local === "dimension") {
271
+ for (const ref of (attribute("ref") ?? "").split(":")) {
272
+ const { col, line } = coordinate(ref);
273
+ if (col > OFFICE_PREVIEW_MAX_COLUMNS || line > OFFICE_PREVIEW_MAX_ROWS) truncated = true;
274
+ }
275
+ } else if (depth === 3 && tag.local === "row") {
276
+ explicitRow = attribute("r") !== undefined;
277
+ row = attribute("r") === undefined ? row + 1 : Number(attribute("r"));
278
+ if (!Number.isInteger(row) || row < 1 || row > 1048576)
279
+ throw new Error("This workbook contains invalid row coordinates.");
280
+ rowTag = xml
281
+ .slice(xml.lastIndexOf("<", parser.position - 1), parser.position)
282
+ .replace(/\/>$/, ">");
283
+ column = 0;
284
+ cells = rows.get(row) ?? new Map<number, string>();
285
+ if (row > OFFICE_PREVIEW_MAX_ROWS) truncated = true;
286
+ } else if (depth === 4 && tag.local === "c") {
287
+ const ref = attribute("r");
288
+ const position = ref ? coordinate(ref) : { col: column + 1, line: row };
289
+ if (!explicitRow && column === 0) row = position.line;
290
+ column = position.col;
291
+ if (row < 1 || position.line !== row)
292
+ throw new Error("This workbook contains inconsistent cell rows.");
293
+ if (row > OFFICE_PREVIEW_MAX_ROWS || column > OFFICE_PREVIEW_MAX_COLUMNS) {
294
+ truncated = true;
295
+ return;
296
+ }
297
+ // Explicit coordinates also bound sheets whose rows/cells omit r.
298
+ const letters =
299
+ column <= 26 ? String.fromCharCode(64 + column) : `A${String.fromCharCode(38 + column)}`;
300
+ const style = attribute("s");
301
+ const type = attribute("t");
302
+ if ((style && !/^\d{1,6}$/.test(style)) || (type && !/^[a-zA-Z]+$/.test(type)))
303
+ throw new Error("This workbook contains invalid cell metadata.");
304
+ cell = {
305
+ start: parser.position,
306
+ opening: xml
307
+ .slice(xml.lastIndexOf("<", parser.position - 1), parser.position)
308
+ .replace(/\/?>$/, `${ref ? "" : ` r="${letters}${row}"`}>`),
309
+ name: tag.name,
310
+ prefix: tag.prefix ? `${tag.prefix}:` : "",
311
+ selfClosing: tag.isSelfClosing,
312
+ text: "",
313
+ value: "",
314
+ reading: "",
315
+ shared: type === "s",
316
+ };
317
+ }
318
+ if (cell && (tag.local === "t" || tag.local === "v")) cell.reading = tag.local;
319
+ });
320
+ const readCellText = (chunk: string) => {
321
+ if (cell?.reading === "t") cell.text += chunk;
322
+ if (cell?.reading === "v") cell.value += chunk;
323
+ };
324
+ parser.on("text", readCellText);
325
+ parser.on("cdata", readCellText);
326
+ parser.on("closetag", (tag) => {
327
+ if (depth === 4 && tag.local === "c" && cell) {
328
+ const end = cell.selfClosing ? cell.start : xml.lastIndexOf("<", parser.position - 1);
329
+ const raw = cell.opening + xml.slice(cell.start, end) + `</${cell.name}>`;
330
+ const shown = cell.shared ? (strings[Number(cell.value)] ?? "") : cell.text || cell.value;
331
+ const kept = shown.slice(0, Math.min(4096, budget.remaining));
332
+ budget.remaining -= kept.length;
333
+ if (kept.length < shown.length) {
334
+ truncated = true;
335
+ const escape = (s: string) =>
336
+ s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
337
+ cells.set(
338
+ column,
339
+ cell.opening
340
+ .replace(/\s+t\s*=\s*(?:"[^"]*"|'[^']*')/, "")
341
+ .replace(/>$/, ' t="inlineStr">') +
342
+ `<${cell.prefix}is><${cell.prefix}t>` +
343
+ escape(kept) +
344
+ `</${cell.prefix}t></${cell.prefix}is></${cell.name}>`,
345
+ );
346
+ } else cells.set(column, raw);
347
+ cell = null;
348
+ } else if (depth === 3 && tag.local === "row" && row <= OFFICE_PREVIEW_MAX_ROWS) {
349
+ rows.set(row, cells);
350
+ rowTags.set(row, rowTag);
351
+ }
352
+ if (depth === 2 && tag.local === "sheetData")
353
+ dataEnd = emptyData ? parser.position : xml.lastIndexOf("<", parser.position - 1);
354
+ if (cell?.reading === tag.local) cell.reading = "";
355
+ depth--;
356
+ });
357
+ parser.write(xml).close();
358
+ if (!dataStart) throw new Error("This workbook has no worksheet data.");
359
+ const boundRange = (ref: string) => {
360
+ const [a, b = a] = ref.split(":");
361
+ const first = coordinate(a!);
362
+ const last = coordinate(b!);
363
+ if (first.col > 50 || first.line > 500) return "";
364
+ const col = Math.min(50, last.col);
365
+ const letters = col <= 26 ? String.fromCharCode(64 + col) : "A" + String.fromCharCode(38 + col);
366
+ return a + ":" + letters + Math.min(500, last.line);
367
+ };
368
+ const metadata = (part: string) =>
369
+ part.replace(
370
+ /(<((?:\w+:)?(?:dimension|mergeCell|col))\b(?:[^"'<>]|"[^"]*"|'[^']*')*>)(?:\s*<\/\2\s*>)?/g,
371
+ (tag: string, opening: string) => {
372
+ const attributes = metadataAttributes.get(opening);
373
+ if (!attributes) return tag;
374
+ const replace = (name: string, value: string) => {
375
+ const pattern = new RegExp(`\\s${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`);
376
+ tag = pattern.test(tag)
377
+ ? tag.replace(pattern, ` ${name}="${value}"`)
378
+ : tag.replace(/\/?>/, (end) => ` ${name}="${value}"${end}`);
379
+ };
380
+ if (attributes.ref !== undefined) {
381
+ const bounded = boundRange(attributes.ref);
382
+ if (!bounded) return "";
383
+ replace("ref", bounded);
384
+ }
385
+ if (/<(?:\w+:)?col\b/.test(opening)) {
386
+ const min = Math.max(1, Number(attributes.min ?? 1));
387
+ const max = Math.min(OFFICE_PREVIEW_MAX_COLUMNS, Number(attributes.max ?? 16384));
388
+ if (!Number.isInteger(min) || !Number.isInteger(max) || min > max) return "";
389
+ replace("min", String(min));
390
+ replace("max", String(max));
391
+ }
392
+ return tag;
393
+ },
394
+ );
395
+ return {
396
+ xml: emptyData
397
+ ? metadata(xml)
398
+ : `${metadata(xml.slice(0, dataStart))}${[...rows]
399
+ .sort(([a], [b]) => a - b)
400
+ .map(
401
+ ([line, values]) =>
402
+ `${rowTags.get(line) ?? `<row r="${line}">`}${[...values]
403
+ .sort(([a], [b]) => a - b)
404
+ .map(([, value]) => value)
405
+ .join("")}</${/^<([^\s>]+)/.exec(rowTags.get(line) ?? "<row>")![1]}>`,
406
+ )
407
+ .join("")}${metadata(xml.slice(dataEnd))}`,
408
+ truncated,
409
+ };
410
+}
411
+
412
+async function boundWorkbook(archive: JSZip) {
413
+ const paths = new Map<string, string>();
414
+ let sharedPath = "xl/sharedStrings.xml";
415
+ const relationships = xmlParser();
416
+ relationships.on("opentag", (tag) => {
417
+ if (tag.local !== "Relationship") return;
418
+ const type = tag.attributes.Type?.value;
419
+ const path = new URL(
420
+ tag.attributes.Target?.value ?? "",
421
+ "https://docx.invalid/xl/workbook.xml",
422
+ ).pathname.slice(1);
423
+ if (type?.endsWith("/worksheet")) paths.set(tag.attributes.Id?.value ?? "", path);
424
+ if (type?.endsWith("/sharedStrings")) sharedPath = path;
425
+ });
426
+ relationships
427
+ .write((await archive.file("xl/_rels/workbook.xml.rels")?.async("string")) ?? "")
428
+ .close();
429
+ const sheetPaths: string[] = [];
430
+ const workbook = xmlParser();
431
+ workbook.on("opentag", (tag) => {
432
+ if (tag.local !== "sheet") return;
433
+ const id = Object.values(tag.attributes).find((attribute) => attribute.local === "id")?.value;
434
+ const path = paths.get(id ?? "");
435
+ if (!path || sheetPaths.length === 100)
436
+ throw new Error("This workbook has invalid or too many sheets.");
437
+ sheetPaths.push(path);
438
+ });
439
+ workbook.write((await archive.file("xl/workbook.xml")?.async("string")) ?? "").close();
440
+ const strings: string[] = [];
441
+ const shared = await archive.file(sharedPath)?.async("string");
442
+ if (shared) {
443
+ const parser = xmlParser();
444
+ let text = "";
445
+ let reading = false;
446
+ parser.on("opentag", (tag) => {
447
+ if (tag.local === "si") text = "";
448
+ if (tag.local === "t") reading = true;
449
+ });
450
+ const readSharedText = (chunk: string) => {
451
+ if (reading) text += chunk;
452
+ };
453
+ parser.on("text", readSharedText);
454
+ parser.on("cdata", readSharedText);
455
+ parser.on("closetag", (tag) => {
456
+ if (tag.local === "t") reading = false;
457
+ if (tag.local === "si") strings.push(text);
458
+ });
459
+ parser.write(shared).close();
460
+ }
461
+ const budget = { remaining: 1024 * 1024 };
462
+ const limited = new Map<string, boolean>();
463
+ for (const path of new Set(sheetPaths)) {
464
+ const file = archive.file(path);
465
+ if (!file) throw new Error("This workbook has a missing worksheet.");
466
+ const sheet = boundedWorksheet(await file.async("string"), strings, budget);
467
+ archive.file(path, sheet.xml);
468
+ limited.set(path, sheet.truncated);
469
+ }
470
+ return sheetPaths.map((path) => limited.get(path) ?? false);
471
+}
472
+
473
+const WORD_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
474
+const WORD_EXPANDED_PARTS = new Set(["footnotes", "endnotes", "comments", "header", "footer"]);
475
+const WORD_DISABLED_PARTS = new Set(["commentsExtended", "fontTable", "aFChunk"]);
476
+const WORD_BINARY_PARTS = new Set([
477
+ "image",
478
+ "font",
479
+ "thumbnail",
480
+ "audio",
481
+ "video",
482
+ "oleObject",
483
+ "package",
484
+ "printerSettings",
485
+ "vbaProject",
486
+ "origin",
487
+ "certificate",
488
+ // Package metadata can point to binary payloads; explicit XML still wins below.
489
+ "core-properties",
490
+ "extended-properties",
491
+ "custom-properties",
492
+ "signature",
493
+]);
494
+
495
+function wordPartTypes() {
496
+ const defaults = new Map<string, string>();
497
+ const overrides = new Map<string, string>();
498
+ const xmlParts = new Set([
499
+ "word/document.xml",
500
+ "docProps/app.xml",
501
+ "docProps/core.xml",
502
+ "docProps/custom.xml",
503
+ ]);
504
+ const roles = new Map<string, Set<string>>();
505
+ const relationships = new Map<string, Map<string, string>>();
506
+ return {
507
+ roles,
508
+ relationships,
509
+ binary(path: string) {
510
+ const extension = path.split(".").at(-1)?.toLowerCase() ?? "";
511
+ const type = overrides.get(path) ?? defaults.get(extension) ?? "";
512
+ // An XML relationship always wins over a misleading media content type.
513
+ if (
514
+ path === "[Content_Types].xml" ||
515
+ extension === "rels" ||
516
+ extension === "xml" ||
517
+ xmlParts.has(path) ||
518
+ /(?:\+xml|\/xml)$/i.test(type)
519
+ )
520
+ return false;
521
+ return (
522
+ [...(roles.get(path) ?? [])].some((role) => WORD_BINARY_PARTS.has(role)) ||
523
+ /^(?:image|audio|video|font)\//i.test(type) ||
524
+ /^(?:png|jpe?g|gif|webp|bmp|tiff?|ico|bin|sigs|cer|ttf|otf|odttf|woff2?)$/.test(
525
+ extension,
526
+ ) ||
527
+ type === "application/octet-stream" ||
528
+ type === "application/vnd.openxmlformats-package.digital-signature-origin"
529
+ );
530
+ },
531
+ metadata(path: string, xml: string) {
532
+ const parser = xmlParser();
533
+ const removed: { start: number; end: number }[] = [];
534
+ let start = -1;
535
+ parser.on("opentag", (tag) => {
536
+ const attr = (name: string) => tag.attributes[name]?.value ?? "";
537
+ if (path === "[Content_Types].xml") {
538
+ if (tag.local === "Default")
539
+ defaults.set(attr("Extension").toLowerCase(), attr("ContentType"));
540
+ if (tag.local === "Override")
541
+ overrides.set(attr("PartName").replace(/^\//, ""), attr("ContentType"));
542
+ }
543
+ if (tag.local !== "Relationship" || !path.endsWith(".rels")) return;
544
+ const type = attr("Type");
545
+ const role = type.slice(type.lastIndexOf("/") + 1);
546
+ const external =
547
+ attr("TargetMode").toLowerCase() === "external" ||
548
+ /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(attr("Target"));
549
+ const folder = path === "_rels/.rels" ? "" : path.replace(/_rels\/[^/]+\.rels$/, "");
550
+ // Preserve archive URL resolution, including literal query/fragment
551
+ // characters in ZIP names rather than silently classifying another file.
552
+ const target = new URL(attr("Target"), `https://docx.invalid/${folder}`)
553
+ .toString()
554
+ .slice("https://docx.invalid/".length);
555
+ if (!external) {
556
+ if (
557
+ !WORD_BINARY_PARTS.has(role) &&
558
+ role !== "hyperlink" &&
559
+ (type.startsWith(WORD_RELATIONSHIP) ||
560
+ role === "core-properties" ||
561
+ role === "signature")
562
+ )
563
+ xmlParts.add(target);
564
+ const types = roles.get(target) ?? new Set<string>();
565
+ types.add(role);
566
+ roles.set(target, types);
567
+ const owner = path === "_rels/.rels" ? "" : path.replace(/_rels\/([^/]+)\.rels$/, "$1");
568
+ const refs = relationships.get(owner) ?? new Map<string, string>();
569
+ if (!refs.has(attr("Id"))) refs.set(attr("Id"), target);
570
+ relationships.set(owner, refs);
571
+ if (target === "word/document.xml" && role !== "officeDocument")
572
+ throw new Error("Preview limited: this Word document has an aliased document part.");
573
+ if (type === WORD_RELATIONSHIP + "officeDocument" && target !== "word/document.xml")
574
+ throw new Error(
575
+ "Preview limited: this Word document has an unsupported document relationship.",
576
+ );
577
+ }
578
+ if (
579
+ (external && !(role === "hyperlink" && externalUrl(attr("Target")))) ||
580
+ WORD_DISABLED_PARTS.has(role)
581
+ ) {
582
+ start = xml.lastIndexOf("<", parser.position - 1);
583
+ }
584
+ });
585
+ parser.on("closetag", (tag) => {
586
+ if (tag.local === "Relationship" && start >= 0) {
587
+ removed.push({ start, end: parser.position });
588
+ start = -1;
589
+ }
590
+ });
591
+ parser.write(xml).close();
592
+ for (const range of removed.toReversed())
593
+ xml = xml.slice(0, range.start) + xml.slice(range.end);
594
+ return xml;
595
+ },
596
+ };
597
+}
598
+
599
+// Bound inherited style and numbering expansion before the engine loads it.
600
+// Picture bullets can duplicate embedded images, so omit those definitions.
601
+const WORD_STYLE_MAX_BYTES = 1024 * 1024;
602
+const WORD_STYLE_MAX_UNITS = 20_000;
603
+
604
+function wordXmlCost(xml: string, roles: Set<string> | undefined) {
605
+ const parser = xmlParser();
606
+ let depth = 0;
607
+ let markup = 0;
608
+ const limit = Symbol("Word style budget");
609
+ const exceeded = { bytes: Infinity, markup: Infinity, pictures: false };
610
+ let styleCount = 0;
611
+ let ownUnits = 0;
612
+ const styles = new Map<
613
+ string,
614
+ { properties: Map<string, number>; base: string; linked: string }
615
+ >();
616
+ let style: { id: string; base: string; linked: string; properties: Map<string, number> } | null =
617
+ null;
618
+ const names: string[] = [];
619
+ const definitions = new Map<string, { bytes: number; markup: number }>();
620
+ const references: { id: string; selector: number }[] = [];
621
+ let definition: { id: string; start: number; markup: number } | null = null;
622
+ let reference: { id: string; selector: number } | null = null;
623
+ let pictures = false;
624
+ parser.on("opentag", (tag) => {
625
+ if (++depth > 64)
626
+ throw new Error("Preview limited: this Word document has excessive XML nesting.");
627
+ markup++;
628
+ const attr = (name: string) =>
629
+ Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";
630
+ names.push(tag.local === "tblStylePr" ? `${tag.local}:${attr("type")}` : tag.local);
631
+ if (roles?.has("styles") && (tag.local === "style" || tag.local === "docDefaults")) {
632
+ if (++styleCount > 1_024 || attr("styleId").length > 256) throw limit;
633
+ style = { id: attr("styleId"), properties: new Map(), base: "", linked: "" };
634
+ }
635
+ if (style) {
636
+ if (tag.local === "basedOn") style.base = attr("val");
637
+ else if (tag.local === "link") style.linked = attr("val");
638
+ else if (names.length > 2 && tag.local !== "name") {
639
+ const key = names.slice(2).join("/");
640
+ const size = new TextEncoder().encode(
641
+ xml.slice(xml.lastIndexOf("<", parser.position - 1), parser.position),
642
+ ).length;
643
+ if (++ownUnits > WORD_STYLE_MAX_UNITS) throw limit;
644
+ style.properties.set(key, size);
645
+ }
646
+ }
647
+ if (roles?.has("numbering")) {
648
+ if (tag.local === "abstractNum")
649
+ definition = {
650
+ id: attr("abstractNumId"),
651
+ start: xml.lastIndexOf("<", parser.position - 1),
652
+ markup: markup - 1,
653
+ };
654
+ if (tag.local === "num") {
655
+ if (references.length >= 2_000) throw limit;
656
+ reference = { id: "", selector: attr("numId").length + 32 };
657
+ references.push(reference);
658
+ }
659
+ if (tag.local === "abstractNumId" && reference) reference.id = attr("val");
660
+ }
661
+ if (tag.local === "numPicBullet") pictures = true;
662
+ });
663
+ parser.on("closetag", (tag) => {
664
+ if (definition && tag.local === "abstractNum") {
665
+ const previous = definitions.get(definition.id);
666
+ definitions.set(definition.id, {
667
+ bytes:
668
+ (previous?.bytes ?? 0) +
669
+ new TextEncoder().encode(xml.slice(definition.start, parser.position)).length,
670
+ markup: (previous?.markup ?? 0) + markup - definition.markup,
671
+ });
672
+ definition = null;
673
+ }
674
+ if (tag.local === "num") reference = null;
675
+ if (style && (tag.local === "style" || tag.local === "docDefaults")) {
676
+ styles.set(style.id, style);
677
+ style = null;
678
+ }
679
+ names.pop();
680
+ depth--;
681
+ });
682
+ try {
683
+ parser.write(xml).close();
684
+ } catch (cause) {
685
+ if (cause !== limit) throw cause;
686
+ return exceeded;
687
+ }
688
+ const rawBytes = new TextEncoder().encode(xml).length;
689
+ if (roles?.has("styles")) {
690
+ // Immutable parent pointers match processStyles' ordered merges (including
691
+ // forward links and cycles) without copying an expanding property map.
692
+ type Resolved = {
693
+ properties: Map<string, number>;
694
+ parent?: Resolved | undefined;
695
+ depth: number;
696
+ };
697
+ const resolved = new Map<string, Resolved>();
698
+ for (const [id, style] of styles) resolved.set(id, { properties: style.properties, depth: 1 });
699
+ for (const [id, style] of styles) {
700
+ const parent = style.base ? resolved.get(style.base) : undefined;
701
+ if (parent && parent.depth >= 32) return exceeded;
702
+ resolved.set(id, { properties: style.properties, parent, depth: (parent?.depth ?? 0) + 1 });
703
+ }
704
+ let bytes = 0;
705
+ let expandedMarkup = 0;
706
+ let visited = 0;
707
+ let propertyVisits = 0;
708
+ for (const [id, style] of styles) {
709
+ for (const root of [
710
+ resolved.get(id),
711
+ style.linked ? resolved.get(style.linked) : undefined,
712
+ ]) {
713
+ const seen = new Set<string>();
714
+ for (let node = root; node; node = node.parent) {
715
+ if (++visited > 8_192) return exceeded;
716
+ for (const [key, size] of node.properties) {
717
+ if (++propertyVisits > 100_000) return exceeded;
718
+ if (seen.has(key)) continue;
719
+ // Latent styles never enter properties. Charge each own property
720
+ // once per resolved style, including linked and default selectors.
721
+ const copies = id ? 1 : 2;
722
+ bytes += (size * 2 + id.length + 32) * copies;
723
+ expandedMarkup += copies;
724
+ if (bytes > WORD_STYLE_MAX_BYTES || expandedMarkup > WORD_STYLE_MAX_UNITS)
725
+ return exceeded;
726
+ seen.add(key);
727
+ }
728
+ }
729
+ }
730
+ }
731
+ return { bytes, markup: expandedMarkup, pictures };
732
+ }
733
+ let bytes = rawBytes;
734
+ if (roles?.has("numbering")) {
735
+ for (const ref of references) {
736
+ const cost = definitions.get(ref.id);
737
+ if (!cost) continue;
738
+ bytes += cost.bytes * 2 + cost.markup * ref.selector;
739
+ markup += cost.markup;
740
+ if (bytes > 128 * 1024 || markup > 2_000) return exceeded;
741
+ }
742
+ }
743
+ return { bytes, markup, pictures };
744
+}
745
+
746
+// Layout can repeat notes at references and headers/footers across pages.
747
+// Charge those copies, not just the XML that defines them.
748
+async function wordExpansion(
749
+ archive: JSZip,
750
+ parts: ReturnType<typeof wordPartTypes>,
751
+ mediaSizes: Map<string, number>,
752
+ auxiliaryCosts: Map<string, { bytes: number; markup: number }>,
753
+ documents: string[],
754
+) {
755
+ type Cost = { bytes: number; markup: number; media: number; images: Set<string> };
756
+ const empty = (): Cost => ({ bytes: 0, markup: 0, media: 0, images: new Set() });
757
+ const nodes = new Map<string, { xml: string; path: string }>();
758
+ const optional = new Set<string>();
759
+ const noteParts = new Map<string, string>();
760
+ for (const [path, roles] of parts.roles) {
761
+ if (![...roles].some((role) => WORD_EXPANDED_PARTS.has(role))) continue;
762
+ const xml = await archive.file(path)?.async("string");
763
+ if (!xml) continue;
764
+ optional.add(path);
765
+ if (roles.has("header") || roles.has("footer")) nodes.set(path, { xml, path });
766
+ for (const role of ["footnotes", "endnotes", "comments"]) {
767
+ if (!roles.has(role)) continue;
768
+ noteParts.set(role.slice(0, -1), path);
769
+ const parser = xmlParser();
770
+ let start = 0;
771
+ let id = "";
772
+ let depth = 0;
773
+ let prefix = "";
774
+ let suffix = "";
775
+ parser.on("opentag", (tag) => {
776
+ if (++depth === 1) {
777
+ prefix = xml.slice(0, parser.position);
778
+ suffix = `</${tag.name}>`;
779
+ }
780
+ if (tag.local !== role.slice(0, -1)) return;
781
+ start = xml.lastIndexOf("<", parser.position - 1);
782
+ id = Object.values(tag.attributes).find((attr) => attr.local === "id")?.value ?? "";
783
+ });
784
+ parser.on("closetag", (tag) => {
785
+ if (tag.local === role.slice(0, -1))
786
+ nodes.set(`${path}#${id}`, {
787
+ xml: prefix + xml.slice(start, parser.position) + suffix,
788
+ path,
789
+ });
790
+ depth--;
791
+ });
792
+ parser.write(xml).close();
793
+ }
794
+ }
795
+ const used = new Set<string>();
796
+ const memo = new Map<string, Cost>();
797
+ let expandedXmlBytes = 0;
798
+ const scan = (xml: string, path: string, chain: Set<string>, pages = 1, expand = true): Cost => {
799
+ const cost = empty();
800
+ const refs = new Map<string, number>();
801
+ const headers = new Set<string>();
802
+ const parser = xmlParser();
803
+ const add = (key: string) => refs.set(key, (refs.get(key) ?? 0) + 1);
804
+ parser.on("opentag", (tag) => {
805
+ const attr = (name: string) =>
806
+ Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";
807
+ const note = /^(footnote|endnote|comment)Reference$/.exec(tag.local)?.[1];
808
+ if (note && noteParts.has(note)) add(`${noteParts.get(note)}#${attr("id")}`);
809
+ if (tag.local === "headerReference" || tag.local === "footerReference") {
810
+ const target = parts.relationships.get(path)?.get(attr("id"));
811
+ if (target) headers.add(target);
812
+ }
813
+ if (tag.local === "altChunk") cost.bytes = Infinity;
814
+ if (tag.local !== "blip" && tag.local !== "imagedata") return;
815
+ const target = parts.relationships.get(path)?.get(attr("embed") || attr("id"));
816
+ if (target) {
817
+ cost.media += mediaSizes.get(target) ?? OFFICE_PREVIEW_MAX_BYTES + 1;
818
+ cost.images.add(target);
819
+ }
820
+ });
821
+ parser.write(xml).close();
822
+ for (const header of headers) refs.set(header, pages);
823
+ if (!expand) return cost;
824
+ for (const [key, copies] of refs) {
825
+ const node = nodes.get(key);
826
+ if (!node) continue;
827
+ used.add(node.path);
828
+ if (chain.has(key) || chain.size >= 64) {
829
+ cost.bytes = Infinity;
830
+ break;
831
+ }
832
+ let expanded = memo.get(key);
833
+ if (!expanded) {
834
+ expandedXmlBytes += node.xml.length * 2;
835
+ if (expandedXmlBytes > 3 * 1024 * 1024) {
836
+ cost.bytes = Infinity;
837
+ break;
838
+ }
839
+ const own = wordXmlCost(node.xml, undefined);
840
+ expanded = scan(node.xml, node.path, new Set([...chain, key]));
841
+ expanded.bytes += own.bytes;
842
+ expanded.markup += own.markup;
843
+ memo.set(key, expanded);
844
+ }
845
+ cost.bytes += expanded.bytes * copies;
846
+ cost.markup += expanded.markup * copies;
847
+ cost.media += expanded.media * copies;
848
+ for (const image of expanded.images) cost.images.add(image);
849
+ }
850
+ return cost;
851
+ };
852
+ const costs = new Map<string, Cost>();
853
+ let bytes = 0;
854
+ let markup = 0;
855
+ let media = 0;
856
+ // Styles may introduce a page break before each styled paragraph. The page
857
+ // bound also includes explicit breaks and section transitions in each batch.
858
+ let stylePageBreaks = false;
859
+ for (const [path, roles] of parts.roles)
860
+ if (
861
+ roles.has("styles") &&
862
+ /<(?:\w+:)?pageBreakBefore\b/.test((await archive.file(path)?.async("string")) ?? "")
863
+ )
864
+ stylePageBreaks = true;
865
+ for (const document of documents) {
866
+ const pages = Math.max(
867
+ 1,
868
+ document.match(
869
+ stylePageBreaks ? /<(?:\w+:)?p\b/g : /<(?:\w+:)?(?:br|pageBreakBefore|sectPr)\b/g,
870
+ )?.length ?? 0,
871
+ );
872
+ const expanded = scan(document, "word/document.xml", new Set(), pages);
873
+ const body = wordXmlCost(document, undefined);
874
+ bytes += body.bytes + expanded.bytes;
875
+ markup += body.markup + expanded.markup;
876
+ media += expanded.media;
877
+ costs.set(document, expanded);
878
+ }
879
+ for (const [path, cost] of auxiliaryCosts) {
880
+ if (optional.has(path) && !used.has(path)) continue;
881
+ bytes += cost.bytes;
882
+ markup += cost.markup;
883
+ }
884
+ const overBudget =
885
+ bytes > 3 * 1024 * 1024 || markup > 100_000 || media > OFFICE_PREVIEW_MAX_BYTES;
886
+ const truncated = (used.size > 0 && overBudget) || bytes === Infinity;
887
+ const omitted = new Set([...optional].filter((path) => truncated || !used.has(path)));
888
+ for (const path of omitted) archive.remove(path);
889
+ if (truncated)
890
+ for (const document of documents)
891
+ costs.set(document, scan(document, "word/document.xml", new Set(), 1, false));
892
+ // Remove relationships too: related XML is parsed even when not rendered.
893
+ for (const [owner, refs] of parts.relationships) {
894
+ const ids = new Set([...refs].filter(([, path]) => omitted.has(path)).map(([id]) => id));
895
+ if (ids.size === 0) continue;
896
+ const relPath = owner ? owner.replace(/([^/]+)$/, "_rels/$1.rels") : "_rels/.rels";
897
+ let xml = await archive.file(relPath)?.async("string");
898
+ if (!xml) continue;
899
+ const removed: { start: number; end: number }[] = [];
900
+ const parser = xmlParser();
901
+ let start = -1;
902
+ parser.on("opentag", (tag) => {
903
+ if (tag.local === "Relationship" && ids.has(tag.attributes.Id?.value ?? ""))
904
+ start = xml!.lastIndexOf("<", parser.position - 1);
905
+ });
906
+ parser.on("closetag", (tag) => {
907
+ if (tag.local === "Relationship" && start >= 0) {
908
+ removed.push({ start, end: parser.position });
909
+ start = -1;
910
+ }
911
+ });
912
+ parser.write(xml).close();
913
+ for (const range of removed.toReversed())
914
+ xml = xml.slice(0, range.start) + xml.slice(range.end);
915
+ archive.file(relPath, xml);
916
+ }
917
+ return { costs, truncated, omitted };
918
+}
919
+
920
+// Stream each entry before handing it to an engine. A tiny compressed archive
921
+// must not turn into an unbounded allocation on the UI thread.
922
+async function boundedArchive(input: Extract<OfficeWorkerRequest, { type: "open" }>) {
923
+ const { bytes } = input;
924
+ if (bytes.byteLength > OFFICE_PREVIEW_MAX_BYTES)
925
+ throw new Error("Preview limited to files under 50 MB.");
926
+ checkZipDirectory(bytes);
927
+ const source = await JSZip.loadAsync(bytes).catch(() => {
928
+ throw new Error("This file is damaged, encrypted, or not a valid Office document.");
929
+ });
930
+ const allEntries = Object.values(source.files);
931
+ if (allEntries.length > 2048)
932
+ throw new Error("This file contains too many archive entries to preview.");
933
+ const entries = allEntries.filter((entry) => !entry.dir);
934
+ if (
935
+ input.kind === "docx" &&
936
+ entries.some((entry) => entry.name.includes("\\") || entry.name.startsWith("/"))
937
+ )
938
+ throw new Error("Preview limited: this Word document has unsupported archive paths.");
939
+ const archive = new JSZip();
940
+ const partTypes = wordPartTypes();
941
+ // Metadata must be bounded and classified before any payload gets a media exemption.
942
+ if (input.kind === "docx")
943
+ entries.sort(
944
+ (a, b) =>
945
+ Number(b.name === "[Content_Types].xml" || b.name.endsWith(".rels")) -
946
+ Number(a.name === "[Content_Types].xml" || a.name.endsWith(".rels")),
947
+ );
948
+ const costs = new Map<string, { bytes: number; markup: number }>();
949
+ const mediaSizes = new Map<string, number>();
950
+ let total = 0;
951
+ let wordAuxiliaryMarkup = 0;
952
+ let wordInputTruncated = false;
953
+ let word: ReturnType<typeof wordDocuments> | null = null;
954
+ for (const entry of entries) {
955
+ const document = input.kind === "docx" && entry.name === "word/document.xml";
956
+ const media = input.kind === "docx" && partTypes.binary(entry.name);
957
+ const chunks: Uint8Array[] = [];
958
+ const sections = document ? wordSections() : null;
959
+ let decoder: TextDecoder | undefined;
960
+ let length = 0;
961
+ await new Promise<void>((resolve, reject) => {
962
+ // JSZip exposes this streaming API at runtime but omits it from its types.
963
+ const stream = (
964
+ entry as JSZip.JSZipObject & {
965
+ internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array>;
966
+ }
967
+ ).internalStream("uint8array");
968
+ stream
969
+ .on("data", (chunk: Uint8Array) => {
970
+ total += chunk.length;
971
+ length += chunk.length;
972
+ if (total > OFFICE_PREVIEW_MAX_BYTES) {
973
+ stream.pause();
974
+ reject(new Error("The expanded document is too large to preview safely."));
975
+ return;
976
+ }
977
+ try {
978
+ if (sections) {
979
+ decoder ??= officeXmlDecoder(chunk);
980
+ sections.write(decoder.decode(chunk, { stream: true }));
981
+ }
982
+ } catch (cause) {
983
+ stream.pause();
984
+ reject(cause);
985
+ return;
986
+ }
987
+ if (document && length > 4 * 1024 * 1024) {
988
+ const kept = Math.max(0, chunk.length - (length - 4 * 1024 * 1024));
989
+ if (kept) chunks.push(chunk.subarray(0, kept));
990
+ wordInputTruncated = true;
991
+ return;
992
+ }
993
+ // Media is bounded independently. Even renamed auxiliary XML must
994
+ // stay small before the engine parses it.
995
+ if (input.kind === "docx" && !document && !media) {
996
+ for (const byte of chunk) if (byte === 0x3c) wordAuxiliaryMarkup++;
997
+ if (length > 1024 * 1024 || wordAuxiliaryMarkup > 50_000) {
998
+ stream.pause();
999
+ reject(
1000
+ new Error("Preview limited: this Word document has too much auxiliary markup."),
1001
+ );
1002
+ return;
1003
+ }
1004
+ }
1005
+ if (
1006
+ total > OFFICE_PREVIEW_MAX_BYTES ||
1007
+ (!document &&
1008
+ (input.kind === "xlsx" || media || entry.name.endsWith(".xml")) &&
1009
+ length > 8 * 1024 * 1024)
1010
+ ) {
1011
+ stream.pause();
1012
+ reject(new Error("The expanded document is too large to preview safely."));
1013
+ } else chunks.push(chunk);
1014
+ })
1015
+ .on("error", reject)
1016
+ .on("end", resolve)
1017
+ .resume();
1018
+ });
1019
+ const content = new Uint8Array(document ? Math.min(length, 4 * 1024 * 1024) : length);
1020
+ let offset = 0;
1021
+ for (const chunk of chunks) {
1022
+ content.set(chunk, offset);
1023
+ offset += chunk.length;
1024
+ }
1025
+ if (document) {
1026
+ sections!.write(decoder?.decode() ?? "");
1027
+ word = wordDocuments(officeXml(content), wordInputTruncated, sections!.finish());
1028
+ archive.file(entry.name, word.documents[0]!);
1029
+ } else if (input.kind === "docx" && !media) {
1030
+ let xml = officeXml(content);
1031
+ if (entry.name === "[Content_Types].xml" || entry.name.endsWith(".rels"))
1032
+ xml = partTypes.metadata(entry.name, xml);
1033
+ const roles = partTypes.roles.get(entry.name);
1034
+ const cost = wordXmlCost(xml, roles);
1035
+ // The renderer parses related parts even when their render option is off.
1036
+ if (roles && [...roles].every((role) => WORD_DISABLED_PARTS.has(role))) continue;
1037
+ if (
1038
+ (roles?.has("numbering") && cost.pictures) ||
1039
+ (roles?.has("styles") &&
1040
+ (cost.bytes > WORD_STYLE_MAX_BYTES || cost.markup > WORD_STYLE_MAX_UNITS)) ||
1041
+ (roles?.has("numbering") && (cost.bytes > 128 * 1024 || cost.markup > 2_000))
1042
+ ) {
1043
+ wordInputTruncated = true;
1044
+ continue;
1045
+ }
1046
+ costs.set(entry.name, cost);
1047
+ archive.file(entry.name, xml);
1048
+ } else {
1049
+ if (input.kind === "docx" && partTypes.roles.get(entry.name)?.has("font")) {
1050
+ continue;
1051
+ }
1052
+ if (media) mediaSizes.set(entry.name, Math.ceil((content.length * 4) / 3));
1053
+ archive.file(entry.name, /\.(?:xml|rels)$/i.test(entry.name) ? officeXml(content) : content);
1054
+ }
1055
+ }
1056
+ if (word) {
1057
+ const expansion = await wordExpansion(archive, partTypes, mediaSizes, costs, word.documents);
1058
+ wordInputTruncated ||= expansion.truncated;
1059
+ for (const path of expansion.omitted) {
1060
+ archive.remove(path);
1061
+ costs.delete(path);
1062
+ }
1063
+ let mediaBytes = 0;
1064
+ const usedImages = new Set<string>();
1065
+ const auxiliary = [...costs.values()].reduce(
1066
+ (sum, cost) => ({ bytes: sum.bytes + cost.bytes, markup: sum.markup + cost.markup }),
1067
+ { bytes: 0, markup: 0 },
1068
+ );
1069
+ // The worker engine parses shared parts once, rather than once per legacy render batch.
1070
+ let bytes = auxiliary.bytes;
1071
+ let markup = auxiliary.markup;
1072
+ const documents: string[] = [];
1073
+ for (const document of word.documents) {
1074
+ const rawCost = wordXmlCost(document, undefined);
1075
+ const extra = expansion.costs.get(document)!;
1076
+ const cost = { bytes: rawCost.bytes + extra.bytes, markup: rawCost.markup + extra.markup };
1077
+ const images = extra.media;
1078
+ const batchImages = new Set(extra.images);
1079
+ if (
1080
+ bytes + cost.bytes > 3 * 1024 * 1024 ||
1081
+ markup + cost.markup > 100_000 ||
1082
+ mediaBytes + images > OFFICE_PREVIEW_MAX_BYTES
1083
+ )
1084
+ break;
1085
+ bytes += cost.bytes;
1086
+ markup += cost.markup;
1087
+ mediaBytes += images;
1088
+ for (const path of batchImages) usedImages.add(path);
1089
+ documents.push(document);
1090
+ }
1091
+ if (documents.length === 0)
1092
+ throw new Error("Preview limited: this Word document has too much expanded markup.");
1093
+ word.truncated ||= wordInputTruncated || documents.length < word.documents.length;
1094
+ word.documents = documents;
1095
+ for (const path of mediaSizes.keys()) if (!usedImages.has(path)) archive.remove(path);
1096
+ archive.file("word/document.xml", documents[0]!);
1097
+ }
1098
+ const truncatedSheets = input.kind === "xlsx" ? await boundWorkbook(archive) : [];
1099
+ return { archive, word, truncatedSheets };
1100
+}
1101
+
1102
+export async function prepareOffice(
1103
+ bytes: ArrayBuffer,
1104
+ kind: Extract<OfficeWorkerRequest, { type: "open" }>["kind"],
1105
+) {
1106
+ const result = await boundedArchive({ type: "open", kind, bytes });
1107
+ const root =
1108
+ kind === "docx"
1109
+ ? "word/document.xml"
1110
+ : kind === "xlsx"
1111
+ ? "xl/workbook.xml"
1112
+ : "ppt/presentation.xml";
1113
+ if (!result.archive.file(root))
1114
+ throw new Error("This is not a valid Office Open XML file. Encrypted files are not supported.");
1115
+ if (result.word) {
1116
+ const references = new Map<string, string>();
1117
+ const relationships = xmlParser();
1118
+ relationships.on("opentag", (tag) => {
1119
+ if (tag.local !== "Relationship") return;
1120
+ const type = tag.attributes.Type?.value ?? "";
1121
+ const target = tag.attributes.Target?.value ?? "";
1122
+ const path = new URL(target, "https://docx.invalid/word/").pathname.slice(1);
1123
+ if (result.archive.file(path))
1124
+ references.set(tag.attributes.Id?.value ?? "", type.slice(type.lastIndexOf("/") + 1));
1125
+ });
1126
+ const relationshipXml = await result.archive
1127
+ .file("word/_rels/document.xml.rels")
1128
+ ?.async("string");
1129
+ if (relationshipXml) relationships.write(relationshipXml).close();
1130
+ let xml = joinWordBatches(result.word.documents);
1131
+ const removed: { start: number; end: number }[] = [];
1132
+ const parser = xmlParser();
1133
+ let start = -1;
1134
+ // Bounded parts can be omitted; dangling story references otherwise reject the entire body in the engine.
1135
+ parser.on("opentag", (tag) => {
1136
+ if (tag.local !== "headerReference" && tag.local !== "footerReference") return;
1137
+ const id = Object.values(tag.attributes).find((attr) => attr.local === "id")?.value ?? "";
1138
+ if (references.get(id) !== tag.local.replace("Reference", ""))
1139
+ start = xml.lastIndexOf("<", parser.position - 1);
1140
+ });
1141
+ parser.on("closetag", (tag) => {
1142
+ if (start >= 0 && (tag.local === "headerReference" || tag.local === "footerReference")) {
1143
+ removed.push({ start, end: parser.position });
1144
+ start = -1;
1145
+ }
1146
+ });
1147
+ parser.write(xml).close();
1148
+ for (const range of removed.toReversed())
1149
+ xml = xml.slice(0, range.start) + xml.slice(range.end);
1150
+ result.archive.file(root, xml);
1151
+ }
1152
+ return {
1153
+ bytes: await result.archive.generateAsync({ type: "arraybuffer", compression: "STORE" }),
1154
+ truncated: result.word?.truncated || result.truncatedSheets.some(Boolean) || false,
1155
+ };
1156
+}
1157
+
1158
+function joinWordBatches(documents: string[]) {
1159
+ let prefix = "";
1160
+ let suffix = "";
1161
+ let section = "";
1162
+ const bodies: string[] = [];
1163
+ for (const xml of documents) {
1164
+ const parser = xmlParser();
1165
+ let depth = 0;
1166
+ let start = 0;
1167
+ let end = 0;
1168
+ let sectionStart = 0;
1169
+ parser.on("opentag", (tag) => {
1170
+ depth++;
1171
+ if (depth === 2 && tag.local === "body") {
1172
+ start = parser.position;
1173
+ if (!prefix) prefix = xml.slice(0, start);
1174
+ }
1175
+ if (depth === 3 && tag.local === "sectPr")
1176
+ sectionStart = xml.lastIndexOf("<", parser.position - 1);
1177
+ });
1178
+ parser.on("closetag", (tag) => {
1179
+ if (depth === 2 && tag.local === "body") {
1180
+ end = xml.lastIndexOf("<", parser.position - 1);
1181
+ suffix = xml.slice(end);
1182
+ }
1183
+ depth--;
1184
+ });
1185
+ parser.write(xml).close();
1186
+ bodies.push(xml.slice(start, sectionStart || end));
1187
+ section = sectionStart ? xml.slice(sectionStart, end) : "";
1188
+ }
1189
+ return prefix + bodies.join("") + section + suffix;
1190
+}
apps/web/src/components/files/officePreview.worker.ts
new
+20
@@ -0,0 +1,20 @@
1
+import { prepareOffice } from "./officeArchive";
2
+import type { OfficeWorkerRequest, OfficeWorkerResult } from "./officePreviewProtocol";
3
+self.addEventListener("message", (event: MessageEvent<OfficeWorkerRequest>) => {
4
+ if (event.data.type !== "open") return;
5
+ const input = event.data;
6
+ void prepareOffice(input.bytes, input.kind)
7
+ .then((result) => {
8
+ const reply: OfficeWorkerResult = { type: input.kind, ...result };
9
+ self.postMessage(reply, { transfer: [result.bytes] });
10
+ })
11
+ .catch((cause: unknown) => {
12
+ self.postMessage(
13
+ {
14
+ type: "error",
15
+ message: cause instanceof Error ? cause.message : "Could not parse this file.",
16
+ } satisfies OfficeWorkerResult,
17
+ { transfer: [] },
18
+ );
19
+ });
20
+});
apps/web/src/components/files/officePreviewProtocol.ts
new
+16
@@ -0,0 +1,16 @@
1
+import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
2
+export const OFFICE_PREVIEW_MAX_BYTES = 50 * 1024 * 1024;
3
+export const OFFICE_PREVIEW_MAX_ROWS = 500;
4
+export const OFFICE_PREVIEW_MAX_COLUMNS = 50;
5
+export type OfficeWorkerRequest = {
6
+ readonly type: "open";
7
+ readonly kind: OfficePreviewKind;
8
+ readonly bytes: ArrayBuffer;
9
+};
10
+export type OfficeWorkerResult =
11
+ | { readonly type: "error"; readonly message: string }
12
+ | {
13
+ readonly type: OfficePreviewKind;
14
+ readonly bytes: ArrayBuffer;
15
+ readonly truncated: boolean;
16
+ };
apps/web/src/components/files/zipDirectory.ts
new
+75
@@ -0,0 +1,75 @@
1
+export function checkZipDirectory(bytes: ArrayBuffer, entryLimit = 2048) {
2
+ // Reject oversized directories before JSZip allocates objects for their entries.
3
+ const view = new DataView(bytes);
4
+ let directoryEnd = -1;
5
+ let directorySize = 0;
6
+ for (
7
+ let offset = bytes.byteLength - 22;
8
+ offset >= Math.max(0, bytes.byteLength - 65557);
9
+ offset--
10
+ ) {
11
+ if (view.getUint32(offset, true) !== 0x06054b50) continue;
12
+ if (offset + 22 + view.getUint16(offset + 20, true) !== bytes.byteLength)
13
+ throw new Error("This is not a readable ZIP archive.");
14
+ let count = view.getUint16(offset + 10, true);
15
+ directorySize = view.getUint32(offset + 12, true);
16
+ let directoryOffset = view.getUint32(offset + 16, true);
17
+ directoryEnd = offset;
18
+ if (
19
+ [4, 6, 8, 10].some((field) => view.getUint16(offset + field, true) === 0xffff) ||
20
+ directorySize === 0xffffffff ||
21
+ directoryOffset === 0xffffffff
22
+ ) {
23
+ const locator = offset - 20;
24
+ const record = locator - 56;
25
+ // JSZip uses the last locator, including signatures inside the archive comment.
26
+ for (let candidate = bytes.byteLength - 4; candidate > locator; candidate--)
27
+ if (view.getUint32(candidate, true) === 0x07064b50)
28
+ throw new Error("Unsupported ZIP64 directory.");
29
+ if (
30
+ record < 0 ||
31
+ view.getUint32(locator, true) !== 0x07064b50 ||
32
+ view.getUint32(record, true) !== 0x06064b50 ||
33
+ view.getBigUint64(record + 4, true) !== 44n ||
34
+ view.getUint32(record + 16, true) !== 0 ||
35
+ view.getUint32(record + 20, true) !== 0 ||
36
+ view.getUint32(locator + 4, true) !== 0 ||
37
+ view.getUint32(locator + 16, true) !== 1 ||
38
+ view.getBigUint64(locator + 8, true) !== BigInt(record)
39
+ )
40
+ throw new Error("Unsupported ZIP64 directory.");
41
+ const records = view.getBigUint64(record + 32, true);
42
+ const size = view.getBigUint64(record + 40, true);
43
+ const start = view.getBigUint64(record + 48, true);
44
+ if (
45
+ records > BigInt(entryLimit) ||
46
+ size > BigInt(record) ||
47
+ start > BigInt(record) ||
48
+ view.getBigUint64(locator + 8, true) !== start + size ||
49
+ view.getBigUint64(record + 24, true) !== records
50
+ )
51
+ throw new Error("This ZIP64 directory is too large or damaged.");
52
+ count = Number(records);
53
+ directorySize = Number(size);
54
+ directoryOffset = Number(start);
55
+ directoryEnd = record;
56
+ }
57
+ if (count > entryLimit) throw new Error("This archive contains more than 2,048 entries.");
58
+ if (directoryOffset > directoryEnd - directorySize)
59
+ throw new Error("This ZIP directory is damaged.");
60
+ break;
61
+ }
62
+ if (directoryEnd < 0 || directorySize > directoryEnd)
63
+ throw new Error("This is not a readable ZIP archive.");
64
+ let records = 0;
65
+ for (let offset = directoryEnd - directorySize; offset < directoryEnd;) {
66
+ if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50)
67
+ throw new Error("This ZIP directory is damaged.");
68
+ if (++records > entryLimit) throw new Error("This archive contains more than 2,048 entries.");
69
+ const nameLength = view.getUint16(offset + 28, true);
70
+ if (nameLength > 1024) throw new Error("An archive path is too long to preview.");
71
+ offset +=
72
+ 46 + nameLength + view.getUint16(offset + 30, true) + view.getUint16(offset + 32, true);
73
+ if (offset > directoryEnd) throw new Error("This ZIP directory is damaged.");
74
+ }
75
+}
apps/web/vite.config.ts
+23
-3
@@ -97,9 +97,22 @@ const browserTestApiPort = 61_000 + ((Hash.string(import.meta.dirname) >>> 0) %
97
98
const browserTestProject = {
99
extends: true,
100
- // Pre-bundled so a late first import does not trigger a mid-run reload. The
101
- // dependency scan misses autocomplete because tests reach it only through lazy imports.
102
- optimizeDeps: { include: ["vite-plus/test/browser", "@base-ui/react/autocomplete"] },
100
+ // Pre-bundle lazy browser and worker dependencies to avoid mid-run reloads.
101
+ optimizeDeps: {
102
+ include: [
103
+ "vite-plus/test/browser",
104
+ "@base-ui/react/autocomplete",
105
+ "saxes",
106
+ "@betteroffice/docx/editor",
107
+ "@betteroffice/docx/layout",
108
+ "@betteroffice/docx/layout/render",
109
+ "@betteroffice/docx/yrs",
110
+ "@betteroffice/fonts",
111
+ "@betteroffice/pptx",
112
+ "@betteroffice/xlsx",
113
+ "@betteroffice/xlsx/headless",
114
+ ],
115
+ },
116
test: {
117
name: "browser",
118
include: ["src/**/*.browser.test.{ts,tsx}"],
@@ -274,6 +287,12 @@ export default defineConfig(() => {
287
},
288
resolve: {
289
tsconfigPaths: true,
290
+ alias: {
291
+ "@betteroffice/fonts-cjk": new URL(
292
+ "./src/components/files/office/fonts-cjk.ts",
293
+ import.meta.url,
294
+ ).pathname,
295
+ },
296
dedupe: ["react", "react-dom"],
297
},
298
experimental: {
@@ -325,6 +344,7 @@ export default defineConfig(() => {
344
manifest: true,
345
sourcemap: buildSourcemap,
346
},
347
+ worker: { format: "es" },
348
test: {
349
projects: [
350
defineProject(unitTestProject),
packages/shared/src/filePreview.test.ts
+89
-3
@@ -4,18 +4,87 @@ import {
4
filePreviewKind,
5
decodeFilePreviewText,
6
FILE_TEXT_PREVIEW_MAX_BYTES,
7
+ hostPreviewMimeTypeFromExtension,
8
+ isWorkspaceFontPreviewPath,
9
+ isWorkspaceImagePreviewPath,
10
isWorkspacePreviewEntryPath,
11
mediaKindFromPath,
12
+ officePreviewKind,
13
} from "./filePreview.ts";
14
15
describe("workspace file previews", () => {
16
+ it.each(["ttf", "otf", "woff", "woff2"])(
17
+ "previews %s fonts through signed host assets",
18
+ (extension) => {
19
+ expect(
20
+ filePreviewKind({ name: `sample.${extension}`, mimeType: "application/octet-stream" }),
21
+ ).toBe("font");
22
+ expect(filePreviewKind({ name: "download", mimeType: `font/${extension}` })).toBe("font");
23
+ expect(isWorkspaceFontPreviewPath(`/tmp/sample.${extension.toUpperCase()}`)).toBe(true);
24
+ expect(isWorkspacePreviewEntryPath(`sample.${extension}`)).toBe(true);
25
+ expect(hostPreviewMimeTypeFromExtension(`.${extension}`)).toBe(`font/${extension}`);
26
+ expect(isWorkspaceFontPreviewPath(`sample.${extension}?download=1`)).toBe(false);
27
+ expect(filePreviewKind({ name: `sample.${extension}`, mimeType: "application/zip" })).toBe(
28
+ "unsupported",
29
+ );
30
+ },
31
+ );
32
+ it.each([
33
+ [
34
+ "quarterly-report.DOCX",
35
+ "docx",
36
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
37
+ ],
38
+ [
39
+ "finance#q4/operating-plan.xlsx",
40
+ "xlsx",
41
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
42
+ ],
43
+ [
44
+ "slides?review/quarterly-review.pptx",
45
+ "pptx",
46
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
47
+ ],
48
+ ])("recognizes Office assets at literal path %s", (name, kind, mimeType) => {
49
+ expect(officePreviewKind({ name })).toBe(kind);
50
+ expect(filePreviewKind({ name, mimeType: "application/octet-stream" })).toBe(kind);
51
+ expect(isWorkspacePreviewEntryPath(name)).toBe(true);
52
+ expect(hostPreviewMimeTypeFromExtension(`.${kind}`)).toBe(mimeType);
53
+ expect(filePreviewKind({ name: "download", mimeType })).toBe(kind);
54
+ expect(filePreviewKind({ name, mimeType: "application/zip" })).toBe("unsupported");
55
+ });
56
// regression: #10311 previews classify by the literal filename, not URL-like suffixes
13
- it.each(["image.png.ts", "image.png#notes.txt", "image%2Epng"])(
14
- "rejects non-preview path %s",
57
+ it.each([
58
+ "image.png.ts",
59
+ "image.png#notes.txt",
60
+ "image%2Epng",
61
+ "report.docx#notes.txt",
62
+ "report.xlsx?download=1",
63
+ "slides%2Epptx",
64
+ "report.docm",
65
+ "slides.ppt",
66
+ ])("rejects non-preview path %s", (path) => {
67
+ expect(isWorkspacePreviewEntryPath(path)).toBe(false);
68
+ });
69
+
70
+ it.each(["picture.bmp", "photo.heic", "scan.tif", "scan.TIFF"])(
71
+ "recognizes image preview path %s",
72
(path) => {
16
- expect(isWorkspacePreviewEntryPath(path)).toBe(false);
73
+ expect(isWorkspaceImagePreviewPath(path)).toBe(true);
74
+ expect(isWorkspacePreviewEntryPath(path)).toBe(true);
75
},
76
);
77
+
78
+ it("serves audio in place from the host like video and browser documents", () => {
79
+ expect(hostPreviewMimeTypeFromExtension(".m4a")).toBe("audio/mp4");
80
+ expect(hostPreviewMimeTypeFromExtension(".weba")).toBe("audio/webm");
81
+ expect(hostPreviewMimeTypeFromExtension(".mp4")).toBe("video/mp4");
82
+ expect(hostPreviewMimeTypeFromExtension(".txt")).toBeNull();
83
+ expect(hostPreviewMimeTypeFromExtension(".constructor")).toBeNull();
84
+ expect(hostPreviewMimeTypeFromExtension(".toString")).toBeNull();
85
+ expect(hostPreviewMimeTypeFromExtension(".__proto__")).toBeNull();
86
+ expect(hostPreviewMimeTypeFromExtension(".webm-audio")).toBe("audio/webm");
87
+ });
88
});
89
90
describe("media path parsing", () => {
@@ -48,6 +117,17 @@ describe("attachment preview classification", () => {
117
it.each([
118
["example.json", "application/octet-stream", "text"],
119
["report.pdf", "application/pdf", "pdf"],
120
+ ["page.HTML", "", "html"],
121
+ ["diagram.mmd", "", "mermaid"],
122
+ ["diagram.MERMAID", "text/plain", "mermaid"],
123
+ ["download", "text/vnd.mermaid", "mermaid"],
124
+ ["source-code.otf", "application/vnd.oasis.opendocument.formula-template", "font"],
125
+ ["notes.rtf", "application/rtf", "text"],
126
+ ["notes.rtf", "", "text"],
127
+ ["clip.weba", "", "audio"],
128
+ ["image.bmp", "application/octet-stream", "image"],
129
+ ["photo.heic", "application/octet-stream", "image"],
130
+ ["scan.tiff", "application/octet-stream", "image"],
131
["recording.mp3", "", "audio"],
132
["recording.webm-audio", "", "audio"],
133
["recording.webm", "audio/webm", "audio"],
@@ -61,6 +141,12 @@ describe("attachment preview classification", () => {
141
expect(() => decodeFilePreviewText(new Uint8Array([65, 0, 66]))).toThrow("binary");
142
expect(() => decodeFilePreviewText(new Uint8Array([255]))).toThrow("UTF-8");
143
});
144
+ it.each(["doc", "xls", "ppt", "odt", "ods", "odp", "epub", "zip", "tar", "gz", "7z", "rar"])(
145
+ "retains the binary fallback for %s, which opencode does not render",
146
+ (extension) => {
147
+ expect(filePreviewKind({ name: `sample.${extension}` })).toBe("unsupported");
148
+ },
149
+ );
150
it("does not corrupt a multi-byte character at the preview boundary", () => {
151
const bytes = new Uint8Array(FILE_TEXT_PREVIEW_MAX_BYTES + 1).fill(97);
152
bytes[FILE_TEXT_PREVIEW_MAX_BYTES - 1] = 0xe2;
packages/shared/src/filePreview.ts
+80
-5
@@ -26,20 +26,39 @@ export type FilePreviewKind =
26
| "pdf"
27
| "html"
28
| "markdown"
29
+ | "mermaid"
30
+ | "font"
31
+ | "docx"
32
+ | "xlsx"
33
+ | "pptx"
34
| "text"
35
| "unsupported";
36
32
-export function filePreviewKind(file: {
33
- readonly name: string;
34
- readonly mimeType?: string;
35
-}): FilePreviewKind {
37
+export function filePreviewKind(
38
+ file: { readonly name: string; readonly mimeType?: string },
39
+ options?: { readonly richDocuments?: boolean },
40
+): FilePreviewKind {
41
const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
42
const name = file.name.toLowerCase();
43
const extension = name.slice(name.lastIndexOf("."));
44
const generic = !mime || mime === "application/octet-stream" || mime === "text/plain";
45
+ const richDocuments = options?.richDocuments !== false;
46
+ const office = richDocuments ? officePreviewKind(file) : null;
47
+ if (office) return office;
48
if (mime === "application/pdf") return "pdf";
49
if (mime === "text/html") return "html";
50
if (mime === "text/markdown" || mime === "text/x-markdown") return "markdown";
51
+ if (richDocuments && mime === "text/vnd.mermaid") return "mermaid";
52
+ if (richDocuments && mime.startsWith("font/")) return "font";
53
+ // Linux's MIME database also assigns .otf to OpenDocument formula templates.
54
+ // FontFace validates the actual bytes before a specimen is shown.
55
+ if (
56
+ richDocuments &&
57
+ extension === ".otf" &&
58
+ mime === "application/vnd.oasis.opendocument.formula-template"
59
+ )
60
+ return "font";
61
+ if (richDocuments && mime === "application/rtf") return "text";
62
if (mime.startsWith("image/")) return "image";
63
if (mime.startsWith("video/")) return "video";
64
if (mime.startsWith("audio/")) return "audio";
@@ -47,6 +66,9 @@ export function filePreviewKind(file: {
66
if (extension === ".pdf") return "pdf";
67
if (/^\.html?$/.test(extension)) return "html";
68
if (/^\.(md|markdown|mdown|mkd|mdx)$/.test(extension)) return "markdown";
69
+ if (richDocuments && /^\.(mmd|mermaid)$/.test(extension)) return "mermaid";
70
+ if (richDocuments && isWorkspaceFontPreviewPath(name)) return "font";
71
+ if (richDocuments && extension === ".rtf") return "text";
72
const media = mediaMimeTypeFromExtension(extension);
73
if (media?.startsWith("image/")) return "image";
74
if (media?.startsWith("video/")) return "video";
@@ -73,6 +95,30 @@ export function filePreviewKind(file: {
95
96
export const FILE_TEXT_PREVIEW_MAX_BYTES = 1024 * 1024;
97
98
+const OFFICE_MIME_TYPES = {
99
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
100
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
101
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
102
+} as const;
103
+
104
+export type OfficePreviewKind = keyof typeof OFFICE_MIME_TYPES;
105
+
106
+export function officePreviewKind(file: {
107
+ readonly name: string;
108
+ readonly mimeType?: string;
109
+}): OfficePreviewKind | null {
110
+ const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
111
+ for (const kind of ["docx", "xlsx", "pptx"] as const) {
112
+ if (mime === OFFICE_MIME_TYPES[kind]) return kind;
113
+ if (
114
+ (!mime || mime === "application/octet-stream" || mime === "text/plain") &&
115
+ file.name.toLowerCase().endsWith(`.${kind}`)
116
+ )
117
+ return kind;
118
+ }
119
+ return null;
120
+}
121
+
122
export function decodeFilePreviewText(bytes: Uint8Array, truncated = false) {
123
const bounded = bytes.subarray(0, FILE_TEXT_PREVIEW_MAX_BYTES);
124
if (bounded.some((byte) => byte === 0))
@@ -92,23 +138,31 @@ export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as
138
139
export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
140
".avif",
141
+ ".bmp",
142
".gif",
143
".ico",
144
+ ".heic",
145
".jpeg",
146
".jpg",
147
".png",
148
".svg",
149
+ ".tif",
150
+ ".tiff",
151
".webp",
152
] as const;
153
154
const IMAGE_MIME_TYPE_BY_EXTENSION = new Map([
155
[".avif", "image/avif"],
156
+ [".bmp", "image/bmp"],
157
+ [".heic", "image/heic"],
158
[".gif", "image/gif"],
159
[".ico", "image/x-icon"],
160
[".jpeg", "image/jpeg"],
161
[".jpg", "image/jpeg"],
162
[".png", "image/png"],
163
[".svg", "image/svg+xml"],
164
+ [".tif", "image/tiff"],
165
+ [".tiff", "image/tiff"],
166
[".webp", "image/webp"],
167
]);
168
@@ -129,8 +183,20 @@ const AUDIO_MIME_TYPE_BY_EXTENSION = new Map([
183
[".opus", "audio/ogg"],
184
[".aiff", "audio/aiff"],
185
[".webm-audio", "audio/webm"],
186
+ [".weba", "audio/webm"],
187
+]);
188
+
189
+const FONT_MIME_TYPE_BY_EXTENSION = new Map([
190
+ [".ttf", "font/ttf"],
191
+ [".otf", "font/otf"],
192
+ [".woff", "font/woff"],
193
+ [".woff2", "font/woff2"],
194
]);
195
196
+export function isWorkspaceFontPreviewPath(path: string): boolean {
197
+ return /\.(ttf|otf|woff2?)$/i.test(path);
198
+}
199
+
200
export function audioMimeTypeFromExtension(extension: string): string | null {
201
if (!/^\.[a-z0-9-]+$/i.test(extension)) return null;
202
return AUDIO_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ?? null;
@@ -151,6 +217,10 @@ export function hostPreviewMimeTypeFromExtension(extension: string): string | nu
217
mediaMimeTypeFromExtension(extension) ??
218
audioMimeTypeFromExtension(extension) ??
219
BROWSER_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
220
+ FONT_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
221
+ (Object.hasOwn(OFFICE_MIME_TYPES, extension.toLowerCase().slice(1))
222
+ ? OFFICE_MIME_TYPES[extension.toLowerCase().slice(1) as OfficePreviewKind]
223
+ : null) ??
224
null
225
);
226
}
@@ -215,5 +285,10 @@ export function isWorkspaceAudioPreviewPath(path: string): boolean {
285
}
286
287
export function isWorkspacePreviewEntryPath(path: string): boolean {
218
- return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);
288
+ return (
289
+ isWorkspaceBrowserPreviewPath(path) ||
290
+ isWorkspaceImagePreviewPath(path) ||
291
+ isWorkspaceFontPreviewPath(path) ||
292
+ officePreviewKind({ name: path }) !== null
293
+ );
294
}
pnpm-lock.yaml
+47
@@ -992,6 +992,18 @@ importers:
992
'@base-ui/react':
993
specifier: ^1.4.1
994
version: 1.5.0(@date-fns/tz@1.5.0)(@types/react@19.3.0)(date-fns@4.4.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
995
+ '@betteroffice/docx':
996
+ specifier: 0.4.3
997
+ version: 0.4.3(@betteroffice/fonts@0.4.0)
998
+ '@betteroffice/fonts':
999
+ specifier: 0.4.0
1000
+ version: 0.4.0
1001
+ '@betteroffice/pptx':
1002
+ specifier: 0.2.0
1003
+ version: 0.2.0
1004
+ '@betteroffice/xlsx':
1005
+ specifier: 0.3.0
1006
+ version: 0.3.0
1007
'@clerk/clerk-js':
1008
specifier: 6.40.0
1009
version: 6.40.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
@@ -1175,6 +1187,9 @@ importers:
1187
remark-parse:
1188
specifier: 'catalog:'
1189
version: 11.0.0(supports-color@8.1.1)
1190
+ saxes:
1191
+ specifier: 6.0.0
1192
+ version: 6.0.0
1193
tailwind-merge:
1194
specifier: ^3.4.0
1195
version: 3.6.0
@@ -2904,6 +2919,28 @@ packages:
2919
'@types/react':
2920
optional: true
2921
2922
+ '@betteroffice/docx@0.4.3':
2923
+ resolution: {integrity: sha512-CEErXJH3iCsi2a61gTNkAofLCzSTcktLmp710gGhMwbBfOqwQ2yI7dRFBV3ElGa9JxkS03IfejvLX0sAvlTrUQ==}
2924
+ peerDependencies:
2925
+ '@betteroffice/fonts': ^0
2926
+ peerDependenciesMeta:
2927
+ '@betteroffice/fonts':
2928
+ optional: true
2929
+
2930
+ '@betteroffice/fonts@0.4.0':
2931
+ resolution: {integrity: sha512-x1BVwYDAgY5R6TWI4t9NLguSiAEbH5GItN2ZlpBIFoRXTIJgjBsXd6sUxPGpexXOyY6KdhRjG8XvHjyAYxEGCw==}
2932
+ peerDependencies:
2933
+ '@betteroffice/fonts-cjk': ^0
2934
+ peerDependenciesMeta:
2935
+ '@betteroffice/fonts-cjk':
2936
+ optional: true
2937
+
2938
+ '@betteroffice/pptx@0.2.0':
2939
+ resolution: {integrity: sha512-pNPQ58tlA+pVibERbLdQNskvP7a0GIMf4jhkCU/gPp8043Ichf6gB3PSb4ra9sfqoIaWqOaZKCWyptovA2+Q0A==}
2940
+
2941
+ '@betteroffice/xlsx@0.3.0':
2942
+ resolution: {integrity: sha512-K2bHtdk/epAxsmvxJlIWBRndjP3ltQU0Oh3p4gcZd2n5/YgXglo3SmMYX4nQe8WEm/yvz91p+aIasKyXXQP9Wg==}
2943
+
2944
'@blazediff/core@1.10.0':
2945
resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==}
2946
@@ -13140,6 +13177,16 @@ snapshots:
13177
optionalDependencies:
13178
'@types/react': 19.3.0
13179
13180
+ '@betteroffice/docx@0.4.3(@betteroffice/fonts@0.4.0)':
13181
+ optionalDependencies:
13182
+ '@betteroffice/fonts': 0.4.0
13183
+
13184
+ '@betteroffice/fonts@0.4.0': {}
13185
+
13186
+ '@betteroffice/pptx@0.2.0': {}
13187
+
13188
+ '@betteroffice/xlsx@0.3.0': {}
13189
+
13190
'@blazediff/core@1.10.0': {}
13191
13192
'@bramus/specificity@2.4.2':
third-party-licenses.config.json
+49
@@ -1,5 +1,12 @@
1
{
2
"customNotices": [
3
+ {
4
+ "name": "opencode Office viewers",
5
+ "bundles": ["web"],
6
+ "license": "MIT",
7
+ "sourceUrl": "https://github.com/anomalyco/opencode",
8
+ "noticeFile": "apps/web/src/components/files/office/LICENSE.opencode"
9
+ },
10
{
11
"bundles": ["desktop", "web"],
12
"license": "MIT",
@@ -222,6 +229,33 @@
229
}
230
],
231
"packageOverrides": [
232
+ {
233
+ "name": "@betteroffice/xlsx",
234
+ "version": "0.3.0",
235
+ "license": "Apache-2.0",
236
+ "sourceUrl": "https://github.com/openooxml/betteroffice",
237
+ "generatedNotice": {
238
+ "licenseId": "Apache-2.0"
239
+ }
240
+ },
241
+ {
242
+ "name": "@betteroffice/pptx",
243
+ "version": "0.2.0",
244
+ "license": "Apache-2.0",
245
+ "sourceUrl": "https://github.com/openooxml/betteroffice",
246
+ "generatedNotice": {
247
+ "licenseId": "Apache-2.0"
248
+ }
249
+ },
250
+ {
251
+ "name": "@betteroffice/docx",
252
+ "version": "0.4.3",
253
+ "license": "Apache-2.0",
254
+ "sourceUrl": "https://github.com/openooxml/betteroffice",
255
+ "generatedNotice": {
256
+ "licenseId": "Apache-2.0"
257
+ }
258
+ },
259
{
260
"name": "character-entities",
261
"version": "2.0.2",
@@ -240,11 +274,26 @@
274
"generatedNotice": {
275
"licenseId": "ISC",
276
"copyrights": [
277
+ "Copyright (c) 2018-2021 Louis-Dominique Dubeau",
278
"Copyright (c) Contributors",
279
"Copyright (c) Isaac Z. Schlueter and Contributors"
280
]
281
}
282
},
283
+ {
284
+ "name": "@betteroffice/fonts",
285
+ "version": "0.4.0",
286
+ "license": "Apache-2.0 AND OFL-1.1",
287
+ "generatedNotices": [
288
+ { "licenseId": "Apache-2.0" },
289
+ {
290
+ "licenseId": "OFL-1.1",
291
+ "copyrights": [
292
+ "Copyright 2013 The Carlito Project Authors (https://github.com/googlefonts/carlito), with Reserved Font Name \"Carlito\""
293
+ ]
294
+ }
295
+ ]
296
+ },
297
{
298
"name": "remark-math",
299
"version": "6.0.0",