TypeScript
feat(web): preview office files, fonts, and mermaid diagrams (#21362)
mariad69810a97a98
diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.tsindex b5fe707f4ca..155b89c1cc5 100644--- a/apps/desktop/src/ipc/methods/window.test.ts+++ b/apps/desktop/src/ipc/methods/window.test.ts@@ -20,9 +20,13 @@ vi.mock("electron", () => ({import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";+import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";+import * as ElectronDialog from "../../electron/ElectronDialog.ts";+import * as ElectronWindow from "../../electron/ElectronWindow.ts";import {getLocalEnvironmentBootstraps,getRelayTelemetryEnabled,+ pickProjectFavicon,probeRemoteEditors,} from "./window.ts";@@ -192,6 +196,77 @@ describe("getRelayTelemetryEnabled", () => {);});+describe("pickProjectFavicon", () => {+ const pickerLayer = (+ pickFiles: () => Effect.Effect<Array<string>>,+ settings?: DesktopAppSettings.DesktopSettings,+ ) =>+ Layer.mergeAll(+ Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }),+ Layer.mock(ElectronWindow.ElectronWindow)({+ focusedMainOrFirst: Effect.succeedNone,+ }),+ DesktopAppSettings.layerTest(settings),+ );++ it.effect("opens a single-image picker from the project directory", () =>+ Effect.gen(function* () {+ const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));+ const result = yield* pickProjectFavicon+ .handler("/project")+ .pipe(Effect.provide(pickerLayer(pickFiles)));++ assert.strictEqual(result, "/pictures/icon.png");+ assert.deepEqual(pickFiles.mock.calls, [+ [+ {+ owner: Option.none(),+ defaultPath: Option.some("/project"),+ multiple: false,+ filters: [+ {+ name: "Images",+ extensions: [+ "avif",+ "bmp",+ "gif",+ "ico",+ "heic",+ "jpeg",+ "jpg",+ "png",+ "svg",+ "tif",+ "tiff",+ "webp",+ "icns",+ ],+ },+ ],+ },+ ],+ ]);+ }),+ );++ it.effect("does not open a picker while the local environment is off", () =>+ Effect.gen(function* () {+ const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));+ const result = yield* pickProjectFavicon.handler("/project").pipe(+ Effect.provide(+ pickerLayer(pickFiles, {+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,+ localEnvironmentEnabled: false,+ }),+ ),+ );++ assert.strictEqual(result, null);+ assert.strictEqual(pickFiles.mock.calls.length, 0);+ }),+ );+});+it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")("finds remote editors installed without PATH launchers",() =>diff --git a/apps/mobile/src/components/ComposerContextSheet.tsx b/apps/mobile/src/components/ComposerContextSheet.tsxindex 598e3cf10d1..2e93aee6381 100644--- a/apps/mobile/src/components/ComposerContextSheet.tsx+++ b/apps/mobile/src/components/ComposerContextSheet.tsx@@ -111,7 +111,7 @@ export function ComposerContextSheet(props: {: undefined;if (record && !("payload" in record) && (record.kind === "image" || record.kind === "file")) {const mimeType = videoMimeType(record) ?? record.mimeType;- const previewKind = filePreviewKind(record);+ const previewKind = filePreviewKind(record, { richDocuments: false });const resource = {_tag: "attachment" as const,attachmentId: record.attachmentId,diff --git a/apps/mobile/src/lib/attachmentDocument.ts b/apps/mobile/src/lib/attachmentDocument.tsindex 94d2ced4d0f..c19e2826898 100644--- a/apps/mobile/src/lib/attachmentDocument.ts+++ b/apps/mobile/src/lib/attachmentDocument.ts@@ -29,7 +29,7 @@ export function useAttachmentDocument(input: {readonly environmentId: EnvironmentId | null;readonly attachment: FileBackedComposerAttachment | null;}) {- const kind = filePreviewKind(input);+ const kind = filePreviewKind(input, { richDocuments: false });const delimiter = filePreviewDelimiter(input);const shareController = useRef<AbortController | null>(null);useEffect(() => () => shareController.current?.abort(), []);diff --git a/apps/mobile/src/lib/attachmentDocumentPresentation.test.ts b/apps/mobile/src/lib/attachmentDocumentPresentation.test.tsnew file mode 100644index 00000000000..4299c93ad65--- /dev/null+++ b/apps/mobile/src/lib/attachmentDocumentPresentation.test.ts@@ -0,0 +1,28 @@+import { expect, it } from "vite-plus/test";+import { filePreviewKind } from "@t3tools/shared/filePreview";++it.each([+ [+ "report.docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "unsupported",+ ],+ [+ "budget.xlsx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ "unsupported",+ ],+ [+ "deck.pptx",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ "unsupported",+ ],+ ["report.docx", "text/plain", "text"],+ ["report.docx", "application/octet-stream", "unsupported"],+ ["chart.mmd", "text/vnd.mermaid", "text"],+ ["chart.mermaid", "text/plain", "text"],+ ["chart.mmd", "application/octet-stream", "unsupported"],+ ["font.ttf", "font/ttf", "unsupported"],+] as const)("preserves mobile's existing path for %s (%s)", (name, mimeType, expected) => {+ expect(filePreviewKind({ name, mimeType }, { richDocuments: false })).toBe(expected);+});diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.tsindex b4b888af4b4..f6c3a0e5c55 100644--- a/apps/mobile/src/lib/composerContext.ts+++ b/apps/mobile/src/lib/composerContext.ts@@ -78,7 +78,7 @@ export function composerDocumentAttachmentRecord(): ComposerDocumentAttachment | null {if (!record || "payload" in record || record.kind !== "file") return null;if (videoMimeType(record) !== null) return null;- const kind = filePreviewKind(record);+ const kind = filePreviewKind(record, { richDocuments: false });if (kind === "image" || kind === "pdf" || kind === "video") return null;return record;}diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.tsindex cc36317899e..129bb1c388c 100644--- a/apps/server/src/assets/AssetAccess.test.ts+++ b/apps/server/src/assets/AssetAccess.test.ts@@ -915,9 +915,49 @@ describe("AssetAccess", () => {kind: "file",path: canonicalCssPath,});+ for (const extension of ["otf", "ttf", "woff", "woff2"]) {+ const fontName = `preview.${extension}`;+ const fontPath = path.join(root, fontName);+ yield* fileSystem.writeFileString(fontPath, "font bytes");+ const canonicalFontPath = yield* fileSystem.realPath(fontPath);+ for (const resource of [+ { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },+ { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },+ ]) {+ const url = yield* issueAssetUrl({ resource, workspaceRoot: root });+ const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);+ expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), fontName)).toEqual({+ kind: "file",+ path: canonicalFontPath,+ });+ }+ }expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();expect(yield* resolveAsset(token, ".env")).toBeNull();expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();+ for (const extension of [+ "docx",+ "xlsx",+ "pptx",+ "bmp",+ "heic",+ "tif",+ "tiff",+ "weba",+ "mmd",+ "mermaid",+ ]) {+ const siblingName = `private.${extension}`;+ yield* fileSystem.writeFileString(path.join(root, siblingName), "private sibling");+ for (const resource of [+ { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },+ { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },+ ]) {+ const url = yield* issueAssetUrl({ resource, workspaceRoot: root });+ const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);+ expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), siblingName)).toBeNull();+ }+ }}).pipe(Effect.provide(layerTest)),);@@ -955,6 +995,58 @@ describe("AssetAccess", () => {}).pipe(Effect.provide(layerTest)),);+ it.effect("issues exact workspace URLs for image, office, and font previews", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-asset-image-workspace-",+ });+ const assetsDirectory = path.join(root, "assets");+ yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });+ yield* fileSystem.writeFileString(+ path.join(assetsDirectory, "private.docx"),+ "private document",+ );+ for (const extension of [+ "png",+ "bmp",+ "heic",+ "tif",+ "tiff",+ "docx",+ "xlsx",+ "pptx",+ "ttf",+ "otf",+ "woff",+ "woff2",+ ]) {+ const name = `preview.${extension}`;+ const filePath = path.join(assetsDirectory, name);+ const siblingName = `other.${extension}`;+ yield* fileSystem.writeFileString(filePath, "preview");+ yield* fileSystem.writeFileString(+ path.join(assetsDirectory, siblingName),+ "private sibling",+ );+ const canonicalPath = yield* fileSystem.realPath(filePath);+ for (const resource of [+ { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: filePath },+ { _tag: "draft-workspace-file" as const, cwd: root, path: `assets/${name}` },+ ]) {+ const result = yield* issueAssetUrl({ resource, workspaceRoot: root });+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);+ const token = suffix.slice(0, suffix.indexOf("/"));+ expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalPath });+ expect(yield* resolveAsset(token, siblingName)).toBeNull();+ expect(yield* resolveAsset(token, "private.docx")).toBeNull();+ expect(yield* resolveAsset(token, `../${name}`)).toBeNull();+ }+ }+ }).pipe(Effect.provide(layerTest)),+ );+it.effect("previews workspace files with literal fragment characters in their paths", () =>Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;@@ -963,7 +1055,21 @@ describe("AssetAccess", () => {const directory = path.join(root, "assets#archive");yield* fileSystem.makeDirectory(directory);- for (const name of ["icon#v2.png", "report#draft.pdf"]) {+ for (const name of [+ "icon#v2.png",+ "report#draft.pdf",+ "report.docx",+ "workbook.xlsx",+ "slides.pptx",+ "specimen.ttf",+ "specimen.otf",+ "specimen.woff",+ "specimen.woff2",+ "image.bmp",+ "image.heic",+ "image.tif",+ "image.tiff",+ ]) {const filePath = path.join(directory, name);yield* fileSystem.writeFileString(filePath, "preview fixture");const canonicalFile = yield* fileSystem.realPath(filePath);@@ -1049,6 +1155,12 @@ describe("AssetAccess", () => {for (const [extension, mimeType] of [["pdf", "application/pdf"],["svg", "image/svg+xml"],+ ["bmp", "image/bmp"],+ ["ttf", "font/ttf"],+ ["otf", "font/otf"],+ ["woff", "font/woff"],+ ["woff2", "font/woff2"],+ ["weba", "audio/webm"],] as const) {const attachmentId = `thread-1-00000000-0000-4000-8000-000000000001-${extension}`;const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);@@ -1059,7 +1171,7 @@ describe("AssetAccess", () => {_tag: "attachment",attachmentId,fileName: `report.${extension}`,- mimeType,+ mimeType: "application/octet-stream",disposition: "inline",},});diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.tsindex f749cff8fe6..80afd46f177 100644--- a/apps/server/src/assets/AssetAccess.ts+++ b/apps/server/src/assets/AssetAccess.ts@@ -19,14 +19,14 @@ import {TurnItemId,} from "@t3tools/contracts";import {- audioMimeTypeFromExtension,hostPreviewMimeTypeFromExtension,+ officePreviewKind,isWorkspaceAudioPreviewPath,isWorkspaceImagePreviewPath,+ isWorkspaceFontPreviewPath,isWorkspacePreviewEntryPath,isWorkspaceVideoPreviewPath,WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,- WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,} from "@t3tools/shared/filePreview";import {IMAGE_DIMENSIONS_HEADER_BYTES,@@ -88,10 +88,20 @@ const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {htm: "text/html",};const inlinePreviewMimeTypeForExtension = (extension: string) =>- INLINE_PREVIEW_MIME_TYPES[extension] ?? audioMimeTypeFromExtension(`.${extension}`) ?? undefined;+ INLINE_PREVIEW_MIME_TYPES[extension] ??+ hostPreviewMimeTypeFromExtension(`.${extension}`) ??+ undefined;const PREVIEW_ASSET_EXTENSIONS = new Set([...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,- ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,+ // Keep HTML dependency grants independent of newly supported file viewers.+ ".avif",+ ".gif",+ ".ico",+ ".jpeg",+ ".jpg",+ ".png",+ ".svg",+ ".webp",".css",".js",".mjs",@@ -507,21 +517,24 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA? yield* readImageDimensionsFromHeader(canonicalFile): null;return {- claims: isWorkspaceImagePreviewPath(resolved.relativePath)- ? {- version: 1 as const,- kind: "workspace-file-exact" as const,- workspaceRoot: canonicalWorkspaceRoot,- relativePath: resolved.relativePath,- expiresAt: input.expiresAt,- }- : {- version: 1 as const,- kind: "workspace-file" as const,- workspaceRoot: canonicalWorkspaceRoot,- baseRelativePath: path.dirname(resolved.relativePath),- expiresAt: input.expiresAt,- },+ claims:+ isWorkspaceImagePreviewPath(resolved.relativePath) ||+ isWorkspaceFontPreviewPath(resolved.relativePath) ||+ officePreviewKind({ name: resolved.relativePath }) !== null+ ? {+ version: 1 as const,+ kind: "workspace-file-exact" as const,+ workspaceRoot: canonicalWorkspaceRoot,+ relativePath: resolved.relativePath,+ expiresAt: input.expiresAt,+ }+ : {+ version: 1 as const,+ kind: "workspace-file" as const,+ workspaceRoot: canonicalWorkspaceRoot,+ baseRelativePath: path.dirname(resolved.relativePath),+ expiresAt: input.expiresAt,+ },fileName: path.basename(resolved.relativePath),imageDimensions,fileRevision: undefined,diff --git a/apps/web/package.json b/apps/web/package.jsonindex 74516847d57..60cef6f0d5d 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -13,6 +13,10 @@},"dependencies": {"@base-ui/react": "^1.4.1",+ "@betteroffice/docx": "0.4.3",+ "@betteroffice/fonts": "0.4.0",+ "@betteroffice/pptx": "0.2.0",+ "@betteroffice/xlsx": "0.3.0","@clerk/clerk-js": "catalog:","@clerk/electron": "catalog:","@clerk/react": "catalog:",@@ -74,6 +78,7 @@"remark-gfm": "catalog:","remark-math": "6.0.0","remark-parse": "catalog:",+ "saxes": "6.0.0","tailwind-merge": "^3.4.0","unbash": "^5.0.0","unified": "catalog:",diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.tsindex 38096eb034c..c9eb37def61 100644--- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts+++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts@@ -18,7 +18,7 @@ import {} from "./composerAttachmentFiles";describe("composer attachment files", () => {- it("attaches SVG as a file and rejects other unsupported images", () => {+ it("keeps previewable images providers cannot accept on the file path", () => {expect(classifyComposerAttachmentFile({ name: "diagram.svg", type: "image/svg+xml" })).toBe("file",);@@ -26,12 +26,14 @@ describe("composer attachment files", () => {expect(classifyComposerAttachmentFile({ name: "diagram.svg", type: "application/octet-stream" }),).toBe("file");- expect(classifyComposerAttachmentFile({ name: "photo.tiff", type: "image/tiff" })).toBe(- "unsupported-image",- );+ expect(classifyComposerAttachmentFile({ name: "photo.tiff", type: "image/tiff" })).toBe("file");expect(classifyComposerAttachmentFile({ name: "report.pdf", type: "application/pdf" })).toBe("file",);+ expect(classifyComposerAttachmentFile({ name: "picture.bmp", type: "image/bmp" })).toBe("file");+ expect(+ classifyComposerAttachmentFile({ name: "layers.psd", type: "image/vnd.adobe.photoshop" }),+ ).toBe("unsupported-image");});it("keeps DNG originals on the file path without changing their bytes", async () => {@@ -96,7 +98,7 @@ describe("composer attachment files", () => {"image","image","image",- "unsupported-image",+ "file","unsupported-image",]);});@@ -112,20 +114,18 @@ describe("composer attachment files", () => {).toBe(false);});- it("claims SVG and unsupported image pastes even when text is present", () => {- const images = [- new File(["svg"], "diagram.svg", { type: "image/svg+xml" }),- new File(["tiff"], "photo.tiff", { type: "image/tiff" }),- ];+ it("claims SVG pastes even when text is present", () => {+ const image = new File(["svg"], "diagram.svg", { type: "image/svg+xml" });+ expect(+ shouldHandleComposerAttachmentPaste({ files: [image], plainText: "Image caption" }),+ ).toBe(true);+ });- for (const image of images) {- expect(- shouldHandleComposerAttachmentPaste({- files: [image],- plainText: "Image caption",- }),- ).toBe(true);- }+ it("preserves text when the clipboard also includes generic image files", () => {+ const image = new File(["tiff"], "photo.tiff", { type: "image/tiff" });+ expect(+ shouldHandleComposerAttachmentPaste({ files: [image], plainText: "Image caption" }),+ ).toBe(false);});it("uses the hard local limit while server config is unknown", () => {diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.tsindex 7454d1edbb7..283aef09dc8 100644--- a/apps/web/src/components/chat/composerAttachmentFiles.ts+++ b/apps/web/src/components/chat/composerAttachmentFiles.ts@@ -12,6 +12,7 @@ import type { ComposerFileAttachment, ComposerImageAttachment } from "../../compimport { isHeicImageFile } from "../../lib/imageCompression";import { isVideoAttachment, videoMimeType } from "../../types";import { isSvgAttachment } from "@t3tools/shared/image";+import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";type ComposerAttachmentFileKind = "image" | "file" | "unsupported-image";@@ -94,7 +95,9 @@ export function classifyComposerAttachmentFile(if (!file.type.toLowerCase().startsWith("image/")) {return "file";}- return isProviderSendTurnSupportedImageMimeType(file.type) ? "image" : "unsupported-image";+ if (isProviderSendTurnSupportedImageMimeType(file.type)) return "image";+ // These can be previewed as files, but providers must not receive them as images.+ return isWorkspaceImagePreviewPath(file.name) ? "file" : "unsupported-image";}export function isPreviewableComposerVideo(diff --git a/apps/web/src/components/desktop/SnapShotCoordinator.tsx b/apps/web/src/components/desktop/SnapShotCoordinator.tsxindex 132dcdccf9f..d1ff68f2aa2 100644--- a/apps/web/src/components/desktop/SnapShotCoordinator.tsx+++ b/apps/web/src/components/desktop/SnapShotCoordinator.tsx@@ -16,7 +16,6 @@ import { useHandleNewThread } from "../../hooks/useHandleNewThread";import { useStableCallback } from "../../hooks/useStableCallback";import { getClientSettings, useClientSettings } from "../../hooks/useSettings";import { readThreadShell } from "../../state/entities";-import { compressImageToByteLimit, dataUrlToFile } from "../../lib/imageCompression";import { resolveThreadActionProjectRef } from "../../lib/chatThreadActions";import {beginSnapShotAnimation,@@ -38,7 +37,6 @@ import {countQuestionRequestAttachments,openQuestionAttachmentDraft,} from "../../questionAttachments";-import { readFileAsDataUrl } from "../ChatView.logic";import { stackedThreadToast, toastManager } from "../ui/toast";type CaptureTarget = DraftId | ScopedThreadRef;@@ -163,6 +161,8 @@ export async function deliverSnapShot(const store = useComposerDraftStore.getState();updateSnapShotAnimationSource(item.id, item.source);const capture = await bridge.readSnapShot(item.id);+ const { compressImageToByteLimit, dataUrlToFile, readFileAsDataUrl } =+ await import("../../lib/imageCompression");const original = dataUrlToFile(capture.dataUrl, capture.name, capture.mimeType);const compressed = await compressImageToByteLimit(original, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);if (!compressed.ok) {diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsxnew file mode 100644index 00000000000..81ab18e607d--- /dev/null+++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx@@ -0,0 +1,1271 @@+import { act, render, stubGlobal, type Screen } from "../../../test/render";+import { EnvironmentId } from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";+import { page } from "vite-plus/test/browser";+import "~/index.css";++const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));++vi.mock(import("~/assets/assetUrls"), async (original) => ({+ ...(await original()),+ useAssetUrlRefresh: () => refresh,+}));+// The real source view highlights through a worker pool; the text it receives is what matters here.+// Never load the original: its highlighter graph can outlast waitFor on a cold CI browser.+vi.mock(import("./ReadOnlySourcePreview"), () => ({+ default: ({ text }: { text: string }) => <pre>{text}</pre>,+}));++import { AttachmentFilePreview } from "./AttachmentFilePreview";+import { OfficeFilePreview } from "./OfficeFilePreview";+import { MermaidFilePreview } from "./MermaidFilePreview";+import { OFFICE_PREVIEW_MAX_COLUMNS, type OfficeWorkerResult } from "./officePreviewProtocol";++it.each(["<w:body/>", "<w:body></w:body>"])(+ "opens an empty Word document with %s",+ async (body) => {+ const { default: JSZip } = await import("jszip");+ const { prepareOffice } = await import("./officeArchive");+ const archive = new JSZip().file(+ "word/document.xml",+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${body}</w:document>`,+ );+ const prepared = await prepareOffice(+ await archive.generateAsync({ type: "arraybuffer" }),+ "docx",+ );+ const result = await JSZip.loadAsync(prepared.bytes);+ const xml = new DOMParser().parseFromString(+ await result.file("word/document.xml")!.async("string"),+ "application/xml",+ );+ expect(xml.querySelector("parsererror")).toBeNull();+ expect(+ xml.getElementsByTagNameNS(+ "http://schemas.openxmlformats.org/wordprocessingml/2006/main",+ "body",+ ),+ ).toHaveLength(1);+ },+);++it.each([false, true])(+ "rejects excessive archive entries before JSZip (directories: %s)",+ async (directories) => {+ const { default: JSZip } = await import("jszip");+ const { prepareOffice } = await import("./officeArchive");+ const archive = new JSZip();+ for (let i = 0; i < 4096; i++)+ archive.file(`entry-${i}${directories ? "/" : ".txt"}`, "", { dir: directories });+ const bytes = await archive.generateAsync({ type: "arraybuffer" });+ const load = vi.spyOn(JSZip, "loadAsync");+ try {+ await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");+ expect(load).not.toHaveBeenCalled();+ // The actual central-directory records must also be bounded if EOCD lies.+ const view = new DataView(bytes);+ view.setUint16(bytes.byteLength - 22 + 8, 1, true);+ view.setUint16(bytes.byteLength - 22 + 10, 1, true);+ await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");+ expect(load).not.toHaveBeenCalled();+ } finally {+ load.mockRestore();+ }+ },+);++it("rejects oversized embedded images before decoding pixels and retains ordinary images", async () => {+ const { officeImageBitmap } = await import("./office/image-bitmap");+ const canvas = new OffscreenCanvas(2, 3);+ canvas.getContext("2d");+ const blob = await canvas.convertToBlob({ type: "image/png" });+ const bytes = await blob.arrayBuffer();+ new DataView(bytes).setUint32(16, 12000);+ new DataView(bytes).setUint32(20, 12000);+ const decode = vi.spyOn(globalThis, "createImageBitmap");+ try {+ await expect(officeImageBitmap(new Blob([bytes]))).rejects.toThrow("pixel limit");+ expect(decode).not.toHaveBeenCalled();+ const bitmap = await officeImageBitmap(blob);+ expect([bitmap.width, bitmap.height]).toEqual([2, 3]);+ bitmap.close();+ } finally {+ decode.mockRestore();+ }+});++it.each(["utf-16le", "utf-16be", "windows-1252"])(+ "preserves %s Office XML and safe hyperlink targets",+ async (encoding) => {+ const { default: JSZip } = await import("jszip");+ const { prepareOffice } = await import("./officeArchive");+ const archive = new JSZip();+ const encode = (text: string) => {+ const xml = `<?xml version="1.0" encoding="${encoding}"?>${text}`;+ if (encoding === "windows-1252") return Uint8Array.from(xml, (char) => char.charCodeAt(0));+ const bytes = new Uint8Array(2 + xml.length * 2);+ const view = new DataView(bytes.buffer);+ const little = encoding === "utf-16le";+ view.setUint16(0, 0xfeff, little);+ for (let i = 0; i < xml.length; i++) view.setUint16(2 + i * 2, xml.charCodeAt(i), little);+ return bytes;+ };+ archive.file(+ "word/document.xml",+ encode(+ '<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>',+ ),+ );+ archive.file(+ "word/_rels/document.xml.rels",+ encode(+ `<Relationships>${["https://example.com/page", "http://example.com", "mailto:[email protected]", "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>`,+ ),+ );+ const prepared = await prepareOffice(+ await archive.generateAsync({ type: "arraybuffer" }),+ "docx",+ );+ const result = await JSZip.loadAsync(prepared.bytes);+ expect(await result.file("word/document.xml")!.async("string")).toContain("café");+ const links = await result.file("word/_rels/document.xml.rels")!.async("string");+ expect(links).toContain('encoding="UTF-8"');+ expect(links).toContain("https://example.com/page");+ expect(links).toContain("http://example.com");+ expect(links).toContain("mailto:[email protected]");+ expect(links).not.toContain("javascript:");+ expect(links).not.toContain("file:");+ },+);++it.each([+ ["", "worksheets/./sheet1.xml", false],+ ["x:", "../xl/worksheets/sheet1.xml", false],+ ["", "/xl/worksheets/sheet1.xml", true],+])("preserves %sworksheet metadata with relationship target %s", async (prefix, target, empty) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ const ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";+ archive.file(+ "xl/workbook.xml",+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="s"/></sheets></workbook>',+ );+ archive.file(+ "xl/_rels/workbook.xml.rels",+ `<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}"/></Relationships>`,+ );+ archive.file(+ "xl/worksheets/sheet1.xml",+ `<${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>`+ .replace(/<((?:x:)?(?:col|dimension|mergeCell))\b([^>]*)\/>/g, prefix ? "<$1$2></$1>" : "$&")+ .replace(/<sheetData>[\s\S]*?<\/sheetData>/, (data) => (empty ? "<sheetData/>" : data))+ .replace(/="([^"]*)"/g, (attribute, value: string) =>+ prefix || empty+ ? ` = '${value.replace(/\d/g, (digit) => `&#${digit.charCodeAt(0)};`)}'`+ : attribute,+ ),+ );+ const bytes = await archive.generateAsync({ type: "arraybuffer" });+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {+ type: "module",+ });+ try {+ const result = await new Promise<OfficeWorkerResult>((resolve) => {+ worker.addEventListener(+ "message",+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),+ { once: true },+ );+ worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);+ });+ expect(result.type).toBe("xlsx");+ if (result.type !== "xlsx") throw new Error("Expected bounded workbook");+ const bounded = await JSZip.loadAsync(result.bytes);+ const sheet = new DOMParser().parseFromString(+ await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),+ "application/xml",+ );+ expect(sheet.querySelector("parsererror")).toBeNull();+ const row = sheet.getElementsByTagNameNS(ns, "row")[0];+ if (empty) expect(row).toBeUndefined();+ else {+ expect(row!.getAttribute("ht")).toBe("42");+ expect(row!.getAttribute("hidden")).toBe("1");+ expect(row!.getElementsByTagNameNS(ns, "c")[0]!.getAttribute("r")).toBe("A50");+ expect(row!.getElementsByTagNameNS(ns, "t")[0]!.textContent).toHaveLength(4096);+ }+ expect(sheet.getElementsByTagNameNS(ns, "dimension")).toHaveLength(0);+ expect(sheet.getElementsByTagNameNS(ns, "mergeCell")).toHaveLength(0);+ const columns = sheet.getElementsByTagNameNS(ns, "col");+ expect(columns).toHaveLength(1);+ expect(columns[0]!.getAttribute("min")).toBe(String(OFFICE_PREVIEW_MAX_COLUMNS - 1));+ expect(columns[0]!.getAttribute("max")).toBe(String(OFFICE_PREVIEW_MAX_COLUMNS));+ } finally {+ worker.terminate();+ }+});++it("reports the final slide at maximum scroll after page visibility changes", async () => {+ const { OfficePages } = await import("./office/OfficePages");+ const changed = vi.fn();+ const container = document.createElement("div");+ container.style.cssText = "display:flex;flex-direction:column;width:400px;height:400px";+ await using screen = await render(+ <OfficePages+ pages={Array.from({ length: 6 }, () => ({ width: 400, height: 240 }))}+ label="Slide"+ paint={async () => undefined}+ onPageChange={changed}+ onError={(error) => {+ throw error;+ }}+ />,+ { container },+ );+ const scroller = screen.container.querySelector<HTMLElement>("[data-office-pages]")!;+ await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(scroller.clientHeight));+ await act(() => {+ scroller.scrollTop = scroller.scrollHeight;+ });+ await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(5));+ await act(() => {+ scroller.scrollTop = 10;+ });+ await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(0));+});++it("preserves merged text across tile clears", async () => {+ const { paintFrame } = await import("./office/sheet-frame");+ const canvas = new OffscreenCanvas(400, 80);+ const context = canvas.getContext("2d")!;+ paintFrame(+ context,+ {+ viewport: { x: 0, y: 0, width: 400, height: 80 },+ list: { width: 400, height: 80, commands: [] },+ tiles: [+ {+ x: 0,+ y: 0,+ clipX: 0,+ clipY: 0,+ list: {+ width: 208,+ height: 80,+ commands: [+ {+ op: "text",+ x: 2,+ y: 40,+ text: "MMMMMMMMMMMMMMMMMMMMMMMM",+ fontSize: 20,+ color: "#000",+ clip: { x: 0, y: 0, w: 400, h: 80 },+ },+ ],+ },+ },+ { x: 192, y: 0, clipX: 200, clipY: 0, list: { width: 208, height: 80, commands: [] } },+ ],+ },+ { ratio: 1, origin: { x: 0, y: 0 } },+ );+ const pixels = context.getImageData(240, 15, 100, 35).data;+ expect(pixels.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);+});++it.each([+ "paragraphs",+ "runs",+ "tables",+ "auxiliary XML",+ "XML bytes",+ "renamed XML",+ "section after prefix",+ "oversized section",+])("bounds excessive Word %s before rendering DOM", async (scenario) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ const body = ["paragraphs", "section after prefix", "oversized section"].includes(scenario)+ ? "<w:p><w:r><w:t>x</w:t></w:r></w:p>".repeat(200_000)+ : scenario === "runs"+ ? `<w:p>${"<w:r><w:t>x</w:t></w:r>".repeat(50_001)}</w:p>`+ : scenario === "tables"+ ? "<w:tbl/>".repeat(50_001)+ : scenario === "XML bytes"+ ? `<w:p><w:r><w:t>${"x".repeat(2 * 1024 * 1024)}</w:t></w:r></w:p>`+ : "<w:p/>";+ const section =+ '<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>';+ archive.file(+ "word/document.xml",+ `<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>`,+ );+ if (scenario === "auxiliary XML" || scenario === "renamed XML")+ archive.file(+ scenario === "renamed XML" ? "word/footnotes.dat" : "word/footnotes.xml",+ `<w:footnotes>${"<w:p/>".repeat(50_001)}</w:footnotes>`,+ );+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });+ const src = URL.createObjectURL(file);+ try {+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {+ type: "module",+ });+ try {+ const result = await new Promise<OfficeWorkerResult>((resolve) => {+ worker.addEventListener(+ "message",+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),+ { once: true },+ );+ void file+ .arrayBuffer()+ .then((bytes) => worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]));+ });+ if (+ scenario === "auxiliary XML" ||+ scenario === "renamed XML" ||+ scenario === "oversized section"+ ) {+ expect(result).toMatchObject({+ type: "error",+ message: expect.stringContaining("Preview limited"),+ });+ } else {+ expect(result.type).toBe("docx");+ if (result.type !== "docx") throw new Error("Expected a Word prefix");+ expect(result.truncated).toBe(true);+ const bounded = await JSZip.loadAsync(result.bytes);+ const markup = await bounded.file("word/document.xml")!.async("string");+ {+ const xml = markup;+ const document = new DOMParser().parseFromString(xml, "application/xml");+ expect(document.querySelector("parsererror")).toBeNull();+ const bodies = document.getElementsByTagNameNS("*", "body");+ expect(bodies).toHaveLength(1);+ const section = bodies[0]!.lastElementChild!;+ expect(section.localName).toBe("sectPr");+ const size = section.getElementsByTagNameNS("*", "pgSz")[0]!;+ expect(size.getAttributeNS(section.namespaceURI, "w")).toBe(+ scenario === "section after prefix" ? "11906" : "16838",+ );+ expect(size.getAttributeNS(section.namespaceURI, "orient")).toBe(+ scenario === "section after prefix" ? null : "landscape",+ );+ }+ expect(markup.length).toBeLessThan(body.length);+ expect(markup.length).toBeLessThanOrEqual(3 * 1024 * 1024);+ expect(markup.match(/<(?![!?/])/g)!.length).toBeLessThanOrEqual(100_000);+ }+ } finally {+ worker.terminate();+ }+ } finally {+ URL.revokeObjectURL(src);+ }+});++it.each([+ "relationship markup",+ "relationship bytes",+ "content type",+ "metadata type",+ "deep XML",+ "query path",+])("bounds XML hidden in media by %s", async (scenario) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ const path = `word/media/payload.png${scenario === "query path" ? "?xml" : ""}`;+ archive.file(+ "word/document.xml",+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p/></w:body></w:document>',+ );+ archive.file(+ "[Content_Types].xml",+ `<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>`,+ );+ archive.file(+ "word/_rels/document.xml.rels",+ `<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>`,+ );+ archive.file(+ path,+ scenario === "relationship bytes"+ ? `<styles>${"x".repeat(1024 * 1024)}</styles>`+ : scenario === "deep XML"+ ? `${"<styles>".repeat(65)}${"</styles>".repeat(65)}`+ : `<styles>${"<style/>".repeat(50_001)}</styles>`,+ );+ const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {+ type: "module",+ });+ try {+ const result = await new Promise<OfficeWorkerResult>((resolve) => {+ worker.addEventListener(+ "message",+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),+ { once: true },+ );+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);+ });+ expect(result).toMatchObject({+ type: "error",+ message: expect.stringContaining("Preview limited"),+ });+ } finally {+ worker.terminate();+ }+});++it.each([+ "footnotes",+ "note roots",+ "endnotes",+ "header",+ "footer",+ "comments",+ "styles",+ "style chain",+ "style count",+ "style visits",+ "numbering",+ "picture numbering",+])("keeps the body and warns when omitting expanded %s", async (role) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";+ const type = role.startsWith("style")+ ? "styles"+ : role === "picture numbering"+ ? "numbering"+ : role === "note roots"+ ? "footnotes"+ : role;+ archive.file(+ "_rels/.rels",+ '<Relationships><Relationship Id="doc" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',+ );+ const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;+ archive.file(+ "word/document.xml",+ `<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>`,+ );+ archive.file(+ "word/_rels/document.xml.rels",+ `<Relationships><Relationship Id="aux" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="media/aux.xml"/></Relationships>`,+ );+ const xml =+ role === "style chain" || role === "style count" || role === "style visits"+ ? `<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>`+ : role === "styles"+ ? `<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>`+ : role.includes("numbering")+ ? `<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>`+ : role === "header" || role === "footer"+ ? `<w:${role === "header" ? "hdr" : "ftr"} xmlns:w="${ns}">${text("omitted payload").repeat(2_000)}</w:${role === "header" ? "hdr" : "ftr"}>`+ : `<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}>`;+ archive.file("word/media/aux.xml", xml);+ if (role === "note roots") {+ archive.file(+ "word/document.xml",+ `<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>`,+ );+ archive.file(+ "word/media/aux.xml",+ `<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>`,+ );+ }+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });+ if (role === "note roots") {+ const { SaxesParser } = await import("saxes");+ const { prepareOffice } = await import("./officeArchive");+ const parse = vi.spyOn(SaxesParser.prototype, "write");+ try {+ expect((await prepareOffice(await file.arrayBuffer(), "docx")).truncated).toBe(true);+ expect(+ parse.mock.calls.reduce(+ (sum, [chunk]) => sum + (typeof chunk === "string" ? chunk.length : 0),+ 0,+ ),+ ).toBeLessThan(4 * 1024 * 1024);+ } finally {+ parse.mockRestore();+ }+ }+ const src = URL.createObjectURL(file);+ try {+ const container = document.createElement("div");+ container.style.cssText = "display:flex;flex-direction:column;width:640px;height:700px";+ await using screen = await render(+ <OfficeFilePreview src={src} name="expanded.docx" kind="docx" sizeBytes={file.size} />,+ { container },+ );+ await vi.waitFor(+ () => {+ expect(screen.container.querySelector('[role="alert"]')?.textContent ?? "").toBe("");+ expect(screen.container.textContent).toContain("body retained");+ },+ { timeout: 30_000 },+ );+ expect(screen.container.textContent).toContain("Preview limited");+ expect(screen.container.textContent).not.toContain("omitted payload");+ await vi.waitFor(() =>+ expect(screen.container.querySelector("canvas")!.width).toBeGreaterThan(0),+ );+ } finally {+ URL.revokeObjectURL(src);+ }+});++it.each([+ "ordinary parts",+ "unused parts",+ "independent styles",+ "inherited styles",+ "python-docx package",+ "default template styles",+ "binary package properties",+])("retains Word %s without a limit warning", async (scenario) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";+ const r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";+ const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;+ archive.file(+ "_rels/.rels",+ `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/></Relationships>`,+ );+ if (scenario === "python-docx package" || scenario === "binary package properties") {+ const packageRelationships = "http://schemas.openxmlformats.org/package/2006/relationships";+ archive.file(+ "_rels/.rels",+ `<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>`,+ );+ archive.file(+ "[Content_Types].xml",+ '<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>',+ );+ archive.file(+ "docProps/thumbnail.jpeg",+ new Uint8Array([255, 216, 255, 224, 0, 16, 74, 70, 73, 70]),+ );+ archive.file("_xmlsignatures/origin.sigs", new Uint8Array());+ for (const part of ["core", "app", "custom"])+ archive.file(`docProps/${part}.xml`, '<properties xmlns="urn:properties"/>');+ if (scenario === "binary package properties") {+ const roles = [+ `${packageRelationships}/metadata/core-properties`,+ `${r}/extended-properties`,+ `${packageRelationships}/metadata/custom-properties`,+ `${packageRelationships}/digital-signature/signature`,+ ];+ archive.file(+ "_rels/.rels",+ `<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>`,+ );+ for (const i of roles.keys())+ archive.file(`docProps/metadata${i}.dat`, new Uint8Array([255, 216, 255, 0]));+ }+ }+ const ordinary = scenario === "ordinary parts";+ archive.file(+ "word/document.xml",+ `<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>`,+ );+ archive.file(+ "word/_rels/document.xml.rels",+ `<Relationships>${["header", "footer", "footnotes", "endnotes", "comments", "fontTable", "styles"].map((role) => `<Relationship Id="${role}" Type="${r}/${role}" Target="${role}.xml"/>`).join("")}</Relationships>`,+ );+ for (const [role, root] of [+ ["header", "hdr"],+ ["footer", "ftr"],+ ])+ archive.file(+ `word/${role}.xml`,+ `<w:${root} xmlns:w="${ns}">${text(`${role} retained`)}</w:${root}>`,+ );+ for (const role of ["footnotes", "endnotes", "comments"])+ archive.file(+ `word/${role}.xml`,+ `<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}>`,+ );+ archive.file(+ "word/fontTable.xml",+ `<w:fonts xmlns:w="${ns}"><w:font w:name="unused"/></w:fonts>`,+ );+ archive.file(+ "word/styles.xml",+ `<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>`,+ );+ if (scenario === "default template styles") {+ const heading =+ '<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>';+ const conditions = [+ "wholeTable",+ "firstRow",+ "lastRow",+ "firstCol",+ "lastCol",+ "band1Horz",+ "band2Horz",+ "band1Vert",+ "band2Vert",+ ];+ archive.file(+ "word/styles.xml",+ `<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>`,+ );+ archive.file(+ "word/_rels/document.xml.rels",+ (await archive.file("word/_rels/document.xml.rels")!.async("string")).replace(+ "</Relationships>",+ `<Relationship Id="numbering" Type="${r}/numbering" Target="numbering.xml"/></Relationships>`,+ ),+ );+ archive.file(+ "word/numbering.xml",+ `<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>`,+ );+ const document = await archive.file("word/document.xml")!.async("string");+ archive.file(+ "word/document.xml",+ document.replace(+ "<w:sectPr>",+ '<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>',+ ),+ );+ }+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });+ const src = URL.createObjectURL(file);+ try {+ const container = document.createElement("div");+ container.style.cssText = "display:flex;flex-direction:column;width:640px;height:700px";+ await using screen = await render(+ <OfficeFilePreview src={src} name="ordinary.docx" kind="docx" />,+ { container },+ );+ await vi.waitFor(() => expect(screen.container.textContent).toContain("ordinary body"), {+ timeout: 30_000,+ });+ expect(screen.container.textContent).not.toContain("Preview limited");+ await vi.waitFor(() =>+ expect(screen.container.querySelector("canvas")!.width).toBeGreaterThan(0),+ );+ if (scenario === "default template styles")+ expect(screen.container.textContent).toContain("styled cell");+ if (ordinary) {+ expect(screen.container.textContent).toContain("header retained");+ expect(screen.container.textContent).toContain("footer retained");+ }+ } finally {+ URL.revokeObjectURL(src);+ }+});++it.each([false, true])(+ "bounds shared-string text including CDATA %s per cell and across sheets in the worker and viewer",+ async (cdata) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ archive.file(+ "xl/workbook.xml",+ '<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>',+ );+ archive.file(+ "xl/_rels/workbook.xml.rels",+ '<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',+ );+ const sharedPath = cdata ? "customStrings.xml" : "sharedStrings.xml";+ archive.file(+ "xl/_rels/workbook.xml.rels",+ (await archive.file("xl/_rels/workbook.xml.rels")!.async("string")).replace(+ "</Relationships>",+ `<Relationship Id="strings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="${sharedPath}"/></Relationships>`,+ ),+ );+ const content = "x".repeat(32_767);+ archive.file(+ `xl/${sharedPath}`,+ `<sst><si><t>${cdata ? `<![CDATA[${content}]]>` : content}</t></si></sst>`,+ );+ archive.file(+ "xl/worksheets/sheet1.xml",+ `<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(+ '<c r="A1" t="s"><v><![CDATA[0]]></v></c>',+ `<c r="A1" t="inlineStr"><is><t><![CDATA[${content}]]></t></is></c>`,+ ),+ );+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {+ type: "module",+ });+ try {+ const result = await new Promise<OfficeWorkerResult>((resolve) => {+ worker.addEventListener(+ "message",+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),+ { once: true },+ );+ void file+ .arrayBuffer()+ .then((bytes) => worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]));+ });+ expect(result.type).toBe("xlsx");+ if (result.type !== "xlsx") throw new Error("Expected bounded workbook");+ const bounded = await JSZip.loadAsync(result.bytes);+ const sheet = new DOMParser().parseFromString(+ await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),+ "application/xml",+ );+ const cells = [...sheet.getElementsByTagName("t")].map((cell) => cell.textContent ?? "");+ expect(cells.reduce((total, cell) => total + cell.length, 0)).toBe(1024 * 1024);+ expect(Math.max(...cells.map((cell) => cell.length))).toBe(4096);+ expect(result.truncated).toBe(true);+ } finally {+ worker.terminate();+ }+ const src = URL.createObjectURL(file);+ try {+ const container = document.createElement("div");+ container.style.cssText = "display:flex;flex-direction:column;width:640px;height:480px";+ await using screen = await render(+ <OfficeFilePreview src={src} name="shared.xlsx" kind="xlsx" />,+ { container },+ );+ await vi.waitFor(+ () =>+ expect(screen.container.querySelector('[role="gridcell"]')?.textContent).toHaveLength(+ 4096,+ ),+ { timeout: 30_000 },+ );+ expect(screen.container.textContent).toContain("Preview limited");+ const canvas = screen.container.querySelector("canvas")!;+ await vi.waitFor(() => expect(canvas.width).toBeGreaterThan(0));+ const scroll = screen.container.querySelector<HTMLElement>('[role="grid"]')!;+ await act(() => {+ scroll.scrollTop = 200;+ scroll.scrollLeft = 200;+ });+ await vi.waitFor(() => expect(scroll.scrollTop).toBe(200));+ expect(canvas.getBoundingClientRect().top).toBeCloseTo(scroll.getBoundingClientRect().top, 0);+ } finally {+ URL.revokeObjectURL(src);+ }+ },+);++it.each([1, 145])(+ "counts shared Word settings once with %s text repetitions",+ async (repetitions) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";+ archive.file(+ "word/document.xml",+ `<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>`,+ );+ archive.file(+ "word/_rels/document.xml.rels",+ '<Relationships><Relationship Id="settings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/></Relationships>',+ );+ const settings = `<w:settings xmlns:w="${ns}"><w:unused>${"s".repeat(120_000)}</w:unused></w:settings>`;+ archive.file("word/settings.xml", settings);+ const bytes = await archive.generateAsync({ type: "arraybuffer" });+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {+ type: "module",+ });+ try {+ const result = await new Promise<OfficeWorkerResult>((resolve) => {+ worker.addEventListener(+ "message",+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),+ { once: true },+ );+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);+ });+ expect(result.type).toBe("docx");+ if (result.type !== "docx") throw new Error("Expected a Word prefix");+ expect(result.truncated).toBe(repetitions > 1);+ const bounded = await JSZip.loadAsync(result.bytes);+ const document = await bounded.file("word/document.xml")!.async("string");+ const retainedSettings = await bounded.file("word/settings.xml")!.async("string");+ expect(document.match(/<w:p>/g)!.length).toBeGreaterThan(100);+ expect(document.length + retainedSettings.length).toBeLessThanOrEqual(3 * 1024 * 1024);+ } finally {+ worker.terminate();+ }+ },+);++it.each(["repeated binary", "XML relationship alias", "duplicate relationship ID"])(+ "bounds Word image expansion for %s",+ async (scenario) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ archive.file(+ "[Content_Types].xml",+ '<Types><Default Extension="png" ContentType="image/png"/></Types>',+ );+ archive.file(+ "word/_rels/document.xml.rels",+ `<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>`,+ );+ archive.file(+ "word/media/payload.png",+ scenario === "XML relationship alias" ? "<styles/>" : new Uint8Array(8 * 1024 * 1024),+ );+ if (scenario === "duplicate relationship ID")+ archive.file("word/media/tiny.png", new Uint8Array(1));+ archive.file(+ "word/document.xml",+ `<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>`,+ );+ const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {+ type: "module",+ });+ try {+ const result = await new Promise<OfficeWorkerResult>((resolve) => {+ worker.addEventListener(+ "message",+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),+ { once: true },+ );+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);+ });+ expect(result).toMatchObject({+ type: "error",+ message: expect.stringContaining("expanded markup"),+ });+ } finally {+ worker.terminate();+ }+ },+);++it.each(["XFD200", "XFD1048576", "AX500", "AZ9999999"])(+ "bounds spreadsheet cells at %s before padding",+ async (ref) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ archive.file(+ "xl/workbook.xml",+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="rId1"/></sheets></workbook>',+ );+ // A nonstandard relationship target must get the same bounds.+ archive.file(+ "xl/_rels/workbook.xml.rels",+ '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="custom.xml"/></Relationships>',+ );+ archive.file(+ "xl/custom.xml",+ `<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>`,+ );+ const bytes = await archive.generateAsync({ type: "arraybuffer" });+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {+ type: "module",+ });+ try {+ const result = await new Promise<OfficeWorkerResult>((resolve) => {+ worker.addEventListener(+ "message",+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),+ { once: true },+ );+ worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);+ });+ if (ref === "AZ9999999") {+ expect(result).toMatchObject({+ type: "error",+ message: expect.stringContaining("invalid"),+ });+ } else {+ expect(result.type).toBe("xlsx");+ if (result.type !== "xlsx") throw new Error("Expected workbook values");+ const bounded = await JSZip.loadAsync(result.bytes);+ const sheet = new DOMParser().parseFromString(+ await bounded.file("xl/custom.xml")!.async("string"),+ "application/xml",+ );+ expect(sheet.querySelector('c[r="A1"] v')?.textContent).toBe("7");+ expect(sheet.querySelectorAll("row").length).toBeLessThanOrEqual(500);+ expect(result.truncated).toBe(ref !== "AX500");+ if (ref === "AX500") expect(sheet.querySelector('c[r="AX500"] v')?.textContent).toBe("9");+ else expect(sheet.querySelector('c[r="' + ref + '"]')).toBeNull();+ }+ } finally {+ worker.terminate();+ }+ },+);++it("keeps spreadsheet dates on their calendar day west of UTC", async () => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ archive.file(+ "xl/workbook.xml",+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Dates" sheetId="1" r:id="rId1"/></sheets></workbook>',+ );+ archive.file(+ "xl/_rels/workbook.xml.rels",+ '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',+ );+ archive.file(+ "xl/styles.xml",+ '<styleSheet><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/></cellXfs></styleSheet>',+ );+ archive.file(+ "xl/worksheets/sheet1.xml",+ '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>46023</v></c></row></sheetData></worksheet>',+ );+ const bytes = await archive.generateAsync({ type: "arraybuffer" });+ const workerModule = new URL(+ "./office/spreadsheet.worker.ts?worker_file&type=module",+ import.meta.url,+ ).href;+ // Give the worker a west-of-UTC default while preserving explicit format options.+ const bootstrap = URL.createObjectURL(+ new Blob(+ [+ `+ const NativeURL = URL;+ globalThis.URL = class extends NativeURL {+ constructor(input, base) { super(input, base?.startsWith("blob:") ? ${JSON.stringify(location.href)} : base); }+ };+ const format = Date.prototype.toLocaleDateString;+ Date.prototype.toLocaleDateString = function(locale, options) {+ return format.call(this, "en-US", { timeZone: "America/Los_Angeles", ...options });+ };+ await import(${JSON.stringify(workerModule)});+ postMessage({ type: "ready" });+ `,+ ],+ { type: "text/javascript" },+ ),+ );+ const worker = new Worker(bootstrap, { type: "module" });+ try {+ await new Promise<void>((resolve, reject) => {+ worker.addEventListener(+ "message",+ (event) => {+ if (event.data.type === "ready") resolve();+ },+ { once: true },+ );+ worker.addEventListener("error", (event) => reject(new Error(event.message)), { once: true });+ });+ const { createWorkerClient } = await import("./office/worker-rpc");+ const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);+ await client.call("open", { bytes }, { transfer: [bytes] });+ const cells = await client.call("cells", {+ sheet: 0,+ range: { top: 0, bottom: 0, left: 0, right: 0 },+ });+ expect(cells[0]![0]).toMatch(/^1\/1\/(26|2026)$/);+ } finally {+ worker.terminate();+ URL.revokeObjectURL(bootstrap);+ }+});++it.each([60, 100])("renders all %i pages of a table-heavy Word report", async (pages) => {+ const { default: JSZip } = await import("jszip");+ const archive = new JSZip();+ const paragraph = (text: string) =>+ `<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>`;+ archive.file(+ "word/document.xml",+ `<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>`,+ );+ archive.file(+ "_rels/.rels",+ '<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>',+ );+ archive.file(+ "[Content_Types].xml",+ '<Types><Default Extension="png" ContentType="image/png"/></Types>',+ );+ // Binary media must not consume the document's markup budget.+ archive.file("word/media/image.png", new Uint8Array(2_500_000));+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });+ await using screen = await render(+ <AttachmentFilePreview+ name="report.docx"+ mimeType="application/octet-stream"+ file={file}+ sizeBytes={file.size}+ />,+ );+ await vi.waitFor(() => expect(screen.container.textContent).toMatch(/\d+ pages/), {+ timeout: 30_000,+ });+ expect(screen.container.textContent).not.toContain("Preview limited");+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();+ const scroll = screen.container.querySelector<HTMLElement>("[data-office-pages]")!;+ await act(() => scroll.scrollTo({ top: scroll.scrollHeight }));+ await vi.waitFor(() => expect(screen.container.textContent).toContain("page " + pages), {+ timeout: 30_000,+ });+});++describe("standalone Mermaid previews", () => {+ it.each([+ 'A@{ "img": "//attacker.invalid/pixel.png" }',+ 'A@{ "im\\u0067": "/pixel.png" }',+ "A@{ label: &key img, *key: '/pixel.png' }",+ 'A["<img src=//attacker.invalid/pixel.png>"]',+ ])("rejects resource syntax before Mermaid lays out %s", async (node) => {+ using imageSource = vi+ .spyOn(HTMLImageElement.prototype, "src", "set")+ .mockImplementation(() => {});+ await using screen = await render(<MermaidFilePreview text={`flowchart LR\n${node}`} />);+ await vi.waitFor(() =>+ expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain(+ "Show Mermaid source",+ ),+ );+ expect(imageSource).not.toHaveBeenCalled();+ expect(screen.container.querySelector("svg")).toBeNull();+ });++ it.each(["<-->", "<==>", "<-.->", "-->"])("renders the %s arrow", async (arrow) => {+ await using screen = await render(<MermaidFilePreview text={`flowchart LR\nA ${arrow} B`} />);+ await vi.waitFor(+ () => {+ const diagram = screen.container.querySelector("svg");+ expect(diagram?.querySelector("path")).not.toBeNull();+ expect(diagram?.textContent).toContain("A");+ expect(diagram?.textContent).toContain("B");+ },+ { timeout: 10_000 },+ );+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();+ });+});++it("reloads a workspace Word file after a preview remount", async () => {+ const { default: JSZip } = await import("jszip");+ let heading = "Original outlook";+ using _fetch = stubGlobal(+ "fetch",+ vi.fn(async () => {+ const archive = new JSZip().file(+ "word/document.xml",+ `<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>`,+ );+ return new Response(await archive.generateAsync({ type: "arraybuffer" }));+ }),+ );+ refresh.mockReset().mockResolvedValue("https://example.com/workspace.docx");+ const asset = { environmentId: EnvironmentId.make("test-environment"), attachmentId: "word" };+ await using screen = await render(+ <AttachmentFilePreview+ key="original"+ name="outlook.docx"+ mimeType="application/octet-stream"+ sizeBytes={0}+ asset={asset}+ />,+ );+ await vi.waitFor(() => expect(screen.container.textContent).toContain("Original outlook"), {+ timeout: 10_000,+ });+ heading = "Revised outlook";+ await screen.rerender(+ <AttachmentFilePreview+ key="refreshed"+ name="outlook.docx"+ mimeType="application/octet-stream"+ sizeBytes={0}+ asset={asset}+ />,+ );+ await vi.waitFor(() => expect(screen.container.textContent).toContain("Revised outlook"), {+ timeout: 10_000,+ });+ expect(screen.container.textContent).not.toContain("Original outlook");+});++it("clears an Office metadata error when the same URL becomes previewable", async () => {+ const src = "data:application/octet-stream,invalid-office-file";+ let resolveResponse!: (response: Response) => void;+ const response = new Promise<Response>((resolve) => {+ resolveResponse = resolve;+ });+ using _fetch = stubGlobal(+ "fetch",+ vi.fn(() => response),+ );+ await using screen = await render(+ <OfficeFilePreview src={src} name="report.docx" kind="docx" sizeBytes={51 * 1024 * 1024} />,+ );+ await vi.waitFor(() => expect(screen.container.textContent).toContain("under 50 MB"));+ await screen.rerender(+ <OfficeFilePreview src={src} name="report.docx" kind="docx" sizeBytes={100} />,+ );+ await vi.waitFor(() =>+ expect(screen.container.querySelector('[aria-label="Loading file"]')).not.toBeNull(),+ );+ expect(screen.container.textContent).not.toContain("under 50 MB");+ resolveResponse(new Response("invalid-office-file"));+ await vi.waitFor(() => expect(screen.container.textContent).toContain("not a readable ZIP"), {+ timeout: 10_000,+ });+});++describe("attachment HTML preview recovery", () => {+ const originalUrl = "data:text/html,original";+ const renewedUrl = "data:text/html,renewed";++ function setup() {+ refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl);+ }++ const openRemote = () =>+ render(+ <AttachmentFilePreview+ name="document.html"+ mimeType="text/html"+ sizeBytes={100}+ asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}+ />,+ );++ const toggleMode = async (screen: Screen, label: string) => {+ const button = screen.container.querySelector<HTMLButtonElement>(+ `button[aria-label="${label}"]`,+ );+ expect(button, label).not.toBeNull();+ await act(async () => button!.click());+ };+ const alert = (screen: Screen) => screen.container.querySelector('[role="alert"]');++ it("keeps a renewed URL for subsequent rendered and source views", async () => {+ setup();+ let now = 0;+ using _now = vi.spyOn(Date, "now").mockImplementation(() => now);+ using _fetch = stubGlobal(+ "fetch",+ vi.fn(async () => new Response("<p>Captured HTML</p>")),+ );+ await using screen = await openRemote();+ expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(originalUrl);+ now = 61 * 60_000;+ await toggleMode(screen, "Show HTML source");+ await act(async () => {+ await import("./ReadOnlySourcePreview");+ });+ expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));+ await vi.waitFor(() =>+ expect(screen.container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"),+ );++ await toggleMode(screen, "Show rendered page");+ expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl);+ await toggleMode(screen, "Show HTML source");+ expect(refresh).toHaveBeenCalledTimes(2);+ expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);+ });++ it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {+ setup();+ let now = 0;+ using _now = vi.spyOn(Date, "now").mockImplementation(() => now);+ using _fetch = stubGlobal(+ "fetch",+ vi.fn(async () => new Response("<p>Captured HTML</p>")),+ );+ await using screen = await openRemote();+ now = 61 * 60_000;+ refresh.mockResolvedValue(null);+ await toggleMode(screen, "Show HTML source");+ expect(fetch).not.toHaveBeenCalled();+ expect(alert(screen)?.textContent).toContain("Reconnect to the environment and try again.");++ await toggleMode(screen, "Show rendered page");+ await toggleMode(screen, "Show HTML source");+ expect(refresh).toHaveBeenCalledTimes(3);+ expect(fetch).not.toHaveBeenCalled();+ });++ it("can return to rendered HTML after local source decoding fails", async () => {+ setup();+ let now = 0;+ using _now = vi.spyOn(Date, "now").mockImplementation(() => now);+ using _fetch = stubGlobal(+ "fetch",+ vi.fn(async () => new Response("<p>Captured HTML</p>")),+ );+ const file = new Blob([new Uint8Array([0x3c, 0x70, 0x3e, 0xe9])], { type: "text/html" });+ await using screen = await render(+ <AttachmentFilePreview+ name="document.html"+ mimeType="text/html"+ sizeBytes={file.size}+ file={file}+ />,+ );+ await toggleMode(screen, "Show HTML source");+ await vi.waitFor(() => expect(alert(screen)?.textContent).toContain("not UTF-8"));++ await toggleMode(screen, "Show rendered page");+ expect(alert(screen)).toBeNull();+ expect(screen.container.querySelector("iframe")?.title).toBe("document.html");+ });+});++it("loads a font attachment through the lazy preview", async () => {+ const { default: fontUrl } =+ await import("../../../node_modules/@betteroffice/fonts/assets/Carlito-Regular.ttf?url");+ const file = await (await fetch(fontUrl)).blob();+ await using screen = await render(+ <AttachmentFilePreview+ name="Carlito.ttf"+ mimeType="font/ttf"+ sizeBytes={file.size}+ file={file}+ />,+ );+ await vi.waitFor(() => {+ const frame = screen.container.querySelector("iframe");+ expect(frame?.title).toBe("Carlito.ttf");+ expect(frame?.srcdoc).toContain("@font-face");+ expect(frame?.srcdoc).toContain("The quick brown fox");+ });+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();+});++it("toggles a Mermaid attachment between diagram and source through the lazy preview", async () => {+ const text = "flowchart LR\nA --> B";+ const file = new Blob([text], { type: "text/vnd.mermaid" });+ await using screen = await render(+ <AttachmentFilePreview+ name="diagram.mmd"+ mimeType={file.type}+ sizeBytes={file.size}+ file={file}+ />,+ );+ await vi.waitFor(() =>+ expect(screen.container.querySelector("[data-markdown-mermaid] svg path")).not.toBeNull(),+ );+ await screen.getByRole("button", { name: "Expand diagram" }).click();+ await vi.waitFor(() => {+ const image = document.querySelector<HTMLImageElement>('[role="dialog"] img');+ expect(image?.alt).toBe("Mermaid diagram");+ expect(image?.naturalWidth).toBeGreaterThan(0);+ });+ await page.getByRole("button", { name: "Close image preview" }).click();+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());+ await screen.getByRole("button", { name: "Show Mermaid source" }).click();+ await vi.waitFor(() => expect(screen.container.querySelector("pre")?.textContent).toBe(text));+ await screen.getByRole("button", { name: "Show rendered diagram" }).click();+ await vi.waitFor(() =>+ expect(screen.container.querySelector("[data-markdown-mermaid] svg path")).not.toBeNull(),+ );+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();+});diff --git a/apps/web/src/components/files/AttachmentFilePreview.tsx b/apps/web/src/components/files/AttachmentFilePreview.tsxindex 9f97ed90e22..25f3456f7ef 100644--- a/apps/web/src/components/files/AttachmentFilePreview.tsx+++ b/apps/web/src/components/files/AttachmentFilePreview.tsx@@ -5,7 +5,11 @@ import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";import { settlePromise } from "@t3tools/client-runtime/state/runtime";import * as AsyncResult from "effect/reactivity/AsyncResult";import * as Cause from "effect/Cause";-import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";+import {+ filePreviewKind,+ officePreviewKind,+ FILE_TEXT_PREVIEW_MAX_BYTES,+} from "@t3tools/shared/filePreview";import { ChevronRightIcon, DownloadIcon, Trash2Icon, WrapTextIcon, XIcon } from "lucide-react";import { Check, Code2, Copy, Eye, Table2 } from "lucide";import { lazy, Suspense, useEffect, useRef, useState } from "react";@@ -30,6 +34,18 @@ import {FileSurfaceNotice,} from "./fileSurfaceChrome";+const OfficeFilePreview = lazy(() =>+ import("./OfficeFilePreview").then((module) => ({ default: module.OfficeFilePreview })),+);++const FontFilePreview = lazy(() =>+ import("./FontFilePreview").then((module) => ({ default: module.FontFilePreview })),+);++const MermaidFilePreview = lazy(() =>+ import("./MermaidFilePreview").then((module) => ({ default: module.MermaidFilePreview })),+);+const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));const STALE_URL_MS = 5 * 60_000;@@ -42,7 +58,11 @@ export function ReadOnlySourcePreview(props: { name: string; text: string }) {);}-function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {+function renderedToggleLabel(+ mode: "markdown" | "mermaid" | "html" | "table",+ rendered: boolean,+): string {+ if (mode === "mermaid") return rendered ? "Show Mermaid source" : "Show rendered diagram";if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";if (mode === "table") return rendered ? "Show source" : "Show table";return rendered ? "Show HTML source" : "Show rendered page";@@ -55,7 +75,10 @@ export function AttachmentFilePreview(props: {file?: Blob | null;asset?:| { environmentId: EnvironmentId; attachmentId: string }- | { environmentId: EnvironmentId; resource: Extract<AssetResource, { _tag: "media-file" }> };+ | {+ environmentId: EnvironmentId;+ resource: Extract<AssetResource, { _tag: "media-file" | "draft-workspace-file" }>;+ };htmlRender?: boolean;threadRef?: ScopedThreadRef;origin?: string;@@ -63,9 +86,18 @@ export function AttachmentFilePreview(props: {onClose?: () => void;}) {const kind = filePreviewKind(props);+ const officeKind = officePreviewKind(props);const delimiter = filePreviewDelimiter(props);const renderedMode =- kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;+ kind === "mermaid"+ ? "mermaid"+ : kind === "markdown"+ ? "markdown"+ : kind === "html"+ ? "html"+ : delimiter+ ? "table"+ : null;const attachmentId =props.asset && "attachmentId" in props.asset ? props.asset.attachmentId : undefined;const { copyToClipboard, isCopied } = useCopyToClipboard({ target: props.name });@@ -82,7 +114,11 @@ export function AttachmentFilePreview(props: {disposition: "inline" as const,}: null;- const downloadResource = resource ? { ...resource, disposition: "attachment" as const } : null;+ const downloadResource = resource+ ? resource._tag === "draft-workspace-file"+ ? resource+ : { ...resource, disposition: "attachment" as const }+ : null;const refresh = useAssetUrlRefresh(props.file ? null : (props.asset?.environmentId ?? null),props.file ? null : resource,@@ -127,7 +163,8 @@ export function AttachmentFilePreview(props: {// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.}, [props.file, refresh, revision]);const url = props.file ? localUrl : remoteUrl;- const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);+ const needsText =+ kind === "text" || kind === "markdown" || kind === "mermaid" || (kind === "html" && !rendered);useEffect(() => {if (!needsText || !url) return;const controller = new AbortController();@@ -170,7 +207,7 @@ export function AttachmentFilePreview(props: {needsText &&content !== null &&!(delimiter && rendered) &&- !(kind === "markdown" && rendered);+ !((kind === "markdown" || kind === "mermaid") && rendered);const save = () => {setSaving(true);@@ -217,6 +254,10 @@ export function AttachmentFilePreview(props: {) : needsText && content ? (delimiter && rendered ? (<DelimitedTablePreview name={props.name} text={content.text} delimiter={delimiter} />+ ) : kind === "mermaid" && rendered ? (+ <Suspense fallback={<FileSurfaceLoading />}>+ <MermaidFilePreview text={content.text} />+ </Suspense>) : kind === "markdown" && rendered ? (<ScrollArea className="min-h-0 flex-1"><ChatMarkdown text={content.text} cwd={undefined} className="mx-auto max-w-4xl px-6 py-5" />@@ -224,6 +265,19 @@ export function AttachmentFilePreview(props: {) : (<ReadOnlySourcePreview name={props.name} text={content.text} />)+ ) : kind === "font" ? (+ <Suspense fallback={<FileSurfaceLoading />}>+ <FontFilePreview src={url} name={props.name} />+ </Suspense>+ ) : officeKind ? (+ <Suspense fallback={<FileSurfaceLoading />}>+ <OfficeFilePreview+ src={url}+ name={props.name}+ kind={officeKind}+ sizeBytes={props.sizeBytes}+ />+ </Suspense>) : kind === "pdf" || kind === "html" ? (<BrowserDocumentFramesrc={url}diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.tsindex ec543e006a8..728ae04e0b1 100644--- a/apps/web/src/components/files/FilePreviewPanel.test.ts+++ b/apps/web/src/components/files/FilePreviewPanel.test.ts@@ -6,6 +6,7 @@ import { describe, expect, it } from "vite-plus/test";import { remapFileCommentAnnotations } from "./fileCommentAnnotations";import {filePreviewReadErrorMessage,+ isMarkdownPreviewFile,resolveFilePreviewPath,setMarkdownTaskChecked,shouldShowFileExplorer,@@ -63,6 +64,16 @@ describe("file comment annotations", () => {});});+describe("isMarkdownPreviewFile", () => {+ it("recognizes markdown and MDX files case-insensitively", () => {+ expect(isMarkdownPreviewFile("README.md")).toBe(true);+ expect(isMarkdownPreviewFile("docs/guide.MDX")).toBe(true);+ expect(isMarkdownPreviewFile("docs/guide.MARKDOWN")).toBe(true);+ expect(isMarkdownPreviewFile("docs/guide.mdown")).toBe(true);+ expect(isMarkdownPreviewFile("docs/guide.mkd")).toBe(true);+ });+});+describe("setMarkdownTaskChecked", () => {const markdown = "- [ ] First\n- [x] Second\n";diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsxindex eeec7c0de59..5f43a214f4e 100644--- a/apps/web/src/components/files/FilePreviewPanel.tsx+++ b/apps/web/src/components/files/FilePreviewPanel.tsx@@ -11,7 +11,9 @@ import { AuthFilesystemWriteScope } from "@t3tools/contracts";import {isWorkspaceAudioPreviewPath,isWorkspaceImagePreviewPath,+ isWorkspaceFontPreviewPath,isWorkspaceVideoPreviewPath,+ officePreviewKind,} from "@t3tools/shared/filePreview";import { useAtomValue } from "@effect/atom-react";import {@@ -41,7 +43,7 @@ import { mediaFileReference } from "@t3tools/client-runtime/media-reference";import { FolderTree, Globe2, WrapTextIcon } from "lucide-react";import { Code2, Eye, Table2 } from "lucide";import * as Schema from "effect/Schema";-import { useEffect, useRef, useState } from "react";+import { lazy, Suspense, useEffect, useRef, useState } from "react";import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";@@ -141,6 +143,10 @@ interface FilePreviewPanelProps {workspaceMutationId: string | null;}+const MermaidFilePreview = lazy(() =>+ import("./MermaidFilePreview").then((module) => ({ default: module.MermaidFilePreview })),+);+const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";const RENDER_BROWSER_FILE_STORAGE_KEY = "t3code.renderBrowserFile";@@ -954,7 +960,11 @@ function RenderedMarkdownSurface({);}-function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {+function renderedToggleLabel(+ mode: "markdown" | "mermaid" | "html" | "table",+ rendered: boolean,+): string {+ if (mode === "mermaid") return rendered ? "Show Mermaid source" : "Show rendered diagram";if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";if (mode === "table") return rendered ? "Show source" : "Show table";return rendered ? "Show HTML source" : "Show rendered page";@@ -992,6 +1002,7 @@ export default function FilePreviewPanel({const relativePath =attachment === undefined ? resolveFilePreviewPath(requestedPath, cwd) : requestedPath;const draft = typeof composerDraftTarget === "string";+ const [documentRefreshId, setDocumentRefreshId] = useState(0);const { resolvedTheme } = useTheme();const wordWrap = useClientSettings((settings) => settings.wordWrap);const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope);@@ -1011,6 +1022,10 @@ export default function FilePreviewPanel({const isImage = relativePath !== null && !isVideo && isWorkspaceImagePreviewPath(relativePath);const isMedia = isImage || isVideo || isAudio;const isPdf = relativePath !== null && isPdfPreviewFile(relativePath);+ const isDocument =+ relativePath !== null &&+ (officePreviewKind({ name: relativePath }) !== null ||+ isWorkspaceFontPreviewPath(relativePath));const isHtml = relativePath !== null && !isPdf && isBrowserPreviewFile(relativePath);const isHostFile =attachment !== undefined || (relativePath !== null && isHostPath(relativePath));@@ -1071,35 +1086,54 @@ export default function FilePreviewPanel({);const breadcrumbRef = useRef<HTMLDivElement>(null);const isMarkdown = previewPath ? isMarkdownPreviewFile(previewPath) : false;+ const isMermaid = previewPath !== null && /\.(mmd|mermaid)$/i.test(previewPath);+ const [renderMermaidPreferred, setRenderMermaidPreferred] = useLocalStorage(+ "t3code.renderMermaid",+ true,+ Schema.Boolean,+ );const tableDelimiter =previewPath && attachment === undefined ? filePreviewDelimiter({ name: previewPath }) : null;const revealHandled =revealLine === null ||(handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId);const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled;+ const renderMermaid = isMermaid && renderMermaidPreferred && revealHandled;const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled);const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled;- const renderedMode = isMarkdown- ? ("markdown" as const)- : tableDelimiter- ? ("table" as const)- : isHtml- ? ("html" as const)- : null;+ const renderedMode = isMermaid+ ? ("mermaid" as const)+ : isMarkdown+ ? ("markdown" as const)+ : tableDelimiter+ ? ("table" as const)+ : isHtml+ ? ("html" as const)+ : null;const canToggleRendered =previewPath !== null && attachment === undefined && renderedMode !== null;const showsRawText =previewPath !== null &&file.data !== null &&!(isMarkdown && renderMarkdown) &&+ !renderMermaid &&!(tableDelimiter && renderTable) &&- !renderBrowserFile;- const rendered = isMarkdown ? renderMarkdown : tableDelimiter ? renderTable : renderBrowserFile;- const setRenderedPreferred = isMarkdown- ? setRenderMarkdownPreferred- : tableDelimiter- ? setRenderTablePreferred- : setRenderBrowserFilePreferred;+ !renderBrowserFile &&+ !isDocument;+ const rendered = isMermaid+ ? renderMermaid+ : isMarkdown+ ? renderMarkdown+ : tableDelimiter+ ? renderTable+ : renderBrowserFile;+ const setRenderedPreferred = isMermaid+ ? setRenderMermaidPreferred+ : isMarkdown+ ? setRenderMarkdownPreferred+ : tableDelimiter+ ? setRenderTablePreferred+ : setRenderBrowserFilePreferred;const canOpenInBrowser =canOperatePreview &&previewPath !== null &&@@ -1126,9 +1160,8 @@ export default function FilePreviewPanel({enabled:attachment === undefined &&relativePath !== null &&- // Skip mutation reads for media/PDF files; re-read similarly named folders to detect conversion to- // files.- (isFolder || (!isMedia && !isPdf)) &&+ // Skip mutation reads for media and documents; folders still detect conversion to files.+ (isFolder || (!isMedia && !isPdf && !isDocument)) &&!selectedFilePending,mutationId: workspaceMutationId,refresh: file.refresh,@@ -1353,20 +1386,25 @@ export default function FilePreviewPanel({title={relativePath}workspaceMutationId={workspaceMutationId}/>- ) : relativePath && absolutePath && file.readError?.failure === "binary_file" ? (+ ) : relativePath &&+ absolutePath &&+ (isDocument || file.readError?.failure === "binary_file") ? (<AttachmentFilePreview- key={`${environmentId}:${absolutePath}`}+ key={`${environmentId}:${absolutePath}:${workspaceMutationId}:${documentRefreshId}`}name={relativePath.split(/[\\/]/).at(-1) || relativePath}mimeType="application/octet-stream"sizeBytes={0}asset={{environmentId,- resource: {- _tag: "media-file",- threadId: threadRef.threadId,- path: absolutePath,- disposition: "attachment",- },+ resource:+ draft && isDocument+ ? { _tag: "draft-workspace-file", cwd, path: absolutePath }+ : {+ _tag: "media-file",+ threadId: threadRef.threadId,+ path: absolutePath,+ ...(isDocument ? {} : { disposition: "attachment" as const }),+ },}}origin="File"/>@@ -1403,7 +1441,11 @@ export default function FilePreviewPanel({<Spinner size="lg" /></div>) : relativePath && file.data ? (- isMarkdown && renderMarkdown ? (+ renderMermaid ? (+ <Suspense fallback={<FileSurfaceLoading />}>+ <MermaidFilePreview text={file.data.contents} />+ </Suspense>+ ) : isMarkdown && renderMarkdown ? (<RenderedMarkdownSurfacekey={relativePath}environmentId={environmentId}@@ -1472,7 +1514,11 @@ export default function FilePreviewPanel({onOpenFile={onOpenFile}workspaceMutationId={workspaceMutationId}{...(previewPath && !isMedia && !isPdf- ? { onRefreshSelectedFile: file.refresh }+ ? {+ onRefreshSelectedFile: isDocument+ ? () => setDocumentRefreshId((revision) => revision + 1)+ : file.refresh,+ }: {})}/></aside>diff --git a/apps/web/src/components/files/FontFilePreview.tsx b/apps/web/src/components/files/FontFilePreview.tsxnew file mode 100644index 00000000000..28c8d5f674c--- /dev/null+++ b/apps/web/src/components/files/FontFilePreview.tsx@@ -0,0 +1,13 @@+import { lazy, Suspense } from "react";++import { FileSurfaceLoading } from "./fileSurfaceChrome";++const FontViewer = lazy(() => import("./FontViewer"));++export function FontFilePreview(props: { readonly src: string; readonly name: string }) {+ return (+ <Suspense fallback={<FileSurfaceLoading />}>+ <FontViewer key={props.src} {...props} />+ </Suspense>+ );+}diff --git a/apps/web/src/components/files/FontViewer.tsx b/apps/web/src/components/files/FontViewer.tsxnew file mode 100644index 00000000000..c88f5109244--- /dev/null+++ b/apps/web/src/components/files/FontViewer.tsx@@ -0,0 +1,86 @@+import { useEffect, useState } from "react";++import { useTheme } from "~/hooks/useTheme";++import { FileSurfaceLoading } from "./fileSurfaceChrome";++const MAX_FONT_BYTES = 10 * 1024 * 1024;++async function readFont(src: string, signal: AbortSignal) {+ const response = await fetch(src, { signal });+ if (!response.ok) throw new Error("The font could not be loaded.");+ if (Number(response.headers.get("content-length")) > MAX_FONT_BYTES)+ throw new Error("Font previews are limited to 10 MB.");+ const reader = response.body?.getReader();+ if (!reader) throw new Error("The font is unavailable.");+ const chunks: Uint8Array<ArrayBuffer>[] = [];+ let length = 0;+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ length += value.length;+ if (length > MAX_FONT_BYTES) throw new Error("Font previews are limited to 10 MB.");+ chunks.push(value);+ }+ } finally {+ await reader.cancel();+ }+ const blob = new Blob(chunks);+ await new FontFace("file-preview", await blob.arrayBuffer()).load();+ return await new Promise<string>((resolve, reject) => {+ const reader = new FileReader();+ reader.addEventListener("load", () => resolve(String(reader.result)), { once: true });+ reader.addEventListener("error", () => reject(new Error("The font could not be decoded.")), {+ once: true,+ });+ reader.readAsDataURL(blob);+ });+}++export default function FontViewer(props: { readonly src: string; readonly name: string }) {+ const { resolvedTheme } = useTheme();+ const [data, setData] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ // 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.+ useEffect(() => {+ const controller = new AbortController();+ const timeout = setTimeout(() => {+ setError("The font took too long to load.");+ controller.abort();+ }, 30_000);+ void readFont(props.src, controller.signal)+ .then((value) => {+ if (!controller.signal.aborted) setData(value);+ })+ .catch((cause: unknown) => {+ if (!controller.signal.aborted)+ setError(cause instanceof Error ? cause.message : "The font is damaged or unsupported.");+ })+ .finally(() => clearTimeout(timeout));+ return () => {+ controller.abort();+ clearTimeout(timeout);+ };+ }, [props.src]);+ if (error)+ return (+ <div+ role="alert"+ className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"+ >+ <p className="text-sm font-medium">No preview for this file</p>+ <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">+ {error} Save it to open in another app.+ </p>+ </div>+ );+ if (!data) return <FileSurfaceLoading />;+ const tokens = getComputedStyle(document.documentElement);+ const background = tokens.getPropertyValue("--background");+ const foreground = tokens.getPropertyValue("--foreground");+ 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>`;+ return (+ <iframe title={props.name} srcDoc={srcDoc} sandbox="" className="min-h-0 flex-1 border-0" />+ );+}diff --git a/apps/web/src/components/files/MermaidFilePreview.tsx b/apps/web/src/components/files/MermaidFilePreview.tsxnew file mode 100644index 00000000000..b0a32d214d2--- /dev/null+++ b/apps/web/src/components/files/MermaidFilePreview.tsx@@ -0,0 +1,13 @@+import { lazy, Suspense } from "react";++import { FileSurfaceLoading } from "./fileSurfaceChrome";++const MermaidViewer = lazy(() => import("./MermaidViewer"));++export function MermaidFilePreview(props: { readonly text: string }) {+ return (+ <Suspense fallback={<FileSurfaceLoading />}>+ <MermaidViewer key={props.text} {...props} />+ </Suspense>+ );+}diff --git a/apps/web/src/components/files/MermaidViewer.tsx b/apps/web/src/components/files/MermaidViewer.tsxnew file mode 100644index 00000000000..c831c583a51--- /dev/null+++ b/apps/web/src/components/files/MermaidViewer.tsx@@ -0,0 +1,33 @@+import { useState } from "react";++import { MermaidDiagram } from "../chat/MermaidDiagram";+import { ExpandedImageDialog } from "../chat/ExpandedImageDialog";++export default function MermaidViewer(props: { readonly text: string }) {+ const [expanded, setExpanded] = useState<string | null>(null);+ // Mermaid lays out DOM before sanitizing its SVG. Refuse resource and config+ // syntax before that pass so standalone files cannot initiate requests. Node+ // metadata is YAML, whose escaped/aliased image keys cannot be checked lexically.+ if (+ /%%\s*\{|^\s*---|<\/?[A-Za-z]|<[!?]|@\s*\{|\b(?:img|image)\s*:|url\s*\(|@import|(?:https?|data|blob|file):/im.test(+ props.text,+ )+ )+ return (+ <div role="alert" className="p-6 text-xs text-muted-foreground">+ This diagram contains resource URLs, markup, node metadata, or custom configuration. Show+ Mermaid source to inspect it safely.+ </div>+ );+ return (+ <div className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto p-6 [&_*]:animate-none!">+ <MermaidDiagram source={props.text} onExpand={setExpanded} />+ {expanded ? (+ <ExpandedImageDialog+ preview={{ images: [{ src: expanded, name: "Mermaid diagram" }], index: 0 }}+ onClose={() => setExpanded(null)}+ />+ ) : null}+ </div>+ );+}diff --git a/apps/web/src/components/files/OfficeFilePreview.tsx b/apps/web/src/components/files/OfficeFilePreview.tsxnew file mode 100644index 00000000000..2976fbd8ff7--- /dev/null+++ b/apps/web/src/components/files/OfficeFilePreview.tsx@@ -0,0 +1,19 @@+import type { OfficePreviewKind } from "@t3tools/shared/filePreview";+import { lazy, Suspense } from "react";++import { FileSurfaceLoading } from "./fileSurfaceChrome";++const OfficeViewer = lazy(() => import("./OfficeViewer"));++export function OfficeFilePreview(props: {+ readonly src: string;+ readonly name: string;+ readonly kind: OfficePreviewKind;+ readonly sizeBytes?: number;+}) {+ return (+ <Suspense fallback={<FileSurfaceLoading />}>+ <OfficeViewer key={JSON.stringify([props.src, props.kind, props.sizeBytes])} {...props} />+ </Suspense>+ );+}diff --git a/apps/web/src/components/files/OfficeViewer.tsx b/apps/web/src/components/files/OfficeViewer.tsxnew file mode 100644index 00000000000..c9e86801988--- /dev/null+++ b/apps/web/src/components/files/OfficeViewer.tsx@@ -0,0 +1,129 @@+import { useStableCallback } from "~/hooks/useStableCallback";+import type { OfficePreviewKind } from "@t3tools/shared/filePreview";+import { lazy, Suspense, useEffect, useState } from "react";+import {+ FileSurfaceLoading,+ FileSurfaceNotice,+ FILE_SURFACE_SUBHEADER_CLASS,+} from "./fileSurfaceChrome";+import { OFFICE_PREVIEW_MAX_BYTES, type OfficeWorkerResult } from "./officePreviewProtocol";+const WordDocument = lazy(() => import("./office/WordDocument"));+const Spreadsheet = lazy(() => import("./office/Spreadsheet"));+const Presentation = lazy(() => import("./office/Presentation"));+async function readOfficeFile(src: string, signal: AbortSignal) {+ const response = await fetch(src, { signal });+ if (!response.ok) throw new Error("The file could not be loaded. Close it and try again.");+ if (Number(response.headers.get("content-length")) > OFFICE_PREVIEW_MAX_BYTES)+ throw new Error("Preview limited to files under 50 MB.");+ const reader = response.body?.getReader();+ if (!reader) throw new Error("The file is unavailable.");+ const chunks: Uint8Array<ArrayBuffer>[] = [];+ let size = 0;+ try {+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ size += value.length;+ if (size > OFFICE_PREVIEW_MAX_BYTES) throw new Error("Preview limited to files under 50 MB.");+ chunks.push(value);+ }+ } finally {+ await reader.cancel();+ }+ return new Blob(chunks).arrayBuffer();+}++export default function OfficeViewer(props: {+ readonly src: string;+ readonly name: string;+ readonly kind: OfficePreviewKind;+ readonly sizeBytes?: number;+}) {+ const [error, setError] = useState<string | null>(null);+ const [prepared, setPrepared] = useState<Exclude<OfficeWorkerResult, { type: "error" }>>();+ const [details, setDetails] = useState("");+ const fail = useStableCallback((cause: unknown) =>+ setError(cause instanceof Error ? cause.message : "Could not render this Office document."),+ );+ // oxlint-disable-next-line t3code/react-effect-budget -- Own the Office fetch, preparation worker, and timeout for this source and release them on cleanup.+ useEffect(() => {+ if ((props.sizeBytes ?? 0) > OFFICE_PREVIEW_MAX_BYTES) {+ // Metadata bounds are checked before fetching or starting an engine.+ // oxlint-disable-next-line react/set-state-in-effect+ setError("Preview limited to files under 50 MB.");+ return;+ }+ const controller = new AbortController();+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {+ type: "module",+ });+ const failure = (cause: unknown) => {+ if (!controller.signal.aborted) fail(cause);+ controller.abort();+ worker.terminate();+ };+ const timer = setTimeout(+ () => failure(new Error("This document took too long to preview. Open it in another app.")),+ 30000,+ );+ worker.addEventListener("error", () => failure(new Error("Could not load the Office viewer.")));+ worker.addEventListener("messageerror", () =>+ failure(new Error("Could not read the Office viewer response.")),+ );+ worker.addEventListener("message", (event: MessageEvent<OfficeWorkerResult>) => {+ if (controller.signal.aborted) return;+ clearTimeout(timer);+ if (event.data.type === "error") failure(new Error(event.data.message));+ else {+ setPrepared(event.data);+ worker.terminate();+ }+ });+ void readOfficeFile(props.src, controller.signal)+ .then((bytes) => {+ if (!controller.signal.aborted)+ worker.postMessage({ type: "open", kind: props.kind, bytes }, [bytes]);+ })+ .catch(failure);+ return () => {+ controller.abort();+ worker.terminate();+ clearTimeout(timer);+ };+ }, [props.src, props.kind, props.sizeBytes, fail]);+ if (error)+ return (+ <div+ role="alert"+ className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"+ >+ <p className="text-sm font-medium">No preview for this file</p>+ <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">+ {error} Save it or open it in another app.+ </p>+ </div>+ );+ if (!prepared) return <FileSurfaceLoading />;+ const Viewer =+ props.kind === "docx" ? WordDocument : props.kind === "xlsx" ? Spreadsheet : Presentation;+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ {details ? (+ <div className={FILE_SURFACE_SUBHEADER_CLASS}>+ <span className="text-xs text-muted-foreground" aria-live="polite">+ {details}+ {props.kind !== "xlsx" ? " · Fit to width" : ""}+ </span>+ </div>+ ) : null}+ {prepared.truncated ? (+ <FileSurfaceNotice>+ Preview limited. Save it or open it in another app to read the full document.+ </FileSurfaceNotice>+ ) : null}+ <Suspense fallback={<FileSurfaceLoading />}>+ <Viewer bytes={prepared.bytes} onDetails={setDetails} onError={fail} />+ </Suspense>+ </div>+ );+}diff --git a/apps/web/src/components/files/filePreviewMode.ts b/apps/web/src/components/files/filePreviewMode.tsindex bc6b0cd2040..3777fad423f 100644--- a/apps/web/src/components/files/filePreviewMode.ts+++ b/apps/web/src/components/files/filePreviewMode.ts@@ -7,7 +7,8 @@ export function resolveFilePreviewPath(path: string | null, cwd: string): stringreturn path === "." || workspaceRelativeFilePath(path, cwd) === "." ? null : path;}-export const isMarkdownPreviewFile = (path: string): boolean => /\.(?:md|mdx)$/i.test(path);+export const isMarkdownPreviewFile = (path: string): boolean =>+ /\.(?:md|mdx|markdown|mdown|mkd)$/i.test(path);export function filePreviewReadErrorMessage(error: ProjectReadFileError): string {switch (error.failure) {diff --git a/apps/web/src/components/files/office/LICENSE.opencode b/apps/web/src/components/files/office/LICENSE.opencodenew file mode 100644index 00000000000..6439474beed--- /dev/null+++ b/apps/web/src/components/files/office/LICENSE.opencode@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2025 opencode++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/apps/web/src/components/files/office/OfficePages.tsx b/apps/web/src/components/files/office/OfficePages.tsxnew file mode 100644index 00000000000..d7b4b78c345--- /dev/null+++ b/apps/web/src/components/files/office/OfficePages.tsx@@ -0,0 +1,206 @@+/* oxlint-disable react/no-array-index-key -- A page keeps its ordinal throughout incremental layout. */+import { observeResize } from "~/lib/observeResize";+import {+ useEffect,+ useImperativeHandle,+ useRef,+ useState,+ type ReactNode,+ type RefObject,+} from "react";++export type PageSize = {+ readonly width: number;+ readonly height: number;+ readonly background?: string | undefined;+};+export type PaintPage = (+ index: number,+ canvas: HTMLCanvasElement,+ scale: number,+ signal: AbortSignal,+) => Promise<void>;++export function OfficePages(props: {+ pages: readonly PageSize[];+ paint: PaintPage;+ label: string;+ overlay?: (index: number) => ReactNode;+ footer?: (index: number) => ReactNode;+ scrollRef?: RefObject<((index: number, y?: number) => void) | null>;+ onPageChange?: (index: number) => void;+ onError: (error: unknown) => void;+}) {+ const scroller = useRef<HTMLDivElement>(null);+ const rows = useRef(new Map<number, HTMLDivElement>());+ const [width, setWidth] = useState(0);+ const [settledWidth, setSettledWidth] = useState(0);+ const [mounted, setMounted] = useState(6);+ // oxlint-disable-next-line t3code/react-effect-budget -- Observe the scroll container width and debounce raster resizing, releasing the observer and timer on unmount.+ useEffect(() => {+ const root = scroller.current;+ if (!root) return;+ let timer: ReturnType<typeof setTimeout>;+ const unobserve = observeResize(root, ([entry]) => {+ if (!entry) return;+ const next = entry.contentRect.width;+ setWidth(next);+ clearTimeout(timer);+ timer = setTimeout(() => setSettledWidth(next), 150);+ });+ return () => {+ clearTimeout(timer);+ unobserve();+ };+ }, []);+ // oxlint-disable-next-line t3code/react-effect-budget -- Yield between page mounting batches with a timer so large documents do not block the browser.+ useEffect(() => {+ if (mounted >= props.pages.length) return;+ const timer = setTimeout(() => setMounted((n) => Math.min(props.pages.length, n + 50)), 0);+ return () => clearTimeout(timer);+ }, [mounted, props.pages.length]);+ useImperativeHandle(+ props.scrollRef,+ () =>+ (index: number, y = 0) => {+ const row = rows.current.get(index);+ const page = props.pages[index];+ if (row && page)+ scroller.current?.scrollTo({+ top: row.offsetTop + y * Math.min(1, Math.max(0, width - 48) / page.width) - 24,+ });+ },+ [props.pages, width],+ );+ return (+ <div+ ref={scroller}+ className="relative min-h-0 flex-1 overflow-auto bg-muted/60"+ data-office-pages+ onScroll={() => {+ const root = scroller.current;+ if (!root || !props.onPageChange) return;+ if (+ root.scrollHeight > root.clientHeight &&+ root.scrollTop + root.clientHeight >= root.scrollHeight - 1+ ) {+ props.onPageChange(Math.min(mounted, props.pages.length) - 1);+ return;+ }+ for (const [index, row] of [...rows.current].sort(([a], [b]) => a - b)) {+ if (row.offsetTop + row.offsetHeight > root.scrollTop + 24) {+ props.onPageChange(index);+ break;+ }+ }+ }}+ >+ <div className="flex flex-col items-center gap-4 py-6">+ {props.pages.slice(0, mounted).map((page, index) => (+ <OfficePage+ key={index}+ page={page}+ index={index}+ root={scroller}+ register={(el) => {+ if (el) rows.current.set(index, el);+ else rows.current.delete(index);+ }}+ scale={Math.min(1, Math.max(0, width - 48) / page.width)}+ rasterScale={Math.min(1, Math.max(0, (settledWidth || width) - 48) / page.width)}+ {...props}+ />+ ))}+ </div>+ </div>+ );+}++function OfficePage(props: {+ page: PageSize;+ index: number;+ root: RefObject<HTMLDivElement | null>;+ register: (element: HTMLDivElement | null) => void;+ scale: number;+ rasterScale: number;+ paint: PaintPage;+ label: string;+ overlay?: (index: number) => ReactNode;+ footer?: (index: number) => ReactNode;+ onError: (error: unknown) => void;+}) {+ const {+ root,+ rasterScale,+ index,+ onError,+ page,+ paint,+ scale,+ register,+ label,+ overlay,+ footer,+ } = props;+ const row = useRef<HTMLDivElement>(null);+ const canvas = useRef<HTMLCanvasElement>(null);+ const [near, setNear] = useState(false);+ const [ratio, setRatio] = useState(window.devicePixelRatio || 1);+ // oxlint-disable-next-line t3code/react-effect-budget -- Observe the page's viewport proximity to limit painting and text layers to nearby pages.+ useEffect(() => {+ if (!row.current) return;+ const observer = new IntersectionObserver(+ ([entry]) => setNear(entry?.isIntersecting ?? false),+ { root: root.current, rootMargin: "100% 0px" },+ );+ observer.observe(row.current);+ return () => observer.disconnect();+ }, [root]);+ // oxlint-disable-next-line t3code/react-effect-budget -- Subscribe to display density changes so canvas rasters match the current screen.+ useEffect(() => {+ const query = matchMedia(`(resolution: ${ratio}dppx)`);+ const change = () => setRatio(window.devicePixelRatio || 1);+ query.addEventListener("change", change);+ return () => query.removeEventListener("change", change);+ }, [ratio]);+ // oxlint-disable-next-line t3code/react-effect-budget -- Paint the visible page canvas at the current raster scale and cancel obsolete paint requests.+ useEffect(() => {+ const target = canvas.current;+ if (!target || !page || !near || ratio <= 0 || rasterScale <= 0) return;+ const controller = new AbortController();+ void paint(index, target, rasterScale, controller.signal).catch((cause: unknown) => {+ if (!controller.signal.aborted) onError(cause);+ });+ return () => controller.abort();+ }, [near, index, page, paint, rasterScale, onError, ratio]);+ // oxlint-disable-next-line t3code/react-effect-budget -- Release the canvas backing store when its page moves away from the viewport.+ useEffect(() => {+ const target = canvas.current;+ if (!near && target) {+ target.width = 0;+ target.height = 0;+ }+ }, [near]);+ return (+ <div className="flex shrink-0 flex-col gap-3" style={{ width: page.width * scale }}>+ <div+ ref={(el) => {+ row.current = el;+ register(el);+ }}+ role="group"+ aria-label={`${label} ${index + 1}`}+ className="relative shrink-0 shadow-md"+ style={{+ width: page.width * scale,+ height: page.height * scale,+ background: page.background ?? "#fff",+ }}+ >+ <canvas ref={canvas} aria-hidden="true" className="absolute inset-0 block size-full" />+ {near ? overlay?.(index) : null}+ </div>+ {footer?.(index)}+ </div>+ );+}diff --git a/apps/web/src/components/files/office/Presentation.tsx b/apps/web/src/components/files/office/Presentation.tsxnew file mode 100644index 00000000000..b3a456c6464--- /dev/null+++ b/apps/web/src/components/files/office/Presentation.tsx@@ -0,0 +1,187 @@+/* oxlint-disable react/no-unstable-nested-components -- These callbacks return overlays, and are invoked as render functions. */+import { useEffect, useRef, useState } from "react";+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";+import {+ FileSurfaceAction,+ FileSurfaceLoading,+ FILE_SURFACE_SUBHEADER_CLASS,+} from "../fileSurfaceChrome";+import { OfficePages, type PaintPage } from "./OfficePages";+import { createWorkerClient } from "./worker-rpc";+import {+ maxImageSide,+ type SlideMethods,+ type SlideSummary,+ type VectorRequest,+} from "./slide-protocol";++type Opened = { slides: readonly SlideSummary[]; paint: PaintPage };+export default function Presentation(props: {+ bytes: ArrayBuffer;+ onDetails: (text: string) => void;+ onError: (cause: unknown) => void;+}) {+ const { onError, bytes: source, onDetails } = props;+ const [opened, setOpened] = useState<Opened>();+ const [page, setPage] = useState(0);+ const [failed, setFailed] = useState<Record<number, boolean>>({});+ const scroll = useRef<((index: number, y?: number) => void) | null>(null);+ // oxlint-disable-next-line t3code/react-effect-budget -- Open and paint slides through a worker whose requests and lifetime belong to this presentation.+ useEffect(() => {+ const controller = new AbortController();+ const worker = new Worker(new URL("./presentation.worker.ts", import.meta.url), {+ type: "module",+ });+ const engine = createWorkerClient<SlideMethods>(worker);+ const fail = (cause: unknown) => {+ if (!controller.signal.aborted) onError(cause);+ };+ worker.addEventListener("error", fail);+ worker.addEventListener("messageerror", fail);+ const paint = async (+ index: number,+ canvas: HTMLCanvasElement,+ scale: number,+ signal: AbortSignal,+ again = false,+ ): Promise<void> => {+ const result = await engine.call(+ "paint",+ { index, density: (window.devicePixelRatio || 1) * scale },+ { key: `slide:${index}`, signal },+ );+ if (signal.aborted || result.kind === "cancelled") {+ if (result.kind === "painted") result.bitmap.close();+ return;+ }+ setFailed((previous) => ({ ...previous, [index]: result.kind === "failed" }));+ if (result.kind === "failed") return;+ const context = canvas.getContext("bitmaprenderer");+ if (!context) {+ result.bitmap.close();+ throw new Error("This browser cannot draw slides.");+ }+ canvas.width = result.bitmap.width;+ canvas.height = result.bitmap.height;+ context.transferFromImageBitmap(result.bitmap);+ if (again || !result.vectors.length) return;+ const bitmaps = await Promise.all(result.vectors.map(rasterize));+ if (signal.aborted) {+ bitmaps.forEach((value) => value.bitmap?.close());+ return;+ }+ await engine.call("vectors", bitmaps, {+ transfer: bitmaps.flatMap((value) => (value.bitmap ? [value.bitmap] : [])),+ signal,+ });+ if (!signal.aborted) await paint(index, canvas, scale, signal, true);+ };+ const bytes = source.slice(0);+ void engine+ .call("open", { bytes }, { transfer: [bytes], signal: controller.signal })+ .then((slides) => {+ if (slides.length === 0 || slides.length > 500)+ throw new Error("Preview limited to presentations with 1 to 500 slides.");+ setOpened({ slides, paint });+ onDetails(`${slides.length} slides`);+ })+ .catch(fail);+ return () => {+ controller.abort();+ engine.close();+ };+ }, [source, onDetails, onError]);+ if (!opened) return <FileSurfaceLoading />;+ const select = (index: number) => {+ setPage(index);+ scroll.current?.(index);+ };+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className={FILE_SURFACE_SUBHEADER_CLASS}>+ <FileSurfaceAction+ label="Previous slide"+ disabled={page === 0}+ onPress={() => select(page - 1)}+ >+ <ChevronLeftIcon className="size-3.5" />+ </FileSurfaceAction>+ <span className="flex-1 text-center text-xs tabular-nums" aria-live="polite">+ Slide {page + 1} of {opened.slides.length}+ </span>+ <FileSurfaceAction+ label="Next slide"+ disabled={page + 1 === opened.slides.length}+ onPress={() => select(page + 1)}+ >+ <ChevronRightIcon className="size-3.5" />+ </FileSurfaceAction>+ </div>+ <OfficePages+ pages={opened.slides}+ paint={opened.paint}+ label="Slide"+ scrollRef={scroll}+ onPageChange={setPage}+ onError={onError}+ overlay={(index) => (+ <>+ {opened.slides[index]?.hidden ? (+ <div className="pointer-events-none absolute inset-0 bg-white/50" />+ ) : null}+ {failed[index] ? (+ <p+ role="status"+ className="absolute inset-0 flex items-center justify-center bg-background/80 p-4 text-xs text-foreground"+ >+ This slide could not be drawn.+ </p>+ ) : null}+ </>+ )}+ footer={(index) => {+ const slide = opened.slides[index];+ return slide?.notes || slide?.hidden ? (+ <div className="space-y-1 text-xs text-muted-foreground">+ {slide.hidden ? <p>Hidden slide</p> : null}+ {slide.notes ? (+ <p+ role="note"+ aria-label="Speaker notes"+ className="select-text whitespace-pre-wrap break-words"+ >+ {slide.notes}+ </p>+ ) : null}+ </div>+ ) : null;+ }}+ />+ </div>+ );+}+async function rasterize(request: VectorRequest) {+ const url = URL.createObjectURL(request.blob);+ const image = new Image();+ image.src = url;+ try {+ await image.decode();+ const shrink = Math.min(1, maxImageSide / Math.max(image.naturalWidth, image.naturalHeight));+ const size = request.size ?? {+ width: Math.max(1, Math.round(image.naturalWidth * shrink)),+ height: Math.max(1, Math.round(image.naturalHeight * shrink)),+ };+ return {+ asset: request.asset,+ bitmap: await createImageBitmap(image, {+ resizeWidth: size.width,+ resizeHeight: size.height,+ resizeQuality: "high",+ }),+ };+ } catch {+ return { asset: request.asset, bitmap: undefined };+ } finally {+ URL.revokeObjectURL(url);+ }+}diff --git a/apps/web/src/components/files/office/Spreadsheet.tsx b/apps/web/src/components/files/office/Spreadsheet.tsxnew file mode 100644index 00000000000..e9789d415d4--- /dev/null+++ b/apps/web/src/components/files/office/Spreadsheet.tsx@@ -0,0 +1,588 @@+import { observeResize } from "~/lib/observeResize";+import { useEffect, useRef, useState } from "react";+import {+ cellAtPoint,+ normalizeRange,+ selectionAt,+ selectionKeyReducer,+ extendTo,+ hyperlinkAtCell,+ safeExternalHyperlink,+ parseHyperlinkLocation,+ type Selection,+ type CellAddr,+} from "@betteroffice/xlsx/headless";+import { FileSurfaceLoading, FileSurfaceNotice } from "../fileSurfaceChrome";+import { createWorkerClient, SupersededError } from "./worker-rpc";+import type { SheetLayout, SheetMethods, SheetFrameRequest, SheetTab } from "./sheet-protocol";+import {+ coverMerges,+ contains,+ lastCell,+ settleMerges,+ skipHidden,+ columnName,+} from "./sheet-cells";+import {+ paintCells,+ paintHeaders,+ paintSelection,+ shiftGrid,+ headerHeight,+ type Painted,+} from "./sheet-paint";+import { externalUrl } from "./links";++type Client = ReturnType<typeof createWorkerClient<SheetMethods>>;+type Opened = {+ engine: Client;+ tabs: readonly SheetTab[];+ layout: SheetLayout;+ target?: CellAddr | undefined;+};+export default function Spreadsheet(props: {+ bytes: ArrayBuffer;+ onDetails: (text: string) => void;+ onError: (cause: unknown) => void;+}) {+ const { onError, bytes: source, onDetails } = props;+ const [opened, setOpened] = useState<Opened>();+ const [error, setError] = useState("");+ const picking = useRef<AbortController | null>(null);+ // oxlint-disable-next-line t3code/react-effect-budget -- Open the workbook worker and cancel workbook and sheet requests when the source changes or unmounts.+ useEffect(() => {+ const controller = new AbortController();+ const worker = new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), {+ type: "module",+ });+ const engine = createWorkerClient<SheetMethods>(worker);+ const fail = (cause: unknown) => {+ if (!controller.signal.aborted) onError(cause);+ };+ worker.addEventListener("error", fail);+ worker.addEventListener("messageerror", fail);+ const bytes = source.slice(0);+ void engine+ .call("open", { bytes }, { transfer: [bytes], signal: controller.signal })+ .then((value) => {+ if (!value) throw new Error("This workbook has no visible sheets.");+ setOpened({ ...value, engine });+ onDetails(`${value.tabs.length} sheets`);+ })+ .catch(fail);+ return () => {+ controller.abort();+ picking.current?.abort();+ engine.close();+ };+ }, [source, onDetails, onError]);+ const show = (sheet: number, target?: CellAddr) => {+ if (!opened) return;+ picking.current?.abort();+ if (sheet === opened.layout.info.activeSheet) return;+ const controller = new AbortController();+ picking.current = controller;+ void opened.engine+ .call("show", { sheet }, { signal: controller.signal })+ .then((layout) => {+ setError("");+ setOpened({ ...opened, layout, target });+ })+ .catch(() => {+ if (!controller.signal.aborted) setError("This sheet could not be opened.");+ });+ };+ if (!opened) return <FileSurfaceLoading />;+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ {error ? <FileSurfaceNotice>{error}</FileSurfaceNotice> : null}+ <SpreadsheetGrid+ key={opened.layout.info.activeSheet}+ engine={opened.engine}+ layout={opened.layout}+ initialCell={opened.target}+ onNavigate={(name, cell) => {+ const tab = opened.tabs.find((tab) => tab.name.toLowerCase() === name.toLowerCase());+ if (tab) show(tab.index, cell);+ }}+ />+ <div+ role="tablist"+ aria-label="Sheets"+ className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-t border-border px-2"+ onKeyDown={(event) => {+ const current = opened.tabs.findIndex(+ (tab) => tab.index === opened.layout.info.activeSheet,+ );+ const next =+ event.key === "ArrowRight"+ ? (current + 1) % opened.tabs.length+ : event.key === "ArrowLeft"+ ? (current + opened.tabs.length - 1) % opened.tabs.length+ : event.key === "Home"+ ? 0+ : event.key === "End"+ ? opened.tabs.length - 1+ : -1;+ if (next < 0) return;+ event.preventDefault();+ const tab = opened.tabs[next];+ if (tab) show(tab.index);+ event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')[next]?.focus();+ }}+ >+ {opened.tabs.map((tab) => (+ <button+ key={tab.index}+ type="button"+ role="tab"+ aria-selected={tab.index === opened.layout.info.activeSheet}+ tabIndex={tab.index === opened.layout.info.activeSheet ? 0 : -1}+ onClick={() => show(tab.index)}+ 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"+ >+ {tab.name}+ </button>+ ))}+ </div>+ </div>+ );+}++function SpreadsheetGrid(props: {+ engine: Client;+ layout: SheetLayout;+ initialCell: CellAddr | undefined;+ onNavigate: (sheet: string, cell: CellAddr) => void;+}) {+ const { onNavigate, layout, engine, initialCell } = props;+ const scroller = useRef<HTMLDivElement>(null);+ const canvas = useRef<HTMLCanvasElement>(null);+ const spacer = useRef<HTMLDivElement>(null);+ const [notice, setNotice] = useState("");+ const [reader, setReader] = useState<{ row: number; col: number; text: string }[]>([]);+ const [active, setActive] = useState({ row: 0, col: 0 });+ const navigate = useRef(onNavigate);+ // oxlint-disable-next-line t3code/react-effect-budget -- Keep the installed native pointer listener calling the latest navigation handler without restarting the canvas engine.+ useEffect(() => {+ navigate.current = onNavigate;+ }, [onNavigate]);+ // 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.+ useEffect(() => {+ const root = scroller.current;+ const target = canvas.current;+ const space = spacer.current;+ if (!root || !target || !space) return;+ const context = target.getContext("2d");+ if (!context) return;+ const controller = new AbortController();+ const info = layout.info;+ const sheet = info.activeSheet;+ const frozen = { rows: info.frozenRows, cols: info.frozenCols };+ const headers = { width: 44, height: headerHeight };+ let selection: Selection = selectionAt(initialCell ?? { row: 0, col: 0 });+ let painted: Painted | undefined;+ let grid: ReturnType<typeof shiftGrid> | undefined;+ let raf = 0;+ let requested = "";+ let sent = 0;+ let received = 0;+ let drag = false;+ let header: "row" | "column" | "all" | undefined;+ let pressed: { row: number; col: number } | undefined;+ let end: { x: number; y: number } | undefined;+ let left = info.initialScrollX;+ let top = info.initialScrollY;+ let reachX = 0;+ let reachY = 0;+ let readController: AbortController | undefined;+ const range = () => coverMerges(normalizeRange(selection), layout.merges);+ const at = (cell: { row: number; col: number }) => {+ const merge = layout.merges.find((item) => contains(item, cell));+ return selectionAt(merge ? { row: merge.top, col: merge.left } : cell);+ };+ const schedule = () => {+ if (raf || controller.signal.aborted) return;+ raf = requestAnimationFrame(() => {+ raf = 0;+ paint();+ });+ };+ const resizeArea = () => {+ const width = Math.min(+ (end?.x ?? Infinity) + (painted?.frame.frozen.width ?? 0),+ Math.max(info.contentWidth, layout.chartWidth, reachX, left + root.clientWidth) ++ root.clientWidth,+ );+ const height = Math.min(+ (end?.y ?? Infinity) + (painted?.frame.frozen.height ?? 0),+ Math.max(info.contentHeight, layout.chartHeight, reachY, top + root.clientHeight) ++ root.clientHeight,+ );+ space.style.width = `${headers.width + width}px`;+ space.style.height = `${headers.height + height}px`;+ };+ const paint = () => {+ const ratio = window.devicePixelRatio || 1;+ const width = root.clientWidth;+ const height = root.clientHeight;+ const size = { width: width - headers.width, height: height - headers.height };+ if (size.width <= 0 || size.height <= 0) return;+ left = root.scrollLeft;+ top = root.scrollTop;+ resizeArea();+ const input: SheetFrameRequest = {+ sheet,+ x: left,+ y: top,+ ...size,+ ratio,+ offset: { x: 0, y: 0 },+ wider: undefined,+ };+ const key = JSON.stringify(input);+ if (key !== requested) {+ requested = key;+ sent += 1;+ const order = sent;+ void engine+ .call("frame", input, { key: "frame", signal: controller.signal })+ .then((reply) => {+ if (order < received || controller.signal.aborted) {+ reply?.bitmap.close();+ return;+ }+ received = order;+ if (!reply) {+ setNotice("These cells could not be drawn. Try scrolling to another area.");+ return;+ }+ setNotice("");+ painted?.frame.bitmap.close();+ painted = { request: input, frame: reply };+ end = reply.end;+ schedule();+ })+ .catch((cause: unknown) => {+ if (!(cause instanceof SupersededError) && !controller.signal.aborted)+ setNotice("These cells could not be drawn.");+ });+ }+ if (+ target.width !== Math.round(width * ratio) ||+ target.height !== Math.round(height * ratio)+ ) {+ target.width = Math.round(width * ratio);+ target.height = Math.round(height * ratio);+ target.style.width = `${width}px`;+ target.style.height = `${height}px`;+ }+ if (!painted) {+ context.fillStyle = "#fff";+ context.fillRect(0, 0, target.width, target.height);+ return;+ }+ paintCells(context, painted, { ratio, headers, x: left, y: top, ...size });+ grid =+ painted.frame.grid &&+ shiftGrid(painted.frame.grid, frozen, painted.frame.frozen, {+ x: painted.frame.viewport.x - left,+ y: painted.frame.viewport.y - top,+ });+ if (!grid) return;+ const anchor = selection.anchor;+ paintSelection(context, {+ grid,+ ratio,+ headers,+ ...size,+ range: range(),+ active: coverMerges(+ { top: anchor.row, left: anchor.col, bottom: anchor.row, right: anchor.col },+ layout.merges,+ ),+ });+ paintHeaders(context, { grid, ratio, headers, width, height, selected: range() });+ };+ const read = () => {+ const focus = selection.focus;+ setActive(focus);+ readController?.abort();+ readController = new AbortController();+ const top = Math.max(0, focus.row - 5);+ const left = Math.max(0, focus.col - 3);+ const range = {+ top,+ left,+ bottom: Math.min(lastCell.row, top + 10),+ right: Math.min(lastCell.col, left + 6),+ };+ void engine+ .call("cells", { sheet, range }, { key: "reader", signal: readController.signal })+ .then((rows) => {+ if (!controller.signal.aborted)+ setReader(+ rows.flatMap((row, r) =>+ row.map((text, c) => ({ row: top + r, col: left + c, text })),+ ),+ );+ })+ .catch(() => undefined);+ };+ const select = (next: Selection) => {+ selection = next;+ read();+ schedule();+ };+ const reveal = () => {+ const cell = selection.focus;+ void engine+ .call("position", { sheet, cell }, { key: "position", signal: controller.signal })+ .then((position) => {+ if (!position || controller.signal.aborted) return;+ const panes = painted?.frame.frozen ?? { width: 0, height: 0 };+ const place = (start: number, next: number, current: number, visible: number) =>+ start < current ? start : next > current + visible ? next - visible : current;+ const x =+ cell.col < info.frozenCols+ ? left+ : place(+ position.start.x,+ position.next.x,+ left,+ root.clientWidth - headers.width - panes.width,+ );+ const y =+ cell.row < info.frozenRows+ ? top+ : place(+ position.start.y,+ position.next.y,+ top,+ root.clientHeight - headers.height - panes.height,+ );+ reachX = Math.max(reachX, x + root.clientWidth);+ reachY = Math.max(reachY, y + root.clientHeight);+ resizeArea();+ root.scrollTo({ left: Math.max(0, x), top: Math.max(0, y) });+ schedule();+ })+ .catch(() => undefined);+ };+ const hit = (event: PointerEvent) => {+ if (!grid) return;+ const rect = target.getBoundingClientRect();+ const x = event.clientX - rect.left - headers.width;+ const y = event.clientY - rect.top - headers.height;+ const frame = painted?.frame;+ if (+ frame &&+ ((x >= frame.frozen.width && x < frame.frozen.width + frame.viewport.x - left) ||+ (y >= frame.frozen.height && y < frame.frozen.height + frame.viewport.y - top))+ )+ return;+ const cell = cellAtPoint(+ grid,+ Math.max(0, Math.min(x, root.clientWidth - headers.width - 1)),+ Math.max(0, Math.min(y, root.clientHeight - headers.height - 1)),+ );+ return cell ? { cell, x, y } : undefined;+ };+ const pointerDown = (event: PointerEvent) => {+ if (event.button !== 0) return;+ const found = hit(event);+ if (!found) return;+ root.focus({ preventScroll: true });+ root.setPointerCapture(event.pointerId);+ drag = true;+ header = found.x < 0 ? (found.y < 0 ? "all" : "row") : found.y < 0 ? "column" : undefined;+ pressed = header ? undefined : found.cell;+ if (found.x < 0 && found.y < 0)+ select({ anchor: { row: lastCell.row, col: lastCell.col }, focus: { row: 0, col: 0 } });+ else if (found.x < 0)+ select({+ anchor: { row: found.cell.row, col: lastCell.col },+ focus: { row: found.cell.row, col: 0 },+ });+ else if (found.y < 0)+ select({+ anchor: { row: lastCell.row, col: found.cell.col },+ focus: { row: 0, col: found.cell.col },+ });+ else select(event.shiftKey ? extendTo(selection, found.cell) : at(found.cell));+ };+ const pointerMove = (event: PointerEvent) => {+ if (!drag) return;+ const found = hit(event);+ if (found && header !== "all")+ select(+ extendTo(selection, {+ row: header === "column" ? 0 : found.cell.row,+ col: header === "row" ? 0 : found.cell.col,+ }),+ );+ };+ const pointerUp = (event: PointerEvent) => {+ drag = false;+ const found = hit(event);+ if (!found || !pressed || found.cell.row !== pressed.row || found.cell.col !== pressed.col)+ return;+ const cell = at(found.cell).anchor;+ const list = painted?.frame;+ if (!list) return;+ const link = hyperlinkAtCell(+ { width: 0, height: 0, commands: [], hyperlinks: [...list.hyperlinks] },+ cell.row,+ cell.col,+ );+ if (!link) return;+ const url = safeExternalHyperlink(link);+ const safe = url && externalUrl(url);+ if (safe) {+ window.open(safe, "_blank", "noopener,noreferrer");+ return;+ }+ const internal =+ link.location && parseHyperlinkLocation(link.location, info.sheetNames[sheet] ?? "");+ if (!internal) return;+ if (internal.sheetName.toLowerCase() !== (info.sheetNames[sheet] ?? "").toLowerCase())+ navigate.current(internal.sheetName, { row: internal.row, col: internal.col });+ else {+ select(at({ row: internal.row, col: internal.col }));+ reveal();+ }+ };+ const copy = () => {+ const used = layout.used;+ const selected = range();+ const clipped = {+ ...selected,+ bottom: Math.min(selected.bottom, Math.max(selected.top, used?.bottom ?? 0)),+ right: Math.min(selected.right, Math.max(selected.left, used?.right ?? 0)),+ };+ if ((clipped.bottom - clipped.top + 1) * (clipped.right - clipped.left + 1) > 200_000) {+ setNotice("Select fewer than 200,000 cells to copy.");+ return;+ }+ void engine+ .call("copy", { sheet, range: clipped }, { signal: controller.signal })+ .then((text) => {+ if (text === undefined) throw new Error("No cells");+ return navigator.clipboard.writeText(text);+ })+ .catch(() => {+ if (!controller.signal.aborted) setNotice("The selected cells could not be copied.");+ });+ };+ const key = (event: KeyboardEvent) => {+ const command = event.ctrlKey || event.metaKey;+ if (command && event.key.toLowerCase() === "c") {+ event.preventDefault();+ copy();+ return;+ }+ if (event.key === "Tab" || event.altKey || event.isComposing) return;+ const action = selectionKeyReducer(selection, event, {+ rows: Math.max((layout.used?.bottom ?? 0) + 1, selection.focus.row + 1),+ cols: Math.max((layout.used?.right ?? 0) + 1, selection.focus.col + 1),+ rowsPerPage: Math.max(1, Math.floor((root.clientHeight - headerHeight) / 20)),+ });+ if (action.type !== "move") return;+ event.preventDefault();+ select(+ skipHidden(+ selection.focus,+ settleMerges(selection, action.selection, layout.merges),+ layout.hidden,+ ),+ );+ reveal();+ };+ const cancel = () => {+ drag = false;+ };+ root.addEventListener("scroll", schedule);+ root.addEventListener("keydown", key);+ root.addEventListener("pointerdown", pointerDown);+ root.addEventListener("pointermove", pointerMove);+ root.addEventListener("pointerup", pointerUp);+ root.addEventListener("pointercancel", cancel);+ const unobserve = observeResize(root, schedule);+ window.addEventListener("resize", schedule);+ resizeArea();+ root.scrollTo({ left, top });+ if (initialCell) {+ selection = at(initialCell);+ reveal();+ }+ read();+ schedule();+ return () => {+ controller.abort();+ readController?.abort();+ cancelAnimationFrame(raf);+ unobserve();+ window.removeEventListener("resize", schedule);+ painted?.frame.bitmap.close();+ root.removeEventListener("scroll", schedule);+ root.removeEventListener("keydown", key);+ root.removeEventListener("pointerdown", pointerDown);+ root.removeEventListener("pointermove", pointerMove);+ root.removeEventListener("pointerup", pointerUp);+ root.removeEventListener("pointercancel", cancel);+ };+ }, [engine, layout, initialCell]);+ return (+ <div className="relative flex min-h-0 flex-1">+ <div+ ref={scroller}+ dir="ltr"+ tabIndex={0}+ role="grid"+ aria-label={layout.info.sheetNames[layout.info.activeSheet]}+ aria-readonly="true"+ aria-multiselectable="true"+ aria-rowcount={lastCell.row + 1}+ aria-colcount={lastCell.col + 1}+ aria-activedescendant={`office-cell-${active.row}-${active.col}`}+ 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"+ >+ <div+ ref={spacer}+ aria-hidden="true"+ className="pointer-events-none absolute left-0 top-0"+ />+ <div aria-hidden="true" className="sticky left-0 top-0 h-0 w-0">+ <canvas ref={canvas} className="absolute left-0 top-0 block" />+ </div>+ <div className="sr-only">+ {[...new Set(reader.map((cell) => cell.row))].map((row) => (+ <div key={row} role="row" aria-rowindex={row + 1}>+ {reader+ .filter((cell) => cell.row === row)+ .map((cell) => (+ <span+ key={cell.col}+ role="gridcell"+ id={`office-cell-${cell.row}-${cell.col}`}+ aria-colindex={cell.col + 1}+ aria-label={`${columnName(cell.col)}${cell.row + 1}`}+ >+ {cell.text}+ </span>+ ))}+ </div>+ ))}+ </div>+ </div>+ {notice ? (+ <div+ role="status"+ className="absolute inset-x-3 bottom-3 rounded-md bg-background p-2 text-xs text-foreground shadow-md"+ >+ {notice}+ </div>+ ) : null}+ </div>+ );+}diff --git a/apps/web/src/components/files/office/WordDocument.tsx b/apps/web/src/components/files/office/WordDocument.tsxnew file mode 100644index 00000000000..44d8b6f58c5--- /dev/null+++ b/apps/web/src/components/files/office/WordDocument.tsx@@ -0,0 +1,184 @@+/* oxlint-disable react/no-array-index-key -- Text spans retain their order within an immutable page. */+/* oxlint-disable react/no-unstable-nested-components -- These callbacks return overlays, and are invoked as render functions. */+import { Tooltip, TooltipTrigger, TooltipPopup } from "~/components/ui/tooltip";+import { Fragment, useEffect, useRef, useState } from "react";+import { FileSurfaceLoading } from "../fileSurfaceChrome";+import { OfficePages, type PaintPage } from "./OfficePages";+import { createWorkerClient } from "./worker-rpc";+import {+ layerFont,+ lineHeight,+ type WordMethods,+ type WordPageSize,+ type WordSpan,+ type WordLink,+} from "./word-protocol";++type Opened = {+ pages: readonly WordPageSize[];+ paint: PaintPage;+ engine: ReturnType<typeof createWorkerClient<WordMethods>>;+};++export default function WordDocument(props: {+ bytes: ArrayBuffer;+ onDetails: (text: string) => void;+ onError: (cause: unknown) => void;+}) {+ const { onError, bytes, onDetails } = props;+ const [opened, setOpened] = useState<Opened>();+ const scroll = useRef<((index: number, y?: number) => void) | null>(null);+ // 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.+ useEffect(() => {+ const controller = new AbortController();+ const worker = new Worker(new URL("./document.worker.ts", import.meta.url), { type: "module" });+ const engine = createWorkerClient<WordMethods>(worker);+ const fail = (error: unknown) => {+ if (!controller.signal.aborted) onError(error);+ };+ worker.addEventListener("error", fail);+ worker.addEventListener("messageerror", fail);+ const buffer = bytes.slice(0);+ const paint: PaintPage = async (index, canvas, scale, signal) => {+ const bitmap = await engine.call(+ "paint",+ { index, scale, ratio: window.devicePixelRatio || 1 },+ { key: `paint:${index}`, signal },+ );+ void engine+ .call("build", { index: index + 1 }, { key: "build", signal })+ .catch(() => undefined);+ if (!bitmap) return;+ const context = canvas.getContext("bitmaprenderer");+ if (!context || signal.aborted) {+ bitmap.close();+ return;+ }+ canvas.width = bitmap.width;+ canvas.height = bitmap.height;+ context.transferFromImageBitmap(bitmap);+ };+ void engine+ .call("open", { bytes: buffer }, { transfer: [buffer], signal: controller.signal })+ .then(async (first) => {+ if (controller.signal.aborted) return;+ setOpened({ pages: first.pages, paint, engine });+ onDetails(`${first.pages.length}${first.loading ? "+" : ""} pages`);+ if (!first.loading) return;+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ while (!controller.signal.aborted) {+ const step = await engine.call("layout", undefined, { signal: controller.signal });+ if (!step.done) continue;+ if (step.pages.length > 1000) throw new Error("Preview limited to 1,000 pages.");+ setOpened({ pages: step.pages, paint, engine });+ onDetails(`${step.pages.length} pages`);+ break;+ }+ })+ .catch(fail);+ return () => {+ controller.abort();+ engine.close();+ };+ }, [bytes, onDetails, onError]);+ if (!opened) return <FileSurfaceLoading />;+ const follow = (link: WordLink) => {+ if (link.kind === "external") {+ window.open(link.url, "_blank", "noopener,noreferrer");+ return;+ }+ void opened.engine+ .call("bookmark", { name: link.bookmark })+ .then((target) => {+ if (target) scroll.current?.(target.index, target.y);+ })+ .catch(onError);+ };+ return (+ <OfficePages+ pages={opened.pages}+ paint={opened.paint}+ label="Page"+ scrollRef={scroll}+ onError={onError}+ overlay={(index) => (+ <WordTextLayer+ engine={opened.engine}+ index={index}+ page={opened.pages[index]}+ follow={follow}+ />+ )}+ />+ );+}++function WordTextLayer(props: {+ engine: Opened["engine"];+ index: number;+ page: WordPageSize | undefined;+ follow: (link: WordLink) => void;+}) {+ const { engine, index, page, follow } = props;+ const [spans, setSpans] = useState<readonly WordSpan[]>([]);+ // 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.+ useEffect(() => {+ if (!page) return;+ const controller = new AbortController();+ void engine+ .call("text", { index: index }, { signal: controller.signal })+ .then(setSpans)+ .catch(() => undefined);+ return () => controller.abort();+ }, [engine, index, page]);+ return (+ <div+ className="absolute inset-0 select-text overflow-hidden whitespace-pre text-transparent selection:bg-primary/30 selection:text-transparent"+ style={{ containerType: "inline-size", fontFamily: layerFont, fontSize: 0, lineHeight }}+ >+ {spans.map((span, index) => {+ const text = (+ <span+ dir={span.dir}+ role={span.link ? "link" : undefined}+ tabIndex={span.link ? 0 : undefined}+ aria-label={span.title}+ className="absolute origin-top-left"+ style={{+ left: `${span.left * 100}%`,+ top: `${span.top * 100}%`,+ fontSize: `${span.size * 100}cqw`,+ transform: span.transform,+ cursor: span.link ? "pointer" : "text",+ }}+ onClick={(event) => {+ if (span.link && event.button === 0 && (getSelection()?.isCollapsed ?? true))+ follow(span.link);+ }}+ onKeyDown={(event) => {+ if (span.link && event.key === "Enter") {+ event.preventDefault();+ follow(span.link);+ }+ }}+ >+ {span.text}+ </span>+ );+ return (+ <Fragment key={index}>+ {span.title ? (+ <Tooltip>+ <TooltipTrigger render={text} />+ <TooltipPopup>{span.title}</TooltipPopup>+ </Tooltip>+ ) : (+ text+ )}+ {span.after === "br" ? <br /> : span.after === "tab" ? "\t" : null}+ </Fragment>+ );+ })}+ </div>+ );+}diff --git a/apps/web/src/components/files/office/document.worker.ts b/apps/web/src/components/files/office/document.worker.tsnew file mode 100644index 00000000000..e25dd3ce43d--- /dev/null+++ b/apps/web/src/components/files/office/document.worker.ts@@ -0,0 +1,377 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import * as Schema from "effect/Schema";+import {+ buildResidentRegionLayoutRequest,+ getLayoutKernelInputs,+ workerLayoutComputation,+} from "@betteroffice/docx/editor";+import { createRustMeasureSource } from "@betteroffice/docx/layout";+import {+ applyFrameDelta,+ decodeFrameDelta,+ encodeDisplayListFrameExtras,+ GlyphCache,+ rasterizeDisplayPageToBackBuffer,+ type DisplayPage,+ type RetainedFrame,+} from "@betteroffice/docx/layout/render";+import {+ createYrsPositionProjection,+ createYrsSession,+ type YrsPositionProjection,+} from "@betteroffice/docx/yrs";+import { wordFonts } from "./fonts";+import { createBitmapImageResolver } from "./word-images";+import { layerFont, type WordMethods, type WordPageSize, type WordSpan } from "./word-protocol";+import { pageText, positionTarget, type TextMeasure } from "./word-text";+import { serveWorker, Transfer } from "./worker-rpc";++// One worker holds one open Word document: its engine session, fonts, layout, built pages and painting. The window+// terminates the worker when the document closes, which is the only way the engine's memory is given back.++const FontRequirements = Schema.fromJsonString(+ Schema.Array(+ Schema.Struct({+ key: Schema.String,+ family: Schema.String,+ bold: Schema.Boolean,+ italic: Schema.Boolean,+ scripts: Schema.optional(+ Schema.Array(Schema.Literals(["cjk-sc", "cjk-tc", "cjk-jp", "cjk-kr", "arabic", "hebrew"])),+ ),+ }),+ ),+);++const decodeFontRequirements = Schema.decodeUnknownSync(FontRequirements);++/** A prefix layout's reply marks itself provisional when the document goes on past it. */+const decodeLayoutReply = Schema.decodeUnknownSync(+ Schema.fromJsonString(Schema.Struct({ provisional: Schema.optional(Schema.Boolean) })),+);++/** Pages laid out and built before the first paint; later pages are built as they near the viewport. */+const firstPages = 3;++/** How long one layout step may hold back a paint that waits behind it, in milliseconds. */+const stepBudget = 24;++/**+ * How many pages either side of the page painted last stay built. A built page holds about 5 MB in the engine and+ * builds again in about 100 ms. This keeps every page near the viewport, which paints a viewport ahead in both+ * directions, and lets a reader scroll back a few screens without waiting, while a long read holds at most 21 pages.+ */+const keptAround = 10;++type Opened = Awaited<ReturnType<typeof open>>;++/** A value built on first use. */+type Lazy<T> = { value: T | undefined };++/** The document this worker opened, once it has. */+const opened: Lazy<Opened> = { value: undefined };++serveWorker<WordMethods>({+ open: async (input) => {+ if (opened.value) throw new Error("The worker already holds a document");++ const loaded = await open(new Uint8Array(input.bytes));++ opened.value = loaded;++ return { pages: loaded.pages().map(pageSize), loading: loaded.loading() };+ },+ layout: () => required().step(),+ paint: async (input, signal) => {+ const bitmap = await required().paint(input.index, input.scale, input.ratio, signal);++ return bitmap ? new Transfer(bitmap, [bitmap]) : undefined;+ },+ build: (input) => {+ required().built(input.index);++ return undefined;+ },+ text: (input) => required().text(input.index),+ bookmark: (input) => required().target(input.name),+});++function required() {+ if (!opened.value) throw new Error("The worker holds no document");++ return opened.value;+}++/** Opens the document and lays out its first pages; the rest lay out a `step` at a time. */+async function open(bytes: Uint8Array) {+ const session = await createYrsSession();+ const document = session.openDocx(bytes, true, { mediaTokens: true }).document;+ const settings = document.package.settings;++ const measure = createRustMeasureSource({+ engine: {+ registerFont: (font) => session.registerFont(font),+ registerSubstituteFont: (id, family) => session.registerSubstituteFont(id, family),+ clearFonts: () => session.clearFonts(),+ },+ bundled: wordFonts(),+ });++ measure.setCompat(settings?.compatibilityFlags);++ const request = buildResidentRegionLayoutRequest(document, 0, {+ themeColors: Object.fromEntries(+ Object.entries(document.package.theme?.colorScheme ?? {}).filter(+ (entry): entry is [string, string] => entry[1] !== undefined,+ ),+ ),+ defaultTabStopTwips: settings?.defaultTabStop ?? null,+ numericIds: {},+ mediaTokens: true,+ });++ const requirements = decodeFontRequirements(+ session.layoutFontRequirementsJson(JSON.stringify(request)),+ ).map(({ scripts, ...requirement }) => ({+ ...requirement,+ ...(scripts ? { scripts: [...scripts] } : {}),+ }));++ await measure.prepareFontRequirements(requirements);++ const measurement = measure.measurementConfigForRequirements(requirements);++ if (!measurement) throw new Error("The document's fonts could not be prepared");++ const input = JSON.stringify({ ...request, measurement });++ // Word shows resolved comments without the active highlight.+ const resolvedCommentIds = (document.package.document.comments ?? [])+ .filter(+ (comment) =>+ (comment.done || comment.status === "resolved") && comment.parentId === undefined,+ )+ .map((comment) => comment.id);++ // The session keeps the layout it last ran and builds display frames from it: only the display extras go in, and a+ // binary frame comes back with the window's pages built and every other page a placeholder carrying its geometry.+ const display = (previous: RetainedFrame | null, reply: string) => {+ const layout = workerLayoutComputation(reply).layout;++ session.setDisplayWindow(0, firstPages);++ const extras = encodeDisplayListFrameExtras({+ measured: [],+ options: {},+ layout,+ fontChains: measurement.fontChains,+ ...(getLayoutKernelInputs(layout)?.headersFooters+ ? { headersFooters: getLayoutKernelInputs(layout)!.headersFooters! }+ : {}),+ resolvedCommentIds,+ });++ return applyFrameDelta(+ previous,+ decodeFrameDelta(session.buildDisplayListFrame(extras, previous?.frameEpoch ?? 0)),+ );+ };++ // Only as much of the body as fills the first pages; a long document goes on past it.+ const prefix = session.layoutDocumentWithRegionsPrefixRetainedJson(input, firstPages);+ const retained = { frame: display(null, prefix) };++ if (retained.frame.displayList.pages.length === 0)+ throw new Error("The document produced no pages");++ // The region layout that finishes the document: begun on the first step, `cost` the running average milliseconds a+ // body block takes.+ const layout = { loading: decodeLayoutReply(prefix).provisional ?? false, begun: false, cost: 3 };++ // Builds a page's content when it is needed and not built, the first time or again after `release`.+ const built = (index: number) => {+ const page = retained.frame.displayList.pages[index];++ if (!page?.unbuilt) return page;++ retained.frame = applyFrameDelta(+ retained.frame,+ decodeFrameDelta(session.buildDisplayPagesFrame([index], retained.frame.frameEpoch)),+ );++ return retained.frame.displayList.pages[index];+ };++ // Gives back the built pages far from the page about to paint, so a long read keeps only the pages around the+ // viewport. A released page keeps its geometry and document positions, which bookmarks search, and builds again+ // when it is needed.+ const release = (painted: number) => {+ // The engine releases pages of the whole document's layout only, and few pages show before it.+ if (layout.loading) return;++ const far = retained.frame.displayList.pages.flatMap((page, index) =>+ !page.unbuilt && Math.abs(painted - index) > keptAround ? [index] : [],+ );++ if (far.length === 0) return;++ const frame = session.releaseDisplayPagesFrame(far, retained.frame.frameEpoch);++ // A superseded release changes nothing; the next one tries again.+ if (frame) retained.frame = applyFrameDelta(retained.frame, decodeFrameDelta(frame));+ };++ // The whole document's layout replaces the prefix's frame.+ const complete = (reply: string) => {+ const before = retained.frame.displayList.pages;++ retained.frame = display(retained.frame, reply);+ layout.loading = false;++ const pages = retained.frame.displayList.pages;++ return {+ done: true as const,+ pages: pages.map(pageSize),+ kept: pages.map((page, index) => {+ const was = before[index];++ return was === page || (!!was?.unbuilt && !!page.unbuilt);+ }),+ };+ };++ const glyphCache = new GlyphCache({+ provider: (font, glyph) => session.outlineGlyphJson(font, glyph),+ });+ const images = createBitmapImageResolver((token) => session.mediaSource(token));+ const surface = new OffscreenCanvas(1, 1);+ const textMeasure = layerMeasure();+ const texts = new WeakMap<DisplayPage, readonly WordSpan[]>();+ // Built on the first followed bookmark: most documents are read without one.+ const projection: Lazy<YrsPositionProjection | null> = { value: undefined };++ return {+ pages: () => retained.frame.displayList.pages,+ loading: () => layout.loading,+ built,+ /**+ * Lays out about `stepBudget` milliseconds more of the body. Blocks vary widely, and sizing a step by the last one+ * alone overshoots after a run of cheap blocks.+ */+ step: () => {+ if (!layout.loading) {+ const pages = retained.frame.displayList.pages;++ return { done: true as const, pages: pages.map(pageSize), kept: pages.map(() => true) };+ }++ if (!layout.begun) {+ layout.begun = true;++ const begun = session.beginRegionLayout(input);++ return begun.layoutJson === undefined+ ? { done: false as const }+ : complete(begun.layoutJson);+ }++ const blocks = Math.min(8192, Math.max(1, Math.round(stepBudget / layout.cost)));+ const started = performance.now();+ const progress = session.resumeRegionLayout(blocks);++ layout.cost = layout.cost * 0.7 + ((performance.now() - started) / blocks) * 0.3;++ return progress.layoutJson === undefined+ ? { done: false as const }+ : complete(progress.layoutJson);+ },+ paint: async (index: number, scale: number, ratio: number, signal: AbortSignal) => {+ // A page that scrolled away before its paint began, or while it rasterized, needs no bitmap.+ if (signal.aborted) return undefined;++ // Released first, so the page builds in the memory they free.+ release(index);++ const page = built(index);++ if (!page) return undefined;++ // The window drew image elements, which shrink smoothly at the default quality; a bitmap needs medium quality to+ // look the same. Sizing the surface first keeps the setting: the painter resizes it, which resets the context,+ // only when its size differs.+ const context = surface.getContext("2d");+ const width = Math.ceil(page.width * ratio * scale);+ const height = Math.ceil(page.height * ratio * scale);++ if (surface.width !== width) surface.width = width;++ if (surface.height !== height) surface.height = height;++ if (context) context.imageSmoothingQuality = "medium";++ await rasterizeDisplayPageToBackBuffer(+ surface,+ page,+ { glyphCache, resolveImage: images.resolve },+ ratio,+ scale,+ );+ images.trim();++ if (signal.aborted) return undefined;++ return surface.transferToImageBitmap();+ },+ text: (index: number) => {+ const page = built(index);++ if (!page || !textMeasure) return [];++ const cached = texts.get(page);++ if (cached) return cached;++ const spans = pageText(page, textMeasure);++ texts.set(page, spans);++ return spans;+ },+ target: (name: string) => {+ projection.value ??= createYrsPositionProjection(session, "body");++ const position = projection.value?.bookmarkPosition(name) ?? undefined;++ if (position !== undefined)+ return positionTarget(retained.frame.displayList.pages, position, built);++ // Word's reserved bookmark for the start of the document.+ return name === "_top" ? { index: 0, y: 0 } : undefined;+ },+ };+}++function pageSize(page: DisplayPage): WordPageSize {+ return { width: page.width, height: page.height, background: page.background };+}++/** Measures the text layer's font with a detached canvas; undefined where the worker offers no 2D context. */+function layerMeasure(): TextMeasure | undefined {+ const context = new OffscreenCanvas(1, 1).getContext("2d");++ if (!context) return undefined;++ // Measured large and scaled down, so rounding stays well below a pixel at any zoom.+ const size = 100;++ context.font = `${size}px ${layerFont}`;++ const metrics = context.measureText("Hg");++ return {+ width: (text) => context.measureText(text).width / size,+ ascent: metrics.fontBoundingBoxAscent / size,+ descent: metrics.fontBoundingBoxDescent / size,+ };+}diff --git a/apps/web/src/components/files/office/fonts-cjk.ts b/apps/web/src/components/files/office/fonts-cjk.tsnew file mode 100644index 00000000000..d593dbb2bf3--- /dev/null+++ b/apps/web/src/components/files/office/fonts-cjk.ts@@ -0,0 +1,4 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+// `@betteroffice/fonts` imports its optional Chinese, Japanese and Korean add-on on demand. The add-on is about 33 MB,+// so the app aliases it to this module, which offers no faces: those scripts fall back to the bundled Latin faces.+export const CJK_FONT_ASSET_URLS = undefined;diff --git a/apps/web/src/components/files/office/fonts.ts b/apps/web/src/components/files/office/fonts.tsnew file mode 100644index 00000000000..6328d294d87--- /dev/null+++ b/apps/web/src/components/files/office/fonts.ts@@ -0,0 +1,85 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import type { BundledFontProvider } from "@betteroffice/docx/layout";+import {+ loadBundledFontBytes,+ resolveBundledFamilyFace,+ resolveLastResortFace,+ resolveMetricCompatFace,+ resolveScriptFallbackFace,+ type BundledFontFace,+ type BundledFontScript,+} from "@betteroffice/fonts";++// Every face loads from the app's own files, so no font request leaves the machine. The Chinese, Japanese and Korean+// faces are an add-on the app does not ship (see `fonts-cjk.ts`), yet the font package still maps East Asian families+// such as Microsoft YaHei or Yu Gothic Medium to them, so every lookup passes through `shippedFace`.+function shipped(script: BundledFontScript) {+ return !script.startsWith("cjk-");+}++/** The faces Word substitutes for a document's fonts: metric-compatible ones first, then Word's own fallbacks. */+export function wordFonts(): BundledFontProvider {+ const loader = (face: BundledFontFace | undefined) => (face ? () => loadFace(face) : undefined);++ return {+ resolve: (family, bold, italic) =>+ loader(shippedFace(resolveMetricCompatFace(family, bold, italic))),+ resolveFamily: (family, bold, italic) =>+ loader(shippedFace(resolveBundledFamilyFace(family, bold, italic))),+ resolveScriptFallback: (script, bold, italic) => loader(scriptFace(script, bold, italic)),+ resolveLastResort: (family, bold, italic) => () =>+ loadFace(lastResortFace(family, bold, italic, "word")),+ };+}++/** The face PowerPoint draws a family with: its metric-compatible or bundled face, else PowerPoint's substitute. */+export function presentationFace(family: string, bold: boolean, italic: boolean): BundledFontFace {+ return (+ shippedFace(resolveMetricCompatFace(family, bold, italic)) ??+ shippedFace(resolveBundledFamilyFace(family, bold, italic)) ??+ lastResortFace(family, bold, italic, "powerpoint")+ );+}++function shippedFace(face: BundledFontFace | undefined) {+ return face && (!face.script || shipped(face.script)) ? face : undefined;+}++/**+ * The substitute an application picks for a family it lacks. Only a weight variant of an East Asian family, such as+ * Yu Mincho Light, resolves to a face the app does not ship; its name without the weight still tells serif from sans.+ */+function lastResortFace(+ family: string,+ bold: boolean,+ italic: boolean,+ office: "word" | "powerpoint",+) {+ const face = resolveLastResortFace(family, bold, italic, office);++ if (shippedFace(face)) return face;++ const base = family+ .trim()+ .split(/[\s-]+/)+ .slice(0, -1)+ .join(" ");++ return (+ shippedFace(resolveLastResortFace(base, bold, italic, office)) ??+ resolveLastResortFace("", bold, italic, office)+ );+}++/** The face that covers a script the Latin faces lack, or undefined when the app ships none. */+export function scriptFace(script: BundledFontScript, bold: boolean, italic: boolean) {+ return shipped(script) ? resolveScriptFallbackFace(script, bold, italic) : undefined;+}++/**+ * A bundled face's bytes. The font package caches them per worker, so a face loads once per open file; the browser's+ * caches, which every worker shares, serve the files to the next.+ */+export function loadFace(face: BundledFontFace) {+ return loadBundledFontBytes(face);+}diff --git a/apps/web/src/components/files/office/image-bitmap.ts b/apps/web/src/components/files/office/image-bitmap.tsnew file mode 100644index 00000000000..7e0473d601e--- /dev/null+++ b/apps/web/src/components/files/office/image-bitmap.ts@@ -0,0 +1,20 @@+import {+ IMAGE_DIMENSIONS_HEADER_BYTES,+ readImageDimensions,+} from "@t3tools/shared/imageDimensions";++export async function officeImageBitmap(blob: Blob) {+ const bytes = new Uint8Array(await blob.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer());+ let size = readImageDimensions(bytes);+ if (!size && bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4d) {+ const view = new DataView(bytes.buffer);+ size =+ view.getUint32(14, true) === 12+ ? { width: view.getUint16(18, true), height: view.getUint16(20, true) }+ : { width: view.getInt32(18, true), height: Math.abs(view.getInt32(22, true)) };+ }+ // Unknown dimensions cannot be decoded safely: compressed bytes do not bound pixel memory.+ if (!size || size.width <= 0 || size.height <= 0 || size.width > 16_777_216 / size.height)+ throw new Error("This embedded image exceeds the preview pixel limit.");+ return createImageBitmap(blob);+}diff --git a/apps/web/src/components/files/office/links.ts b/apps/web/src/components/files/office/links.tsnew file mode 100644index 00000000000..80a8817aec1--- /dev/null+++ b/apps/web/src/components/files/office/links.ts@@ -0,0 +1,24 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import type { WordLink } from "./word-protocol";++/** The schemes the host opens outside the app; it refuses any other, such as `javascript:`, `file:` or `tel:`. */+const schemes = new Set(["http:", "https:", "mailto:"]);++/** A document's link address, normalized, when the host may open it; undefined otherwise, so the link stays text. */+export function externalUrl(href: string) {+ const url = URL.parse(href);++ return url && schemes.has(url.protocol) ? url.href : undefined;+}++/** Where a Word link leads, if it is one a reader may follow: a bookmark in the document, or an `externalUrl`. */+export function wordLink(href: string | undefined): WordLink | undefined {+ if (!href) return undefined;++ if (href.startsWith("#"))+ return href.length > 1 ? { kind: "internal", bookmark: href.slice(1) } : undefined;++ const url = externalUrl(href);++ return url ? { kind: "external", url } : undefined;+}diff --git a/apps/web/src/components/files/office/presentation.worker.ts b/apps/web/src/components/files/office/presentation.worker.tsnew file mode 100644index 00000000000..b02c48144bc--- /dev/null+++ b/apps/web/src/components/files/office/presentation.worker.ts@@ -0,0 +1,428 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import {+ initWasm,+ needsElementDecode,+ openPresentation,+ paintSlide,+ presentationImageBlob,+ type PresentationHandle,+ type SlideDisplayList,+ type SlidePrimitive,+} from "@betteroffice/pptx";+import { slideFonts } from "./slide-fonts";+import {+ maxImageSide,+ type SlideMethods,+ type SlidePainted,+ type SlideSummary,+ type VectorBitmap,+ type VectorRequest,+} from "./slide-protocol";+import { deckText } from "./slide-text";+import { officeImageBitmap } from "./image-bitmap";+import { serveWorker, Transfer } from "./worker-rpc";++// One worker holds one open PowerPoint deck: its engine, fonts, laid-out slides, decoded pictures and painting. The+// window terminates the worker when the deck closes, which is the only way the engine's memory is given back.++/** English Metric Units per CSS pixel. */+const emuPerPixel = 9525;++/** The most device pixels one slide's bitmap holds, about a 4K screen: a zoomed slide stays sharp up to it. */+const maxBitmapPixels = 3840 * 2160;++/** The longest side a canvas takes in every browser. */+const maxBitmapSide = 16384;++/**+ * Shadow pixels a slide may blur, per pixel of its bitmap: sixteen slide-sized shadows before they are dropped. Past+ * it a slide gives up its shadows within about half a second, rather than painting for many seconds.+ */+const shadowPixelsPerPixel = 16;++/**+ * How many bytes of decoded pictures stay for repaints; the least recently drawn go first past it. A deck of camera+ * photos holds about 17 MB per picture, even scaled down to `maxImageSide`.+ */+const pictureBudget = 128 * 1024 * 1024;++type Size = { readonly width: number; readonly height: number };++/**+ * A picture as the painter draws it: a bitmap, an SVG that the window rasterizes (a worker has no SVG decoder) with+ * the bitmap it last returned, or nothing when the browser cannot decode it.+ */+type Picture =+ | { readonly kind: "bitmap"; readonly bitmap: ImageBitmap; readonly size: Size }+ | {+ readonly kind: "vector";+ readonly blob: Blob;+ bitmap: ImageBitmap | undefined;+ failed: boolean;+ }+ | { readonly kind: "missing" };++type Deck = ReturnType<typeof createDeck>;++/** The deck this worker opened, once it has. */+type WorkerState = { deck: Deck | undefined };++const state: WorkerState = { deck: undefined };++serveWorker<SlideMethods>({+ open: async (input) => {+ if (state.deck) throw new Error("The worker already holds a deck");++ await initWasm();++ const bytes = new Uint8Array(input.bytes);+ const handle = openPresentation(bytes);+ const snapshot = handle.snapshot();+ const text = deckText(bytes, snapshot);+ const fonts = slideFonts(handle, workerFonts());++ await fonts.load(text);++ state.deck = createDeck(handle, fonts.layout);++ const size = {+ width: snapshot.widthEmu / emuPerPixel,+ height: snapshot.heightEmu / emuPerPixel,+ };++ return snapshot.slides.map((slide, index): SlideSummary => ({+ ...size,+ hidden: text.hidden[index] ?? false,+ notes: slide.notes?.trim() || undefined,+ }));+ },+ paint: async (input, signal) => {+ const deck = required();+ const painted = await deck.paint(input.index, input.density, signal).finally(deck.trim);++ return painted.kind === "painted" ? new Transfer(painted, [painted.bitmap]) : painted;+ },+ vectors: (input) => required().vectors(input),+});++function required() {+ if (!state.deck) throw new Error("The worker holds no deck");++ return state.deck;+}++/** The worker's own font set, which its canvases draw text with. */+function workerFonts() {+ if (!("fonts" in self)) throw new Error("This browser has no fonts in workers");++ // SAFETY: a worker's global scope is a FontFaceSource, whose `fonts` is a FontFaceSet (CSS Font Loading, exposed to+ // workers). The window's types declare it on documents only, and workers expose no FontFaceSet to check against.+ return self.fonts as FontFaceSet;+}++function createDeck(+ handle: PresentationHandle,+ layout: (index: number) => Promise<SlideDisplayList>,+) {+ // A frame depends on the slide alone, so a new scale or pixel ratio paints the frame laid out before.+ const frames = new Map<number, Promise<SlideDisplayList | undefined>>();+ const pictures = new Map<string, Promise<Picture>>();+ // The decoded bitmaps, least recently drawn first, which `trim` keeps within `pictureBudget`.+ const drawn = new Map<string, ImageBitmap>();+ const surface = new OffscreenCanvas(1, 1);++ const frame = (index: number) => {+ const cached = frames.get(index);++ if (cached) return cached;++ const laid = layout(index).catch(() => undefined);++ frames.set(index, laid);++ return laid;+ };++ const decode = async (asset: string): Promise<Picture> => {+ const blob = presentationImageBlob(handle.mediaBytes(asset));++ // SVG decodes through an image element, which a worker lacks.+ if (needsElementDecode(blob)) return { kind: "vector", blob, bitmap: undefined, failed: false };++ const source = await officeImageBitmap(blob).catch(() => undefined);++ if (!source) return { kind: "missing" };+ const size = { width: source.width, height: source.height };+ return { kind: "bitmap", bitmap: await bounded(source), size };+ };++ const picture = (asset: string) => {+ const cached = pictures.get(asset);++ if (cached) return cached;++ const decoded = decode(asset).catch((): Picture => ({ kind: "missing" }));++ pictures.set(asset, decoded);++ return decoded;+ };++ const tileScale = async (primitive: SlidePrimitive): Promise<SlidePrimitive> => {+ if (primitive.kind === "table" || primitive.kind === "chart") {+ const primitives: SlidePrimitive[] = [];+ for (const child of primitive.primitives) primitives.push(await tileScale(child));+ return { ...primitive, primitives };+ }+ if (primitive.kind !== "image" || !primitive.tile || !primitive.assetId) return primitive;+ const found = await picture(primitive.assetId);+ if (found.kind !== "bitmap") return primitive;+ return {+ ...primitive,+ tile: {+ ...primitive.tile,+ scaleX: primitive.tile.scaleX * (found.size.width / found.bitmap.width),+ scaleY: primitive.tile.scaleY * (found.size.height / found.bitmap.height),+ },+ };+ };++ return {+ paint: async (index: number, density: number, signal: AbortSignal): Promise<SlidePainted> => {+ const laid = await frame(index);++ if (!laid) return { kind: "failed" };++ if (signal.aborted) return { kind: "cancelled" };++ const scale = Math.min(+ density,+ Math.sqrt(maxBitmapPixels / (laid.width * laid.height)),+ maxBitmapSide / Math.max(laid.width, laid.height),+ );++ // One canvas paints every slide: a paint that was withdrawn leaves its pixels for the next to clear, rather than a+ // slide-sized canvas each until the worker collects garbage. A reset context starts as a new canvas's does.+ const canvas = surface;+ const width = Math.max(1, Math.round(laid.width * scale));+ const height = Math.max(1, Math.round(laid.height * scale));++ if (canvas.width !== width) canvas.width = width;++ if (canvas.height !== height) canvas.height = height;++ const context = canvas.getContext("2d");++ if (!context) return { kind: "failed" };++ context.reset();++ const needs = vectorSizes(laid.primitives, scale);+ const wanted = new Map<string, VectorRequest>();++ const resolveImage = async (asset: string) => {+ // A paint that was withdrawn finishes without pictures, and its reply is dropped.+ if (signal.aborted) return null;++ const found = await picture(asset);++ if (found.kind === "bitmap") {+ drawn.delete(asset);+ drawn.set(asset, found.bitmap);++ return found.bitmap;+ }++ if (found.kind === "missing" || found.failed) return null;++ const need = needs.get(asset);++ if (!covers(found.bitmap, need)) wanted.set(asset, { asset, blob: found.blob, size: need });++ if (found.bitmap) {+ drawn.delete(asset);+ drawn.set(asset, found.bitmap);+ }++ return found.bitmap ?? null;+ };++ const options = {+ resolveImage,+ maxShadowPixels: canvas.width * canvas.height * shadowPixelsPerPixel,+ };++ const attempt = (list: SlideDisplayList) =>+ // SAFETY: the painter draws through the members a worker's 2D context shares with the window's, and makes its+ // scratch canvases with OffscreenCanvas wherever it exists, as it does in a worker. Only the window's context+ // type is declared, and it has two focus and attribute members the worker's lacks, hence the double cast.+ paintSlide(context as unknown as CanvasRenderingContext2D, list, scale, 1, options).then(+ () => true,+ () => false,+ );++ const primitives: SlidePrimitive[] = [];+ for (const primitive of laid.primitives) primitives.push(await tileScale(primitive));+ const scaled = { ...laid, primitives };+ const shadowed = await attempt(scaled);++ // Past its shadow budget a slide throws, and paints again without shadows rather than not at all. It first lets+ // through a cancellation that arrived meanwhile, such as a scroll that moved the slide away.+ if (!shadowed) await new Promise((resolve) => setTimeout(resolve));++ if (signal.aborted) return { kind: "cancelled" };++ const done = shadowed || (await attempt(withoutShadows(scaled)));++ if (!done) return { kind: "failed" };++ if (signal.aborted) return { kind: "cancelled" };++ return {+ kind: "painted",+ bitmap: canvas.transferToImageBitmap(),+ vectors: [...wanted.values()],+ };+ },++ /** Closes the least recently drawn pictures past the budget; they decode again when drawn. Call it between paints. */+ trim: () => {+ [...drawn].reduce(+ (total, [asset, bitmap]) => {+ if (total <= pictureBudget) return total;++ const freed = pixelBytes(bitmap);++ bitmap.close();+ drawn.delete(asset);+ pictures.delete(asset);++ return total - freed;+ },+ [...drawn.values()].reduce((total, bitmap) => total + pixelBytes(bitmap), 0),+ );+ },++ /**+ * Keeps the window's rasterized SVG pictures in place of coarser ones. A finer one that a paint at a larger scale+ * returned stays, and so does any one when the window could not rasterize the picture again.+ */+ vectors: (bitmaps: readonly VectorBitmap[]) =>+ Promise.all(+ bitmaps.map(async (entry) => {+ const found = await picture(entry.asset);++ if (found.kind !== "vector") return entry.bitmap?.close();++ if (found.bitmap && (!entry.bitmap || covers(found.bitmap, entry.bitmap)))+ return entry.bitmap?.close();++ found.bitmap?.close();+ drawn.delete(entry.asset);+ found.bitmap = entry.bitmap;+ found.failed = !entry.bitmap;+ if (entry.bitmap) drawn.set(entry.asset, entry.bitmap);+ }),+ ).then(() => undefined),+ };+}++/**+ * The bitmap size each SVG picture on a slide needs at `scale`: its drawn size in device pixels, before cropping and+ * up to `maxImageSide`. A tiled picture repeats at its own size, so it needs exactly that (undefined).+ */+function vectorSizes(primitives: readonly SlidePrimitive[], scale: number) {+ const sizes = new Map<string, Size | undefined>();++ const visit = (primitive: SlidePrimitive): void => {+ if (primitive.kind === "table" || primitive.kind === "chart")+ return primitive.primitives.forEach(visit);++ if (primitive.kind !== "image" || !primitive.assetId) return;++ const asset = primitive.assetId;+ const previous = sizes.get(asset);++ if (primitive.tile || (sizes.has(asset) && !previous)) return void sizes.set(asset, undefined);++ const visibleX = 1 - fraction(primitive.crop?.left) - fraction(primitive.crop?.right);+ const visibleY = 1 - fraction(primitive.crop?.top) - fraction(primitive.crop?.bottom);++ if (visibleX <= 0 || visibleY <= 0) return;++ const width = Math.max(previous?.width ?? 0, (primitive.w * scale) / visibleX);+ const height = Math.max(previous?.height ?? 0, (primitive.h * scale) / visibleY);+ const shrink = Math.min(1, maxImageSide / Math.max(width, height));++ sizes.set(asset, {+ width: Math.max(1, Math.ceil(width * shrink)),+ height: Math.max(1, Math.ceil(height * shrink)),+ });+ };++ primitives.forEach(visit);++ return sizes;+}++function pixelBytes(bitmap: ImageBitmap) {+ return bitmap.width * bitmap.height * 4;+}++/** Whether a rasterized SVG picture is as fine as `need`; undefined needs the picture's own size, rasterized once. */+function covers(bitmap: ImageBitmap | undefined, need: Size | undefined) {+ if (!bitmap) return false;++ if (!need) return true;++ return bitmap.width >= need.width && bitmap.height >= need.height;+}++/** A crop fraction as the painter reads it. */+function fraction(value: number | undefined) {+ return value === undefined || !Number.isFinite(value) ? 0 : Math.min(Math.max(value, 0), 1);+}++function withoutShadows(frame: SlideDisplayList): SlideDisplayList {+ const strip = (primitive: SlidePrimitive): SlidePrimitive => {+ if (primitive.kind === "shape" || primitive.kind === "image") {+ const { shadow: _shadow, ...rest } = primitive;+ return rest;+ }++ if (primitive.kind === "textBox") {+ const { textShadow: _shadow, ...rest } = primitive;+ return rest;+ }++ if (primitive.kind === "table" || primitive.kind === "chart")+ return { ...primitive, primitives: primitive.primitives.map(strip) };++ return primitive;+ };++ return { ...frame, primitives: frame.primitives.map(strip) };+}++/**+ * The picture scaled down to `maxImageSide` when it is larger. Decks of camera photos would otherwise hold about 100 MB+ * per decoded picture for as long as the deck is open.+ */+async function bounded(source: ImageBitmap) {+ const shrink = maxImageSide / Math.max(source.width, source.height);++ if (shrink >= 1) return source;++ return createImageBitmap(source, {+ resizeWidth: Math.max(1, Math.round(source.width * shrink)),+ resizeHeight: Math.max(1, Math.round(source.height * shrink)),+ resizeQuality: "high",+ }).then(+ (resized) => {+ source.close();++ return resized;+ },+ () => source,+ );+}diff --git a/apps/web/src/components/files/office/sheet-cells.ts b/apps/web/src/components/files/office/sheet-cells.tsnew file mode 100644index 00000000000..f61cad9981d--- /dev/null+++ b/apps/web/src/components/files/office/sheet-cells.ts@@ -0,0 +1,217 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import type { XlsxAnchor } from "@betteroffice/xlsx";+import {+ selectionAt,+ type CellAddr,+ type CellRange,+ type Selection,+} from "@betteroffice/xlsx/headless";++/** The sheet's last cell, zero-based: row 1,048,576 in column XFD. */+export const lastCell = { row: 1048575, col: 16383 };++/** A column's letters, such as "A", "Z" or "AA". */+export function columnName(index: number): string {+ return (+ (index < 26 ? "" : columnName(Math.floor(index / 26) - 1)) ++ String.fromCharCode(65 + (index % 26))+ );+}++/** The cells an export anchor names: one range for a cell or range anchor, none for any other kind. */+export function anchorRange(anchor: XlsxAnchor): CellRange[] {+ if (anchor.kind !== "cell" && anchor.kind !== "range") return [];++ const range = parseRange(anchor.a1);++ return range ? [range] : [];+}++/** An A1 cell or range, such as "B2" or "A1:F20"; undefined for anything else. */+export function parseRange(a1: string): CellRange | undefined {+ // A lone cell is its own last corner; an empty one, as in "A1:", names no range.+ const corners = a1.split(":");+ const first = parseCell(corners[0] ?? "");+ const last = corners.length === 1 ? first : parseCell(corners[1] ?? "");++ if (!first || !last) return undefined;++ return {+ top: Math.min(first.row, last.row),+ left: Math.min(first.col, last.col),+ bottom: Math.max(first.row, last.row),+ right: Math.max(first.col, last.col),+ };+}++/** Grows a range until it covers every merged cell it touches, as Excel selects. */+export function coverMerges(range: CellRange, merges: readonly CellRange[]): CellRange {+ const grown = merges.reduce(+ (current, merge) =>+ overlaps(current, merge)+ ? {+ top: Math.min(current.top, merge.top),+ left: Math.min(current.left, merge.left),+ bottom: Math.max(current.bottom, merge.bottom),+ right: Math.max(current.right, merge.right),+ }+ : current,+ range,+ );++ // A merge the range grew into can touch another one it did not reach before.+ if (same(grown, range)) return grown;++ return coverMerges(grown, merges);+}++/**+ * Moves a collapsed selection the way Excel moves its active cell around merged cells: landing in one selects its+ * first cell, and a step that stays inside the merged cell it started from steps past it.+ */+export function settleMerges(+ previous: Selection,+ next: Selection,+ merges: readonly CellRange[],+): Selection {+ if (!collapsed(next)) return next;++ const merge = merges.find((candidate) => contains(candidate, next.focus));++ if (!merge) return next;++ if (!collapsed(previous) || !contains(merge, previous.focus))+ return selectionAt({ row: merge.top, col: merge.left });++ const cell = {+ row: Math.min(+ lastCell.row,+ Math.max(0, past(previous.focus.row, next.focus.row, merge.top, merge.bottom)),+ ),+ col: Math.min(+ lastCell.col,+ Math.max(0, past(previous.focus.col, next.focus.col, merge.left, merge.right)),+ ),+ };++ const landed = merges.find((candidate) => contains(candidate, cell));++ return selectionAt(landed ? { row: landed.top, col: landed.left } : cell);+}++/** A run of hidden rows or columns, zero-based and inclusive. */+export type Span = { readonly start: number; readonly end: number };++/** Hidden row spans such as "5:7", or column spans such as "C:D", as the export lists them. */+export function parseSpans(spans: readonly string[], axis: "rows" | "columns"): Span[] {+ return spans.flatMap((span) => {+ const [first = "", last = first] = span.split(":");+ const start = axis === "rows" ? Number(first) - 1 : columnIndex(first);+ const end = axis === "rows" ? Number(last) - 1 : columnIndex(last);++ return Number.isInteger(start) && Number.isInteger(end) && start >= 0 && end >= start+ ? [{ start, end }]+ : [];+ });+}++/**+ * Moves a selection's focus off hidden rows and columns, on in the direction it moved, as Excel's arrow keys skip+ * them. A move that would leave the sheet stays where it started.+ */+export function skipHidden(+ from: CellAddr,+ selection: Selection,+ hidden: { readonly rows: readonly Span[]; readonly columns: readonly Span[] },+): Selection {+ const focus = {+ row: clear(from.row, selection.focus.row, hidden.rows, lastCell.row),+ col: clear(from.col, selection.focus.col, hidden.columns, lastCell.col),+ };++ if (focus.row === selection.focus.row && focus.col === selection.focus.col) return selection;++ if (collapsed(selection)) return selectionAt(focus);++ return { anchor: selection.anchor, focus };+}++/** Runs an engine call that throws on input it cannot take, such as a viewport with too many cells to draw. */+export function attempt<T>(run: () => T): T | undefined {+ try {+ return run();+ } catch {+ return undefined;+ }+}++/** Whether a range holds a cell. */+export function contains(range: CellRange, cell: CellAddr) {+ return (+ cell.row >= range.top &&+ cell.row <= range.bottom &&+ cell.col >= range.left &&+ cell.col <= range.right+ );+}++function parseCell(a1: string): CellAddr | undefined {+ const match = /^\$?([A-Z]{1,3})\$?([1-9]\d*)$/i.exec(a1);++ if (!match) return undefined;++ const col = columnIndex(match[1]!);+ const row = Number(match[2]) - 1;++ if (col > lastCell.col || row > lastCell.row) return undefined;++ return { row, col };+}++/** A column's zero-based index from its letters; NaN for anything but one to three letters. */+function columnIndex(letters: string) {+ if (!/^[A-Z]{1,3}$/i.test(letters)) return Number.NaN;++ return (+ [...letters.toUpperCase()].reduce(+ (total, letter) => total * 26 + letter.charCodeAt(0) - 64,+ 0,+ ) - 1+ );+}++/** Where a move along one axis lands once past any hidden span it ended in. */+function clear(from: number, to: number, spans: readonly Span[], last: number): number {+ const span = spans.find((candidate) => to >= candidate.start && to <= candidate.end);++ if (!span || to === from) return to;++ const next = to > from ? span.end + 1 : span.start - 1;++ if (next < 0 || next > last) return from;++ return clear(from, next, spans, last);+}++/** One step along an axis: past the merge's far edge in the direction of the move, or where it was. */+function past(from: number, to: number, low: number, high: number) {+ if (to > from) return high + 1;++ if (to < from) return low - 1;++ return from;+}++function collapsed(selection: Selection) {+ return (+ selection.anchor.row === selection.focus.row && selection.anchor.col === selection.focus.col+ );+}++function overlaps(a: CellRange, b: CellRange) {+ return a.left <= b.right && a.right >= b.left && a.top <= b.bottom && a.bottom >= b.top;+}++function same(a: CellRange, b: CellRange) {+ return a.top === b.top && a.left === b.left && a.bottom === b.bottom && a.right === b.right;+}diff --git a/apps/web/src/components/files/office/sheet-frame.ts b/apps/web/src/components/files/office/sheet-frame.tsnew file mode 100644index 00000000000..67789b6b79f--- /dev/null+++ b/apps/web/src/components/files/office/sheet-frame.ts@@ -0,0 +1,215 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import {+ paintDisplayList,+ type DisplayList,+ type GridMeta,+ type WorkbookHandle,+} from "@betteroffice/xlsx";+import { attempt } from "./sheet-cells";+import { frozenSize } from "./sheet-paint";+import type { SheetViewport } from "./sheet-protocol";++// The workbook worker's frames: the display lists of one viewport, split into tiles where the engine refuses it whole,+// and their painting.++/** The most tiles a side of a frame splits into before the frame gives up. */+const maxSplit = 8;++/**+ * How far a tile reaches past each of its seams, in CSS pixels. The engine draws pane dividers and cut tracks at a+ * frame's edges, which the next tile has to cover, and the seam falls inside a device pixel.+ */+const seamOverlap = 8;++/** Part of a frame: its display list, where its origin sits in the frame, and where it starts to show. */+type Tile = {+ readonly list: DisplayList;+ readonly x: number;+ readonly y: number;+ readonly clipX: number;+ readonly clipY: number;+};++/**+ * A frame of cells: the tiles that draw it, one display list for its grid and links, without draw commands, and the+ * viewport it shows.+ */+export type Frame = {+ readonly list: DisplayList;+ readonly tiles: readonly Tile[];+ readonly viewport: SheetViewport;+};++/**+ * The cells of one viewport, as the engine draws them; `undefined` when even its smallest tiles fail. A `wider`+ * viewport around it is drawn instead when the engine takes it whole.+ */+export function drawFrame(+ workbook: WorkbookHandle,+ viewport: SheetViewport,+ frozen: { readonly rows: number; readonly cols: number },+ wider?: SheetViewport,+): Frame | undefined {+ const around = wider && attempt(() => workbook.displayList(wider));++ if (wider && around)+ return {+ list: around,+ tiles: [{ list: around, x: 0, y: 0, clipX: 0, clipY: 0 }],+ viewport: wider,+ };++ const whole = attempt(() => workbook.displayList(viewport));++ if (whole)+ return { list: whole, tiles: [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }], viewport };++ // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. One row and one column of+ // the frame give its tracks, and so where its frozen panes end.+ const columns = attempt(() => workbook.displayList({ ...viewport, height: 1 }).grid);+ const rows = attempt(() => workbook.displayList({ ...viewport, width: 1 }).grid);++ if (!columns || !rows) return undefined;++ const grid = {+ startRow: rows.startRow,+ ...(rows.rowIndices ? { rowIndices: rows.rowIndices } : {}),+ rowOffsets: rows.rowOffsets,+ startCol: columns.startCol,+ ...(columns.colIndices ? { colIndices: columns.colIndices } : {}),+ colOffsets: columns.colOffsets,+ };++ return tiled(workbook, viewport, frozenSize(grid, frozen), grid, 2);+}++/**+ * Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a+ * tile covers the panes it repeats.+ */+export function paintFrame(+ context: OffscreenCanvasRenderingContext2D,+ frame: Frame,+ input: { readonly ratio: number; readonly origin: { readonly x: number; readonly y: number } },+) {+ const ratio = input.ratio;+ const origin = input.origin;+ // SAFETY: the painter draws through the members a worker's 2D context shares with the window's. Only the window's+ // context type is declared, and it has focus and attribute members the worker's lacks, hence the double cast.+ const painter = context as unknown as CanvasRenderingContext2D;+ const tiled = frame.tiles.length > 1;+ const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined;+ const textContext = text?.getContext("2d");++ frame.tiles.forEach((tile) => {+ const at = { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio };+ const list = tiled+ ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") }+ : tile.list;++ if (tile.clipX === 0 && tile.clipY === 0) return paintDisplayList(painter, list, ratio, at);++ context.save();+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.beginPath();+ context.rect(+ Math.round(origin.x + tile.clipX * ratio),+ Math.round(origin.y + tile.clipY * ratio),+ context.canvas.width,+ context.canvas.height,+ );+ context.clip();+ paintDisplayList(painter, list, ratio, at);+ context.restore();+ });+ // Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds.+ if (text && textContext)+ frame.tiles.forEach((tile) => {+ textContext.reset();+ paintDisplayList(+ textContext as unknown as CanvasRenderingContext2D,+ {+ ...tile.list,+ width: frame.viewport.width - tile.x,+ height: frame.viewport.height - tile.y,+ commands: tile.list.commands.filter((command) => command.op === "text"),+ },+ ratio,+ { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio },+ );+ context.save();+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.beginPath();+ context.rect(+ Math.round(origin.x + tile.clipX * ratio),+ Math.round(origin.y + tile.clipY * ratio),+ context.canvas.width,+ context.canvas.height,+ );+ context.clip();+ context.drawImage(text, 0, 0);+ context.restore();+ });+}++/**+ * A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for+ * the frozen panes too, as every viewport has them, so the cells past them start just before its seam.+ */+function tiled(+ workbook: WorkbookHandle,+ viewport: SheetViewport,+ panes: { readonly width: number; readonly height: number },+ grid: GridMeta,+ split: number,+): Frame | undefined {+ const columns = segments(viewport.width, panes.width, split);+ const rows = segments(viewport.height, panes.height, split);+ const tiles: Tile[] = [];++ const complete = rows.every((row) =>+ columns.every((column) => {+ const x = column.start === 0 ? 0 : column.start - seamOverlap - panes.width;+ const y = row.start === 0 ? 0 : row.start - seamOverlap - panes.height;+ // A tile but the last along an axis reaches past its end, which the next tile paints over.+ const right = column.end === viewport.width ? column.end : column.end + seamOverlap;+ const bottom = row.end === viewport.height ? row.end : row.end + seamOverlap;++ const list = attempt(() =>+ workbook.displayList({+ x: viewport.x + x,+ y: viewport.y + y,+ width: right - x,+ height: bottom - y,+ }),+ );++ if (list) tiles.push({ list, x, y, clipX: column.start, clipY: row.start });++ return !!list;+ }),+ );++ if (complete) {+ const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []);++ return {+ list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks },+ tiles,+ viewport,+ };+ }++ if (split >= maxSplit) return undefined;++ return tiled(workbook, viewport, panes, grid, split + 1);+}++/** Even spans of a side, the first holding the frozen panes whole; a seam inside them is dropped. */+function segments(size: number, panes: number, split: number) {+ const starts = Array.from({ length: split }, (_, part) =>+ Math.round((part * size) / split),+ ).filter((start, part) => part === 0 || (start >= panes + seamOverlap && start < size));++ return starts.map((start, part) => ({ start, end: starts[part + 1] ?? size }));+}diff --git a/apps/web/src/components/files/office/sheet-paint.ts b/apps/web/src/components/files/office/sheet-paint.tsnew file mode 100644index 00000000000..89daa57e9cb--- /dev/null+++ b/apps/web/src/components/files/office/sheet-paint.ts@@ -0,0 +1,396 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import { rangeRect, type CellRange, type GridMeta } from "@betteroffice/xlsx/headless";+import { columnName } from "./sheet-cells";+import type { SheetFrame, SheetFrameRequest } from "./sheet-protocol";++/** Excel's light headers and green selection. The sheet keeps them on its white paper in every theme. */+const colours = {+ header: "#f5f5f5",+ label: "#5c5c5c",+ line: "#d4d4d4",+ edge: "#bdbdbd",+ corner: "#c8c8c8",+ selectedHeader: "#d3ecdd",+ selectedLabel: "#185c37",+ accent: "#217346",+ selection: "rgba(33, 115, 70, 0.12)",+};++const font = "11px ui-sans-serif, system-ui, sans-serif";++/** The height of the column headers, in CSS pixels. */+export const headerHeight = 20;++/** The sizes of the header strips, in CSS pixels: the row headers' width and the column headers' height. */+export type Headers = { readonly width: number; readonly height: number };++/**+ * The frozen panes' size in a frame: the offset of the first track past them. Without panes, the first track can start+ * before the frame, part of it scrolled away.+ */+export function frozenSize(+ grid: GridMeta | undefined,+ frozen: { readonly rows: number; readonly cols: number },+) {+ if (!grid) return { width: 0, height: 0 };++ const pane = (+ offsets: readonly number[],+ start: number,+ indices: readonly number[] | undefined,+ count: number,+ ) => {+ if (count === 0) return 0;++ const first = offsets.findIndex(+ (_, position) =>+ position === offsets.length - 1 || trackIndex(start, indices, position) >= count,+ );++ return Math.max(0, offsets[first] ?? 0);+ };++ return {+ width: pane(grid.colOffsets, grid.startCol, grid.colIndices, frozen.cols),+ height: pane(grid.rowOffsets, grid.startRow, grid.rowIndices, frozen.rows),+ };+}++/** A frame from the workbook worker and the request it answers, which says where its cells sit. */+export type Painted = { readonly request: SheetFrameRequest; readonly frame: SheetFrame };++/**+ * Draws a frame's cells beside the headers at the current scroll position. A frame painted at another position, as one+ * is while the next renders, moves with the scroll: the frozen panes stay put and the cells past them shift, leaving+ * the paper where the frame has no cells yet.+ */+export function paintCells(+ context: CanvasRenderingContext2D,+ painted: Painted,+ input: {+ readonly ratio: number;+ readonly headers: Headers;+ readonly x: number;+ readonly y: number;+ readonly width: number;+ readonly height: number;+ },+) {+ const request = painted.request;+ const bitmap = painted.frame.bitmap;+ const panes = painted.frame.frozen;+ const ratio = input.ratio;+ const scale = ratio / request.ratio;+ const origin = { x: input.headers.width * ratio, y: input.headers.height * ratio };++ // Each side splits at the frozen panes: the panes stay put, the cells past them follow the scroll.+ const columns = [+ { start: 0, end: Math.min(panes.width, input.width), shift: 0 },+ { start: panes.width, end: input.width, shift: painted.frame.viewport.x - input.x },+ ];++ const rows = [+ { start: 0, end: Math.min(panes.height, input.height), shift: 0 },+ { start: panes.height, end: input.height, shift: painted.frame.viewport.y - input.y },+ ];++ // The whole canvas clears, headers included: their edges cover part of a device pixel, which would darken with every+ // paint drawn over the last.+ context.save();+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(0, 0, context.canvas.width, context.canvas.height);++ rows.forEach((row) =>+ columns.forEach((column) => {+ if (row.end <= row.start || column.end <= column.start) return;++ const left = Math.round(origin.x + column.start * ratio);+ const top = Math.round(origin.y + row.start * ratio);++ context.save();+ context.beginPath();+ context.rect(+ left,+ top,+ Math.round(origin.x + column.end * ratio) - left,+ Math.round(origin.y + row.end * ratio) - top,+ );+ context.clip();+ // Whole device pixels, so a frame at its own position lands exactly where the worker painted its cells.+ context.drawImage(+ bitmap,+ Math.round(origin.x + column.shift * ratio - request.offset.x * scale),+ Math.round(origin.y + row.shift * ratio - request.offset.y * scale),+ bitmap.width * scale,+ bitmap.height * scale,+ );+ context.restore();+ }),+ );++ context.restore();+}++/**+ * A frame's grid at another scroll position, moved as `paintCells` moves its cells: the tracks past the frozen panes+ * shift by `shift`, and never under the panes, so headers, selection and hit tests follow the cells on screen.+ */+export function shiftGrid(+ grid: GridMeta,+ frozen: { readonly rows: number; readonly cols: number },+ panes: { readonly width: number; readonly height: number },+ shift: { readonly x: number; readonly y: number },+): GridMeta {+ if (shift.x === 0 && shift.y === 0) return grid;++ const axis = (+ offsets: readonly number[],+ start: number,+ indices: readonly number[] | undefined,+ count: number,+ edge: number,+ by: number,+ ) => {+ // The offsets up to the panes' far edge belong to the panes; without panes, every track moves.+ const fixed =+ count === 0+ ? -1+ : offsets.findIndex((_, position) => trackIndex(start, indices, position) >= count);++ return offsets.map((offset, position) => {+ if (fixed === -1 && count > 0) return offset;++ if (position <= fixed) return offset;++ return count === 0 ? offset + by : Math.max(edge, offset + by);+ });+ };++ return {+ ...grid,+ colOffsets: axis(+ grid.colOffsets,+ grid.startCol,+ grid.colIndices,+ frozen.cols,+ panes.width,+ shift.x,+ ),+ rowOffsets: axis(+ grid.rowOffsets,+ grid.startRow,+ grid.rowIndices,+ frozen.rows,+ panes.height,+ shift.y,+ ),+ };+}++/** The sheet row or column at a position in a frame's grid: its indices when tracks are skipped, else consecutive. */+function trackIndex(start: number, indices: readonly number[] | undefined, position: number) {+ return indices?.[position] ?? start + position;+}++/**+ * Draws the column letters and row numbers of a frame's tracks, frozen panes first, along the top and left edges.+ * Hidden tracks have no width in the grid, so they get no header.+ */+export function paintHeaders(+ context: CanvasRenderingContext2D,+ input: {+ readonly grid: GridMeta;+ readonly ratio: number;+ readonly headers: Headers;+ readonly width: number;+ readonly height: number;+ readonly selected: CellRange | undefined;+ },+) {+ const grid = input.grid;+ const headers = input.headers;+ const selected = input.selected;++ context.save();+ context.setTransform(input.ratio, 0, 0, input.ratio, 0, 0);+ context.fillStyle = colours.header;+ context.fillRect(0, 0, input.width, headers.height);+ context.fillRect(0, 0, headers.width, input.height);+ context.font = font;+ context.textAlign = "center";+ context.textBaseline = "middle";++ grid.colOffsets.slice(0, -1).forEach((offset, position) => {+ const index = trackIndex(grid.startCol, grid.colIndices, position);++ paintHeader(context, {+ x: headers.width + offset,+ y: 0,+ width: grid.colOffsets[position + 1]! - offset,+ height: headers.height,+ label: columnName(index),+ selected: !!selected && index >= selected.left && index <= selected.right,+ clip: { x: headers.width, width: input.width - headers.width },+ });+ });+ grid.rowOffsets.slice(0, -1).forEach((offset, position) => {+ const index = trackIndex(grid.startRow, grid.rowIndices, position);++ paintHeader(context, {+ x: 0,+ y: headers.height + offset,+ width: headers.width,+ height: grid.rowOffsets[position + 1]! - offset,+ label: String(index + 1),+ selected: !!selected && index >= selected.top && index <= selected.bottom,+ clip: { y: headers.height, height: input.height - headers.height },+ });+ });++ line(context, colours.edge, 0, headers.height, input.width, headers.height);+ line(context, colours.edge, headers.width, 0, headers.width, input.height);+ // Excel's select-all corner: a small triangle pointing at the cells.+ context.fillStyle = colours.corner;+ context.beginPath();+ context.moveTo(headers.width - 4, headers.height - 12);+ context.lineTo(headers.width - 4, headers.height - 4);+ context.lineTo(headers.width - 12, headers.height - 4);+ context.closePath();+ context.fill();+ context.restore();+}++/** Outlines the selected range and tints it, leaving its active cell clear, in the cells beside the headers. */+export function paintSelection(+ context: CanvasRenderingContext2D,+ input: {+ readonly grid: GridMeta;+ readonly ratio: number;+ readonly headers: Headers;+ readonly width: number;+ readonly height: number;+ readonly range: CellRange;+ readonly active: CellRange;+ },+) {+ const range = rangeRect(input.grid, input.range);++ if (!range) return;++ const active = rangeRect(input.grid, input.active);++ context.save();+ context.setTransform(+ input.ratio,+ 0,+ 0,+ input.ratio,+ input.headers.width * input.ratio,+ input.headers.height * input.ratio,+ );+ context.beginPath();+ context.rect(0, 0, input.width, input.height);+ context.clip();++ if (!sameRect(range, active)) {+ context.beginPath();+ context.rect(range.x, range.y, range.w, range.h);++ if (active) context.rect(active.x, active.y, active.w, active.h);++ context.fillStyle = colours.selection;+ context.fill("evenodd");+ }++ context.strokeStyle = colours.accent;+ context.lineWidth = 2;+ context.strokeRect(range.x, range.y, range.w, range.h);+ context.restore();+}++function paintHeader(+ context: CanvasRenderingContext2D,+ header: {+ readonly x: number;+ readonly y: number;+ readonly width: number;+ readonly height: number;+ readonly label: string;+ readonly selected: boolean;+ readonly clip: {+ readonly x?: number;+ readonly y?: number;+ readonly width?: number;+ readonly height?: number;+ };+ },+) {+ if (header.width <= 0 || header.height <= 0) return;++ const columns = header.y === 0;++ context.save();+ context.beginPath();+ context.rect(+ header.clip.x ?? header.x,+ header.clip.y ?? header.y,+ header.clip.width ?? header.width,+ header.clip.height ?? header.height,+ );+ context.clip();++ // A selected header is tinted, with a bar on the edge that meets the cells.+ if (header.selected) {+ context.fillStyle = colours.selectedHeader;+ context.fillRect(header.x, header.y, header.width, header.height);+ context.fillStyle = colours.accent;+ context.fillRect(+ columns ? header.x : header.x + header.width - 2,+ columns ? header.y + header.height - 2 : header.y,+ columns ? header.width : 2,+ columns ? 2 : header.height,+ );+ }++ // A track too small for its label shows none, rather than labels piled over each other.+ if (columns ? context.measureText(header.label).width + 2 <= header.width : header.height >= 9) {+ context.fillStyle = header.selected ? colours.selectedLabel : colours.label;+ context.fillText(header.label, header.x + header.width / 2, header.y + header.height / 2 + 0.5);+ }++ context.restore();++ // The line after the header, where the gridline between its cells and the next ones meets it.+ const x = columns ? header.x + header.width : header.x;+ const y = columns ? header.y : header.y + header.height;++ line(+ context,+ colours.line,+ x,+ y,+ columns ? x : x + header.width,+ columns ? y + header.height : y,+ );+}++/** A one-pixel line centred on its coordinates, as the display list draws gridlines, so the two meet. */+function line(+ context: CanvasRenderingContext2D,+ colour: string,+ x1: number,+ y1: number,+ x2: number,+ y2: number,+) {+ context.strokeStyle = colour;+ context.lineWidth = 1;+ context.beginPath();+ context.moveTo(x1, y1);+ context.lineTo(x2, y2);+ context.stroke();+}++function sameRect(a: { x: number; y: number; w: number; h: number }, b: typeof a | null) {+ return !!b && a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;+}diff --git a/apps/web/src/components/files/office/sheet-protocol.ts b/apps/web/src/components/files/office/sheet-protocol.tsnew file mode 100644index 00000000000..6f41fc8c3cf--- /dev/null+++ b/apps/web/src/components/files/office/sheet-protocol.ts@@ -0,0 +1,93 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import type { SheetInfo } from "@betteroffice/xlsx";+import type { CellAddr, CellRange, GridMeta, HyperlinkRegion } from "@betteroffice/xlsx/headless";+import type { Span } from "./sheet-cells";+import type { Method } from "./worker-rpc";++// What the Excel preview's window and its workbook worker say to each other. The window keeps the selection, the+// headers and the scroll area; the engine, its recalculation, the display lists and the cells' painting live in the+// worker.++/** A visible sheet: its index in the workbook and its tab name. */+export type SheetTab = { readonly index: number; readonly name: string };++/** What a sheet's grid needs from the workbook before its first frame. */+export type SheetLayout = {+ readonly info: SheetInfo;+ /** The used range; undefined for an empty sheet. */+ readonly used: CellRange | undefined;+ readonly merges: readonly CellRange[];+ readonly hidden: { readonly rows: readonly Span[]; readonly columns: readonly Span[] };+ /** How far the charts reach, in the engine's scroll coordinates. */+ readonly chartWidth: number;+ readonly chartHeight: number;+};++/** A viewport, in CSS pixels and the engine's scroll coordinates: the frozen panes, then the cells past them from `x`, `y`. */+export type SheetViewport = {+ readonly x: number;+ readonly y: number;+ readonly width: number;+ readonly height: number;+};++/** The cells of one viewport. */+export type SheetFrameRequest = {+ readonly sheet: number;+ readonly x: number;+ readonly y: number;+ readonly width: number;+ readonly height: number;+ /** Device pixels per CSS pixel. */+ readonly ratio: number;+ /** Where the cells start inside the bitmap's first device pixel, so a frame lands where a direct paint would. */+ readonly offset: { readonly x: number; readonly y: number };+ /**+ * A larger viewport around this one to draw instead, so the frame still covers the screen after a scroll that+ * outruns the next frame. The worker draws the requested viewport alone where the engine refuses the larger one.+ */+ readonly wider: SheetViewport | undefined;+};++/** A painted frame: the bitmap and the little geometry the window needs to draw headers, select and follow links. */+export type SheetFrame = {+ /** The cells, `offset` device pixels in from its top-left corner. */+ readonly bitmap: ImageBitmap;+ /** The viewport the bitmap shows: the requested one, or a wider one with the margin. */+ readonly viewport: SheetViewport;+ readonly grid: GridMeta | undefined;+ readonly hyperlinks: readonly HyperlinkRegion[];+ /** The frozen panes' size in the frame. */+ readonly frozen: { readonly width: number; readonly height: number };+ /** Where the sheet's last cell ends, past the frozen panes; undefined when the engine cannot tell. */+ readonly end: { readonly x: number; readonly y: number } | undefined;+};++/** The workbook worker's methods. Every method but `open` needs the workbook `open` opened. */+export type SheetMethods = {+ /**+ * Opens the file's bytes and the sheet to show first: the active one, or the first visible one when the workbook was+ * saved on a hidden sheet. Undefined when no sheet is visible.+ */+ readonly open: Method<+ { readonly bytes: ArrayBuffer },+ { readonly tabs: readonly SheetTab[]; readonly layout: SheetLayout } | undefined+ >;+ /** Makes a sheet the active one; rejects, leaving the sheet before it active, when it cannot open. */+ readonly show: Method<{ readonly sheet: number }, SheetLayout>;+ /** Paints a frame; undefined when even its smallest tiles cannot be drawn. */+ readonly frame: Method<SheetFrameRequest, SheetFrame | undefined>;+ /** Where a cell starts and where the cell past it starts, to scroll it into view. */+ readonly position: Method<+ { readonly sheet: number; readonly cell: CellAddr },+ | { readonly start: { x: number; y: number }; readonly next: { x: number; y: number } }+ | undefined+ >;+ /** The cells' text as they show, row by row, for screen readers. */+ readonly cells: Method<+ { readonly sheet: number; readonly range: CellRange },+ readonly (readonly string[])[]+ >;+ /** The cells as they show, as tab-separated text to paste; undefined when they cannot be read. */+ readonly copy: Method<{ readonly sheet: number; readonly range: CellRange }, string | undefined>;+};diff --git a/apps/web/src/components/files/office/slide-fonts.ts b/apps/web/src/components/files/office/slide-fonts.tsnew file mode 100644index 00000000000..e4a8391a690--- /dev/null+++ b/apps/web/src/components/files/office/slide-fonts.ts@@ -0,0 +1,202 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import type {+ PositionedTextRun,+ PresentationHandle,+ SlideDisplayList,+ SlidePrimitive,+} from "@betteroffice/pptx";+import { loadFace, presentationFace, scriptFace } from "./fonts";+import type { DeckText, FallbackScript, FontStyle } from "./slide-text";++/** A face the deck asks for: a family it names, or the fallback for a script the Latin faces lack. */+type Want =+ | { readonly family: string; readonly script?: undefined }+ | { readonly script: FallbackScript; readonly family?: undefined };++/** A face registered with both the engine and the browser. */+type Face = { readonly want: Want; readonly style: FontStyle; readonly css: string };++/**+ * The faces one open deck draws with, added to `fonts`: the font set of the deck's own worker, which paints it. The+ * engine shapes each face under the family name the deck uses, and the browser holds the same bytes under a private+ * name that the laid-out frames are renamed to. Painting then matches shaping, and the deck's names (such as Inter or+ * Segoe UI) never replace a font the painter itself needs.+ */+export function slideFonts(deck: PresentationHandle, fonts: FontFaceSet) {+ const faces = new Map<number, Face>();+ const names = new Map<string, string>();+ const registered = new Set<string>();+ const loads = new Map<string, Promise<void>>();+ const settled = new Set<string>();++ /** Loads a face's bytes and browser face; the returned function registers both, so callers choose the order. */+ const prepare = async (want: Want, requested: FontStyle) => {+ const source = want.script+ ? scriptFace(want.script, requested.bold, requested.italic)+ : presentationFace(want.family, requested.bold, requested.italic);++ if (!source) return;++ // A family without the requested style gets the face it has, which the browser then slants or emboldens.+ const style = { bold: source.weight === 700, italic: source.style === "italic" };+ // The worker holds this deck's faces alone, so the names only need to differ from each other.+ const css = names.get(wantKey(want)) ?? `slide-${names.size}`;+ const key = faceKey(want, style);++ names.set(wantKey(want), css);++ if (registered.has(key)) return;++ const buffer = await loadFace(source).catch(() => undefined);++ if (!buffer) return;++ const browser = await new FontFace(css, buffer, {+ weight: style.bold ? "700" : "400",+ style: style.italic ? "italic" : "normal",+ })+ .load()+ .catch(() => undefined);++ if (!browser) return;++ return () => {+ if (registered.has(key)) return;++ registered.add(key);+ fonts.add(browser);++ const face = {+ family: want.script ? css : want.family,+ ...style,+ bytes: new Uint8Array(buffer),+ };++ faces.set(want.script ? deck.registerFallbackFont(face) : deck.registerFont(face), {+ want,+ style,+ css,+ });+ };+ };++ /** Loads and registers one face once; later requests share the first. */+ const request = (want: Want, style: FontStyle) => {+ const key = faceKey(want, style);+ const existing = loads.get(key);++ if (existing) return existing;++ const load = prepare(want, style).then((register) => {+ register?.();+ settled.add(key);+ });++ loads.set(key, load);++ return load;+ };++ /** The faces a frame drew in a substitute style whose own face has not loaded or failed yet. */+ const missing = (primitives: readonly SlidePrimitive[]) =>+ textRuns(primitives).flatMap((run) => {+ const face = faces.get(run.fontId);+ const style = { bold: run.bold, italic: run.italic };++ if (!face || sameStyle(face.style, style) || settled.has(faceKey(face.want, style)))+ return [];++ return [{ want: face.want, style }];+ });++ const rename = (primitive: SlidePrimitive): SlidePrimitive => {+ if (primitive.kind === "textBox")+ return {+ ...primitive,+ lines: primitive.lines.map((line) => ({+ ...line,+ runs: line.runs.map((run) => ({+ ...run,+ fontFamily: faces.get(run.fontId)?.css ?? run.fontFamily,+ })),+ })),+ };++ if (primitive.kind === "table" || primitive.kind === "chart")+ return { ...primitive, primitives: primitive.primitives.map(rename) };++ return primitive;+ };++ return {+ /**+ * Registers the faces the deck's text names, in the order `text` ranks them: the engine draws every family it+ * cannot find with the first. Resolves once each face has loaded or failed.+ */+ load: async (text: DeckText) => {+ const regular = { bold: false, italic: false };+ // The engine lays no text out without a face, so a deck that names none gets PowerPoint's own default.+ const families =+ text.families.length > 0 ? text.families : [{ name: "Calibri", styles: [regular] }];++ const wants: { want: Want; style: FontStyle }[] = [+ ...families.flatMap((family) =>+ family.styles.map((style) => ({ want: { family: family.name }, style })),+ ),+ ...text.scripts.map((script) => ({ want: { script }, style: regular })),+ ];++ const registers = await Promise.all(wants.map((entry) => prepare(entry.want, entry.style)));++ registers.forEach((register) => register?.());+ wants.forEach((entry) => {+ const key = faceKey(entry.want, entry.style);++ loads.set(key, Promise.resolve());+ settled.add(key);+ });+ },++ /**+ * Lays a slide out. When its text asks for a style a registered face lacks, such as a bold the title style+ * inherits, that face loads and the slide lays out again. The frame names the browser's faces, ready to paint.+ */+ layout: async (index: number) => {+ const settle = async (rounds: number): Promise<SlideDisplayList> => {+ const frame = deck.layoutSlide(index);+ const wanted = rounds === 0 ? [] : missing(frame.primitives);++ if (wanted.length === 0) return { ...frame, primitives: frame.primitives.map(rename) };++ await Promise.all(wanted.map((entry) => request(entry.want, entry.style)));++ return settle(rounds - 1);+ };++ return settle(2);+ },+ };+}++function textRuns(primitives: readonly SlidePrimitive[]): PositionedTextRun[] {+ return primitives.flatMap((primitive) => {+ if (primitive.kind === "textBox") return primitive.lines.flatMap((line) => line.runs);++ if (primitive.kind === "table" || primitive.kind === "chart")+ return textRuns(primitive.primitives);++ return [];+ });+}++function wantKey(want: Want) {+ return want.script ? `script:${want.script}` : `family:${want.family.toLowerCase()}`;+}++function faceKey(want: Want, style: FontStyle) {+ return `${wantKey(want)}|${style.bold}|${style.italic}`;+}++function sameStyle(left: FontStyle, right: FontStyle) {+ return left.bold === right.bold && left.italic === right.italic;+}diff --git a/apps/web/src/components/files/office/slide-protocol.ts b/apps/web/src/components/files/office/slide-protocol.tsnew file mode 100644index 00000000000..bbac52d3c81--- /dev/null+++ b/apps/web/src/components/files/office/slide-protocol.ts@@ -0,0 +1,47 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import type { Method } from "./worker-rpc";++/** The longest side a decoded picture keeps: enough for a full-width slide on a high-density screen. */+export const maxImageSide = 2560;++/** What the window shows of one slide besides its bitmap. */+export type SlideSummary = {+ /** In CSS pixels. */+ readonly width: number;+ readonly height: number;+ readonly hidden: boolean;+ readonly notes: string | undefined;+};++/** An SVG picture the worker cannot decode, which the window rasterizes at `size`, or at its own size when absent. */+export type VectorRequest = {+ readonly asset: string;+ readonly blob: Blob;+ readonly size: { readonly width: number; readonly height: number } | undefined;+};++/** A rasterized SVG picture, or none when the window could not decode it either. */+export type VectorBitmap = { readonly asset: string; readonly bitmap: ImageBitmap | undefined };++export type SlidePainted =+ | {+ readonly kind: "painted";+ /** The slide at the requested density, or less when that would exceed the bitmap caps. */+ readonly bitmap: ImageBitmap;+ /** SVG pictures the slide drew without, or too coarse: paint again once the worker has them. */+ readonly vectors: readonly VectorRequest[];+ }+ /** The slide does not lay out, or does not paint even without shadows. */+ | { readonly kind: "failed" }+ /** The caller aborted the paint while it ran. */+ | { readonly kind: "cancelled" };++/** The PowerPoint worker's methods. */+export type SlideMethods = {+ /** Opens the deck once per worker, its fonts included. Rejects when the engine cannot read it. */+ readonly open: Method<{ readonly bytes: ArrayBuffer }, readonly SlideSummary[]>;+ /** Paints one slide at `density` device pixels per CSS pixel. */+ readonly paint: Method<{ readonly index: number; readonly density: number }, SlidePainted>;+ /** Hands over SVG pictures rasterized for `VectorRequest`s. */+ readonly vectors: Method<readonly VectorBitmap[], void>;+};diff --git a/apps/web/src/components/files/office/slide-text.ts b/apps/web/src/components/files/office/slide-text.tsnew file mode 100644index 00000000000..396c0cb0b27--- /dev/null+++ b/apps/web/src/components/files/office/slide-text.ts@@ -0,0 +1,401 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";+import { inspectPresentation, type DeckSnapshot } from "@betteroffice/pptx";++/** A text style a deck draws with. */+export type FontStyle = { readonly bold: boolean; readonly italic: boolean };++/** A family the deck names, with the styles its text asks for. */+export type DeckFamily = { readonly name: string; readonly styles: readonly FontStyle[] };++/** The scripts the bundled Latin faces may lack, which have a bundled fallback face. */+export type FallbackScript = "hebrew" | "arabic";++/** What a deck's text needs from the fonts, and which slides it hides. */+export type DeckText = {+ /** Most important first: the face registered first also draws every family the deck names but nobody found. */+ readonly families: readonly DeckFamily[];+ readonly scripts: readonly FallbackScript[];+ /** One flag per slide, in deck order. */+ readonly hidden: readonly boolean[];+};++const RunStyle = Schema.Struct({+ bold: Schema.optional(Schema.NullOr(Schema.Boolean)),+ italic: Schema.optional(Schema.NullOr(Schema.Boolean)),+ fontFamily: Schema.optional(Schema.NullOr(Schema.String)),+});++const Body = Schema.Struct({+ paragraphs: Schema.Array(+ Schema.Struct({+ properties: Schema.optional(+ Schema.NullOr(+ Schema.Struct({+ defaultRun: Schema.optional(Schema.NullOr(RunStyle)),+ }),+ ),+ ),+ runs: Schema.Array(+ Schema.Struct({+ text: Schema.String,+ properties: Schema.optional(Schema.NullOr(RunStyle)),+ }),+ ),+ }),+ ),+});++type Drawing = {+ readonly text?: typeof Body.Type | null | undefined;+ readonly children?: readonly Drawing[] | undefined;+ readonly data?: typeof Table.Type | null | undefined;+};++const Table = Schema.Struct({+ rows: Schema.optional(+ Schema.Array(+ Schema.Struct({+ cells: Schema.Array(Schema.Struct({ text: Schema.optional(Schema.NullOr(Body)) })),+ }),+ ),+ ),+});++/** A slide object: a shape, group, picture or graphic frame. */+const Drawing: Schema.Codec<Drawing> = Schema.Struct({+ text: Schema.optional(Schema.NullOr(Body)),+ children: Schema.optional(Schema.Array(Schema.suspend((): Schema.Codec<Drawing> => Drawing))),+ // A table's cells; other frames, such as charts, carry no rows.+ data: Schema.optional(Schema.NullOr(Table)),+});++const ThemeFont = Schema.Struct({ latin: Schema.String });++const Inspected = Schema.Struct({+ slides: Schema.Array(+ Schema.Struct({+ hidden: Schema.optional(Schema.Boolean),+ drawings: Schema.Array(Drawing),+ }).pipe(Schema.encodeKeys({ drawings: "shapes" })),+ ),+ layouts: Schema.optional(+ Schema.Array(+ Schema.Struct({ drawings: Schema.Array(Drawing) }).pipe(+ Schema.encodeKeys({ drawings: "shapes" }),+ ),+ ),+ ),+ masters: Schema.optional(+ Schema.Array(+ Schema.Struct({+ drawings: Schema.Array(Drawing),+ textStyles: Schema.optional(+ Schema.NullOr(+ Schema.Record(+ Schema.String,+ Schema.Array(Schema.Struct({ defaultRun: Schema.optional(Schema.NullOr(RunStyle)) })),+ ),+ ),+ ),+ }).pipe(Schema.encodeKeys({ drawings: "shapes" })),+ ),+ ),+ themes: Schema.optional(+ Schema.Array(+ Schema.Struct({+ theme: Schema.optional(+ Schema.NullOr(+ Schema.Struct({+ fontScheme: Schema.optional(+ Schema.NullOr(Schema.Struct({ majorFont: ThemeFont, minorFont: ThemeFont })),+ ),+ }),+ ),+ ),+ }),+ ),+ ),+});++const decodeInspected = Schema.decodeUnknownOption(Inspected);++const scriptRanges: readonly (readonly [FallbackScript, RegExp])[] = [+ ["hebrew", /[\u0590-\u05FF\uFB1D-\uFB4F]/u],+ ["arabic", /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/u],+];++/**+ * Reads the families, styles and scripts a deck's text uses, from its slides, layouts, masters and theme. When the+ * engine's inspection does not decode, the slides' own runs stand in, without theme fonts or hidden flags.+ */+export function deckText(bytes: Uint8Array, snapshot: DeckSnapshot): DeckText {+ return Option.match(decodeInspected(inspectPresentation(withoutMedia(bytes))), {+ onNone: () => fromSnapshot(snapshot),+ onSome: (inspected) => {+ const schemes =+ inspected.themes?.flatMap((theme) =>+ theme.theme?.fontScheme ? [theme.theme.fontScheme] : [],+ ) ?? [];+ const minor = schemes[0]?.minorFont.latin ?? "";++ const drawings = [+ ...inspected.slides.flatMap((slide) => slide.drawings),+ ...(inspected.layouts ?? []).flatMap((layout) => layout.drawings),+ ...(inspected.masters ?? []).flatMap((master) => master.drawings),+ ];++ const defaults = (inspected.masters ?? []).flatMap((master) =>+ Object.values(master.textStyles ?? {}).flatMap((levels) =>+ levels.flatMap((level) =>+ level.defaultRun ? [{ text: "", style: level.defaultRun }] : [],+ ),+ ),+ );++ return summarize(+ [...drawings.flatMap(drawingRuns), ...defaults].flatMap((run) => {+ const family = run.style?.fontFamily;+ if (!schemes.length || (family && !family.startsWith("+mn") && !family.startsWith("+mj")))+ return [run];+ return schemes.map((scheme) => ({+ ...run,+ style: {+ ...run.style,+ fontFamily: family?.startsWith("+mj")+ ? scheme.majorFont.latin+ : scheme.minorFont.latin,+ },+ }));+ }),+ (family) => (family?.startsWith("+") ? "" : (family ?? "")),+ minor,+ inspected.slides.map((slide) => slide.hidden ?? false),+ );+ },+ });+}++/** A file in the deck's zip package: where its central directory record and its local data sit. */+type Entry = {+ readonly name: string;+ readonly record: number;+ readonly length: number;+ readonly local: number;+};++/**+ * The package without its pictures and media. The inspection reads only the deck's text and styles, but returns every+ * picture as base64, which for a deck of photos costs tens of megabytes of engine memory the worker never gives back.+ * Entries keep their compressed bytes. A package this cannot read, such as a ZIP64 one, stays as it is.+ */+function withoutMedia(bytes: Uint8Array): Uint8Array {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const end = endOfDirectory(view);++ if (end === undefined) return bytes;++ const count = view.getUint16(end + 10, true);+ const directory = view.getUint32(end + 16, true);++ if (count === 0xffff || directory === 0xffffffff || directory > end) return bytes;++ const entries = readEntries(view, directory, end, count);++ if (!entries || !entries.some((entry) => entry.name.startsWith("ppt/media/"))) return bytes;++ // An entry's local header and data run up to the next entry's, or to the central directory.+ const starts = entries.map((entry) => entry.local).toSorted((left, right) => left - right);++ const kept = entries+ .filter((entry) => !entry.name.startsWith("ppt/media/"))+ .map((entry) => ({+ entry,+ start: entry.local,+ end: starts.find((start) => start > entry.local) ?? directory,+ }));++ // Where each kept entry's local data and directory record land in the new package.+ const locals = offsets(kept.map((part) => part.end - part.start));+ const records = offsets(kept.map((part) => part.entry.length));+ const size = locals.at(-1) ?? 0;+ const directorySize = records.at(-1) ?? 0;+ const out = new Uint8Array(size + directorySize + 22);+ const writer = new DataView(out.buffer);++ kept.forEach((part, index) => {+ const local = locals[index] ?? 0;+ const record = size + (records[index] ?? 0);++ out.set(bytes.subarray(part.start, part.end), local);+ out.set(bytes.subarray(part.entry.record, part.entry.record + part.entry.length), record);+ writer.setUint32(record + 42, local, true);+ });++ const tail = size + directorySize;++ out.set(bytes.subarray(end, end + 22), tail);+ writer.setUint16(tail + 8, kept.length, true);+ writer.setUint16(tail + 10, kept.length, true);+ writer.setUint32(tail + 12, directorySize, true);+ writer.setUint32(tail + 16, size, true);+ writer.setUint16(tail + 20, 0, true);++ return out;+}++/** Where each length starts when they are laid end to end, then where the last ends. */+function offsets(lengths: readonly number[]) {+ return lengths.reduce(+ (list, length) => {+ list.push((list.at(-1) ?? 0) + length);++ return list;+ },+ [0],+ );+}++/** Where the end of central directory record starts, searched back from the end past any comment. */+function endOfDirectory(view: DataView) {+ const last = view.byteLength - 22;+ const first = Math.max(0, last - 0xffff);++ for (let at = last; at >= first; at--) if (view.getUint32(at, true) === 0x06054b50) return at;++ return undefined;+}++/**+ * The central directory's records, from `directory` up to the end record at `end`; undefined when one is malformed: it+ * runs past the directory, or its local header does not sit before it.+ */+function readEntries(view: DataView, directory: number, end: number, count: number) {+ const decoder = new TextDecoder();++ return Array.from({ length: count }).reduce<{ at: number; entries: Entry[] } | undefined>(+ (state) => {+ if (!state || state.at + 46 > end || view.getUint32(state.at, true) !== 0x02014b50)+ return undefined;++ const nameLength = view.getUint16(state.at + 28, true);+ const length =+ 46 + nameLength + view.getUint16(state.at + 30, true) + view.getUint16(state.at + 32, true);+ const local = view.getUint32(state.at + 42, true);++ // A local header is 30 bytes before its name and data.+ if (state.at + length > end || local + 30 > directory) return undefined;++ const name = decoder.decode(+ new Uint8Array(view.buffer, view.byteOffset + state.at + 46, nameLength),+ );++ state.entries.push({ name, record: state.at, length, local });++ return { at: state.at + length, entries: state.entries };+ },+ { at: directory, entries: [] },+ )?.entries;+}++type Run = { readonly text: string; readonly style: typeof RunStyle.Type | null | undefined };++function drawingRuns(drawing: Drawing): Run[] {+ return [+ ...bodyRuns(drawing.text),+ ...(drawing.data?.rows ?? []).flatMap((row) =>+ row.cells.flatMap((cell) => bodyRuns(cell.text)),+ ),+ ...(drawing.children ?? []).flatMap(drawingRuns),+ ];+}++function bodyRuns(body: typeof Body.Type | null | undefined): Run[] {+ return (body?.paragraphs ?? []).flatMap((paragraph) =>+ paragraph.runs.map((run) => ({+ text: run.text,+ style: {+ fontFamily: run.properties?.fontFamily ?? paragraph.properties?.defaultRun?.fontFamily,+ bold: run.properties?.bold ?? paragraph.properties?.defaultRun?.bold,+ italic: run.properties?.italic ?? paragraph.properties?.defaultRun?.italic,+ },+ })),+ );+}++function fromSnapshot(snapshot: DeckSnapshot): DeckText {+ const runs = (drawings: DeckSnapshot["slides"][number]["shapes"]): Run[] =>+ drawings.flatMap((drawing) => [+ ...drawing.textStories.flatMap((story) =>+ story.paragraphs.flatMap((paragraph) =>+ paragraph.runs.map((run) => ({ text: run.text, style: run.style })),+ ),+ ),+ ...runs(drawing.children),+ ]);++ return summarize(+ snapshot.slides.flatMap((slide) => runs(slide.shapes)),+ (family) => family ?? "",+ "",+ snapshot.slides.map(() => false),+ );+}++/**+ * Groups runs by the family they resolve to: the theme's body font first, then by how much text each draws. The+ * masters' default runs count too, so a theme font that placeholders inherit without naming it is still found.+ */+function summarize(+ runs: readonly Run[],+ resolve: (family: string | null | undefined) => string,+ theme: string,+ hidden: readonly boolean[],+): DeckText {+ const families = new Map<+ string,+ { name: string; weight: number; styles: Map<string, FontStyle> }+ >();+ const body = theme.trim().toLowerCase();+ const text = runs.map((run) => run.text).join("");++ runs.forEach((run) => {+ const name = resolve(run.style?.fontFamily).trim();++ if (!name) return;++ const style = { bold: run.style?.bold ?? false, italic: run.style?.italic ?? false };+ const family = families.get(name.toLowerCase()) ?? {+ name,+ weight: 0,+ styles: new Map<string, FontStyle>(),+ };++ family.weight += run.text.length;+ family.styles.set(`${style.bold}|${style.italic}`, style);+ families.set(name.toLowerCase(), family);+ });++ return {+ families: [...families.entries()]+ .toSorted((left, right) => rank(right, body) - rank(left, body))+ .map((entry) => ({+ name: entry[1].name,+ // Regular first, so a family's first face is the one its unstyled text draws with.+ styles: [...entry[1].styles.values()].toSorted(+ (left, right) => styleRank(left) - styleRank(right),+ ),+ })),+ scripts: scriptRanges.flatMap((entry) => (entry[1].test(text) ? [entry[0]] : [])),+ hidden,+ };+}++function rank(entry: readonly [string, { readonly weight: number }], body: string) {+ return entry[0] === body ? Number.POSITIVE_INFINITY : entry[1].weight;+}++function styleRank(style: FontStyle) {+ return (style.bold ? 1 : 0) + (style.italic ? 2 : 0);+}diff --git a/apps/web/src/components/files/office/spreadsheet.worker.ts b/apps/web/src/components/files/office/spreadsheet.worker.tsnew file mode 100644index 00000000000..eeb6b41478f--- /dev/null+++ b/apps/web/src/components/files/office/spreadsheet.worker.ts@@ -0,0 +1,309 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import {+ initWasm,+ openWorkbook,+ toTsv,+ type SheetInfo,+ type WorkbookHandle,+ type XlsxCellRead,+ type XlsxRangeTarget,+} from "@betteroffice/xlsx";+import type { CellRange } from "@betteroffice/xlsx/headless";+import { anchorRange, attempt, lastCell, parseRange, parseSpans } from "./sheet-cells";+import { drawFrame, paintFrame } from "./sheet-frame";+import { frozenSize } from "./sheet-paint";+import type { SheetLayout, SheetMethods, SheetTab } from "./sheet-protocol";+import { serveWorker, Transfer } from "./worker-rpc";++// One worker holds one open workbook: its engine, recalculation, display lists and the painting of its cells. The+// window terminates the worker when the workbook closes, which is the only way the engine's memory is given back.++type Opened = {+ readonly workbook: WorkbookHandle;+ /** The active sheet's metadata; the engine draws only the active sheet. */+ info: SheetInfo;+ /** Where each sheet's last cell ends, by sheet and frozen panes' size; measured once, as it costs a frame. */+ readonly ends: Map<string, { readonly x: number; readonly y: number } | undefined>;+ /** The one canvas every frame paints on and hands over as a bitmap. */+ readonly surface: OffscreenCanvas;+};++/** The workbook this worker opened, once it has. */+type State = { opened: Opened | undefined };++const state: State = { opened: undefined };++serveWorker<SheetMethods>({+ open: async (input) => {+ if (state.opened) throw new Error("The worker already holds a workbook");++ await initWasm();++ const workbook = openWorkbook(new Uint8Array(input.bytes));+ const info = workbook.sheetInfo();++ state.opened = { workbook, info, ends: new Map(), surface: new OffscreenCanvas(1, 1) };++ const tabs = visibleTabs(workbook, info);+ // A workbook saved on a hidden sheet opens on the first visible one, as Excel does.+ const first = tabs.find((tab) => tab.index === info.activeSheet) ?? tabs[0];++ if (!first) return undefined;++ return { tabs, layout: show(state.opened, first.index) };+ },+ show: (input) => {+ const opened = required();+ const current = opened.info.activeSheet;+ const layout = attempt(() => show(opened, input.sheet));++ if (layout) return layout;++ // One sheet that fails to open leaves the others readable: go back to the sheet on show.+ attempt(() => show(opened, current));++ throw new Error(`Sheet ${input.sheet} could not open`);+ },+ frame: (input) => {+ const opened = active(input.sheet);+ const frozen = { rows: opened.info.frozenRows, cols: opened.info.frozenCols };+ const viewport = { x: input.x, y: input.y, width: input.width, height: input.height };+ const drawn = drawFrame(opened.workbook, viewport, frozen, input.wider);++ if (!drawn) return undefined;++ const surface = opened.surface;+ const width = Math.ceil(input.offset.x + drawn.viewport.width * input.ratio);+ const height = Math.ceil(input.offset.y + drawn.viewport.height * input.ratio);++ if (surface.width !== width) surface.width = width;++ if (surface.height !== height) surface.height = height;++ const context = surface.getContext("2d");++ if (!context) return undefined;++ paintFrame(context, drawn, { ratio: input.ratio, origin: input.offset });++ const bitmap = surface.transferToImageBitmap();+ const grid = drawn.list.grid;+ const panes = frozenSize(grid, frozen);++ return new Transfer(+ {+ bitmap,+ viewport: drawn.viewport,+ grid,+ hyperlinks: drawn.list.hyperlinks ?? [],+ frozen: panes,+ end: end(opened, input.sheet, panes),+ },+ [bitmap],+ );+ },+ position: (input) => {+ const workbook = required().workbook;+ const cell = input.cell;+ const start = attempt(() => workbook.cellPosition(input.sheet, cell.row, cell.col));++ const next = attempt(() =>+ workbook.cellPosition(+ input.sheet,+ Math.min(cell.row + 1, lastCell.row),+ Math.min(cell.col + 1, lastCell.col),+ ),+ );++ return start && next ? { start, next } : undefined;+ },+ cells: (input) => {+ const cells = read(required(), input.sheet, input.range);+ const range = input.range;++ return Array.from({ length: range.bottom - range.top + 1 }, (_, row) =>+ Array.from(+ { length: range.right - range.left + 1 },+ (_, col) => cells?.[row]?.[col]?.displayText ?? "",+ ),+ );+ },+ // Copies the cells as they show, which is what a reader expects to paste, not the formulas behind them.+ copy: (input) => {+ const cells = read(required(), input.sheet, input.range);++ if (!cells) return undefined;++ return toTsv(+ cells.map((row) =>+ row.map((cell) => ({ input: cell.displayText, isFormula: literal(cell) })),+ ),+ );+ },+});++function required() {+ if (!state.opened) throw new Error("The worker holds no workbook");++ return state.opened;+}++/** The workbook with `sheet` active, as a frame from a grid that has since given way to another sheet may ask. */+function active(sheet: number) {+ const opened = required();++ if (opened.info.activeSheet !== sheet) show(opened, sheet);++ return opened;+}++/** Makes a sheet the active one and reads what its grid needs. */+function show(opened: Opened, sheet: number): SheetLayout {+ opened.workbook.setActiveSheet(sheet);+ opened.info = opened.workbook.sheetInfo();++ return { info: opened.info, ...layout(opened.workbook, sheet) };+}++/**+ * The used range, the merged cells, the hidden rows and columns, and how far the charts reach, from one export of the+ * sheet's metadata. One cell is enough: the lists before the cells are complete however soon the export stops.+ */+function layout(workbook: WorkbookHandle, sheet: number) {+ const result = attempt(() =>+ workbook.exportStructured({+ scope: [{ sheet, range: "A1:XFD1048576" }],+ maxCells: 1,+ includeDefinedNames: false,+ }),+ );++ const exported = result?.ok ? result.content.sheets[0] : undefined;++ const charts = (exported?.objects ?? [])+ .filter((object) => object.kind === "chart" && !object.hidden)+ .flatMap((object) => (object.anchor ? anchorRange(object.anchor) : []))+ // The corner cell holds the chart's edge somewhere inside it, so the cell past it bounds the chart.+ .flatMap((range) => {+ const corner = attempt(() =>+ workbook.cellPosition(+ sheet,+ Math.min(range.bottom + 1, lastCell.row),+ Math.min(range.right + 1, lastCell.col),+ ),+ );++ return corner ? [corner] : [];+ });++ return {+ used: exported?.usedRange ? parseRange(exported.usedRange) : undefined,+ merges: (exported?.merges ?? []).flatMap((merge) => anchorRange(merge.anchor)),+ hidden: {+ rows: parseSpans(exported?.hiddenRows ?? [], "rows"),+ columns: parseSpans(exported?.hiddenColumns ?? [], "columns"),+ },+ chartWidth: Math.max(0, ...charts.map((corner) => corner.x)),+ chartHeight: Math.max(0, ...charts.map((corner) => corner.y)),+ };+}++/** Where the sheet's last cell ends, past the frozen panes. A viewport past it makes the engine throw. */+function end(+ opened: Opened,+ sheet: number,+ frozen: { readonly width: number; readonly height: number },+) {+ const key = `${sheet}:${frozen.width}:${frozen.height}`;++ if (opened.ends.has(key)) return opened.ends.get(key);++ const measured = measureEnd(opened.workbook, sheet, frozen);++ opened.ends.set(key, measured);++ return measured;+}++function measureEnd(+ workbook: WorkbookHandle,+ sheet: number,+ frozen: { readonly width: number; readonly height: number },+) {+ const last = attempt(() => workbook.cellPosition(sheet, lastCell.row, lastCell.col));++ if (!last) return undefined;++ // A viewport one pixel past the frozen panes, on the last cell, reports where that cell ends.+ const grid = attempt(+ () =>+ workbook.displayList({+ x: last.x,+ y: last.y,+ width: frozen.width + 1,+ height: frozen.height + 1,+ }).grid,+ );++ // The engine works in single precision there, so stay a little short of the edge.+ const margin = 2;++ return {+ x:+ last.x ++ Math.max(0, (grid ? (grid.colOffsets[grid.colOffsets.length - 1] ?? 0) : 0) - frozen.width) -+ margin,+ y:+ last.y ++ Math.max(0, (grid ? (grid.rowOffsets[grid.rowOffsets.length - 1] ?? 0) : 0) - frozen.height) -+ margin,+ };+}++/** The cells of a range on a sheet as the engine reads them, row by row; undefined when it cannot. */+function read(opened: Opened, sheet: number, range: CellRange) {+ if ((range.bottom - range.top + 1) * (range.right - range.left + 1) > 200_000) return undefined;+ const target: XlsxRangeTarget = {+ sheetId: opened.info.sheetIds[sheet]!,+ range: {+ kind: "rowCol",+ start: { row: range.top, col: range.left },+ end: { row: range.bottom, col: range.right },+ },+ };++ const result = attempt(() => opened.workbook.readCells({ ranges: [target] }));++ return result?.ok ? result.ranges[0]?.cells : undefined;+}++/** The workbook's sheets but its hidden and very hidden ones, which Excel lists only to unhide. */+function visibleTabs(workbook: WorkbookHandle, info: SheetInfo): SheetTab[] {+ const names = info.sheetNames;++ const result = attempt(() =>+ workbook.exportStructured({+ includeHiddenSheets: true,+ includeDefinedNames: false,+ scope: names.map((_, sheet) => ({ sheet, range: "A1" })),+ }),+ );++ const hidden = new Set(+ (result?.ok ? result.content.sheets : [])+ .filter((sheet) => sheet.visibility === "hidden" || sheet.visibility === "veryHidden")+ .flatMap((sheet) => (sheet.anchor.kind === "sheet" ? [sheet.anchor.sheet.index] : [])),+ );++ return names.flatMap((name, index) => (hidden.has(index) ? [] : [{ index, name }]));+}++/**+ * Whether a cell's text pastes as it is. `toTsv` quotes text that a spreadsheet would read as a formula; a number shown+ * with a sign, such as "-12.50", is safe, and quoting it would paste text instead of the number.+ */+function literal(cell: XlsxCellRead) {+ return (+ cell.value.kind === "number" && /^[-+][\d\s.,%\p{Sc}]+(?:e[-+]\d+)?$/iu.test(cell.displayText)+ );+}diff --git a/apps/web/src/components/files/office/word-images.ts b/apps/web/src/components/files/office/word-images.tsnew file mode 100644index 00000000000..d6a7fe0daf3--- /dev/null+++ b/apps/web/src/components/files/office/word-images.ts@@ -0,0 +1,107 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import type { ImageResolver } from "@betteroffice/docx/layout/render";+import type { YrsMediaSource } from "@betteroffice/docx/yrs";+import { officeImageBitmap } from "./image-bitmap";++/** An embedded image's source, which names a part of the package the session reads. */+const mediaToken = /^media:(0|[1-9]\d*)$/u;++/** How many bytes of decoded images stay for repaints; the least recently drawn go first past it. */+const budget = 256 * 1024 * 1024;++type Decoded = {+ readonly image: Promise<CanvasImageSource | null>;+ /** The decoded image once it is one; the shared placeholder is never closed. */+ bitmap: ImageBitmap | undefined;+};++/**+ * Resolves the display list's images in a worker, where there is no `Image` element: a `media:{n}` source decodes+ * from the bytes the session reads, and a `data:` or `blob:` source decodes in place. Anything else, such as a remote+ * address, resolves to nothing, so painting never makes a request. A part that is missing or cannot be decoded paints a+ * grey box, as the window's resolver does. Decoded images stay for repaints within `budget`.+ */+export function createBitmapImageResolver(media: (token: string) => YrsMediaSource | null) {+ const cache = new Map<string, Decoded>();+ const placeholder = greyBox();++ const decode = (source: string): Promise<CanvasImageSource | null> => {+ const token = mediaToken.test(source);+ const found = token ? media(source) : undefined;++ if (token && !found) return Promise.resolve(placeholder);++ const blob = found+ ? Promise.resolve(new Blob([new Uint8Array(found.bytes)], { type: found.mimeType }))+ : fetch(source).then((response) => response.blob());++ return blob.then(officeImageBitmap).then(+ (bitmap): CanvasImageSource => bitmap,+ () => (token ? placeholder : null),+ );+ };++ const resolve: ImageResolver = (source) => {+ if (!mediaToken.test(source) && !source.startsWith("blob:") && !source.startsWith("data:"))+ return null;++ const cached = cache.get(source);++ if (cached) {+ // Map order is drawing order: the least recently drawn come first.+ cache.delete(source);+ cache.set(source, cached);++ return cached.image;+ }++ const entry: Decoded = {+ image: decode(source).then((image) => {+ if (image instanceof ImageBitmap) entry.bitmap = image;++ return image;+ }),+ bitmap: undefined,+ };++ cache.set(source, entry);++ return entry.image;+ };++ return {+ resolve,+ /** Closes the least recently drawn images past the budget. Call it between paints, never during one. */+ trim() {+ const size = (entry: Decoded) =>+ entry.bitmap ? entry.bitmap.width * entry.bitmap.height * 4 : 0;++ [...cache].reduce(+ (total, [source, entry]) => {+ if (total <= budget || !entry.bitmap) return total;++ const freed = size(entry);++ entry.bitmap.close();+ cache.delete(source);++ return total - freed;+ },+ [...cache.values()].reduce((total, entry) => total + size(entry), 0),+ );+ },+ };+}++/** The grey box a missing image paints: one pixel the painter stretches over the image's place. */+function greyBox() {+ const canvas = new OffscreenCanvas(1, 1);+ const context = canvas.getContext("2d");++ if (!context) return null;++ context.fillStyle = "#e6e6e6";+ context.fillRect(0, 0, 1, 1);++ return canvas;+}diff --git a/apps/web/src/components/files/office/word-protocol.ts b/apps/web/src/components/files/office/word-protocol.tsnew file mode 100644index 00000000000..716716d10a1--- /dev/null+++ b/apps/web/src/components/files/office/word-protocol.ts@@ -0,0 +1,87 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import type { Method } from "./worker-rpc";++// What the Word preview's window and its document worker say to each other. The window keeps only the page column, the+// text layer's DOM and the painted bitmaps; the engine, its fonts, the layout and the painting live in the worker.++/** Where a link in the document leads. */+export type WordLink =+ /** A web or mail address the system browser opens. */+ | { readonly kind: "external"; readonly url: string }+ /** A bookmark in the same document, such as a table of contents entry's heading. */+ | { readonly kind: "internal"; readonly bookmark: string };++/**+ * One transparent piece of the text layer, in units that scale with the page: positions are fractions of the page and+ * lengths are ems of `size`, so the layer follows any page width without being rebuilt.+ */+export type WordSpan = {+ readonly text: string;+ /** Left and top edges, as fractions of the page's width and height. */+ readonly left: number;+ readonly top: number;+ /** The font size, as a fraction of the page's width. */+ readonly size: number;+ /** Stretches the layer font's natural width to the painted glyphs' width, about the left edge. */+ readonly transform: string;+ readonly dir: "ltr" | "rtl";+ readonly link: WordLink | undefined;+ readonly title: string | undefined;+ /**+ * What separates it from the next span in copied text: a line break between paragraphs, table cells and regions, a+ * tab across a gap with no painted space, such as a tab stop or after a list number.+ */+ readonly after: "br" | "tab" | undefined;+};++/** What the page column needs to lay a page out before its content is built. */+export type WordPageSize = {+ readonly width: number;+ readonly height: number;+ readonly background: string | undefined;+};++/** The layer's line height, in ems: the height a painted line's glyph box takes, descenders included. */+export const lineHeight = 1.2;++/** The family the text layer measures and sets its text in; it stays transparent, so only its widths matter. */+export const layerFont = "sans-serif";++/** One step of the rest of the layout. */+export type WordLayoutStep =+ /** More of the document is left to lay out. */+ | { readonly done: false }+ /**+ * The whole document is laid out. `kept` tells, per page, whether the page is the one shown so far, so its row and+ * bitmap can stay; a page the full layout changed paints again.+ */+ | {+ readonly done: true;+ readonly pages: readonly WordPageSize[];+ readonly kept: readonly boolean[];+ };++/** The document worker's methods. Every method but `open` needs a document `open` opened. */+export type WordMethods = {+ /** Opens the file's bytes and lays out its first pages; the reply lists them and whether more follow. */+ readonly open: Method<+ { readonly bytes: ArrayBuffer },+ { readonly pages: readonly WordPageSize[]; readonly loading: boolean }+ >;+ /** Lays out a short step more of the document. */+ readonly layout: Method<undefined, WordLayoutStep>;+ /** Paints a page at `scale` page pixels per CSS pixel times `ratio` device pixels per CSS pixel. */+ readonly paint: Method<+ { readonly index: number; readonly scale: number; readonly ratio: number },+ ImageBitmap | undefined+ >;+ /** Builds a page's content ahead of its paint. */+ readonly build: Method<{ readonly index: number }, undefined>;+ /** A page's text layer. */+ readonly text: Method<{ readonly index: number }, readonly WordSpan[]>;+ /** Where a bookmark sits in the pages laid out so far: its page and the height on it, in page pixels. */+ readonly bookmark: Method<+ { readonly name: string },+ { readonly index: number; readonly y: number } | undefined+ >;+};diff --git a/apps/web/src/components/files/office/word-text.ts b/apps/web/src/components/files/office/word-text.tsnew file mode 100644index 00000000000..127b7934478--- /dev/null+++ b/apps/web/src/components/files/office/word-text.ts@@ -0,0 +1,297 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+import {+ fontSizePxFromShorthand,+ glyphRunRect,+ textRunRect,+ type DisplayPage,+ type DisplayPrimitive,+ type GeoRect,+ type GlyphRunPrimitive,+ type TextRunPrimitive,+} from "@betteroffice/docx/layout/render";+import { wordLink } from "./links";+import { lineHeight, type WordSpan } from "./word-protocol";++/** Measures text in the layer's font. */+export type TextMeasure = {+ /** The natural width of `text` at a font size of 1. */+ readonly width: (text: string) => number;+ /** The font's ascent and descent, at a font size of 1. */+ readonly ascent: number;+ readonly descent: number;+};++/**+ * Builds a page's text layer from its display list: its header, body, notes and footer in reading order. Each glyph+ * run's text sits over its painted glyphs, merged with its neighbours on the line while their text runs on, so+ * selection, find and screen readers see whole words and lines.+ */+export function pageText(page: DisplayPage, measure: TextMeasure): WordSpan[] {+ const body = page.primitives.slice(+ Math.min(page.watermarkPrimitiveCount ?? 0, page.primitives.length),+ );+ const notes = (page.noteAreas ?? []).map((area) => area.primitives ?? []);++ return [page.header?.primitives ?? [], body, ...notes, page.footer?.primitives ?? []].flatMap(+ (region) => regionText(region, page, measure),+ );+}++/**+ * The page and height of the first body text at or after a document position, such as a bookmark's: the heading a+ * table of contents entry points to. Undefined when no text follows it. A page whose content is not built yet is+ * built through `build` only when its body reaches the position.+ */+export function positionTarget(+ pages: readonly DisplayPage[],+ position: number,+ build: (index: number) => DisplayPage | undefined,+) {+ for (const [index, listed] of pages.entries()) {+ const page = listed.unbuilt+ ? (listed.positionSpan?.[1] ?? -1) >= position+ ? build(index)+ : undefined+ : listed;+ const first =+ page && bodyAfter(page, position).toSorted((left, right) => left.start - right.start)[0];++ if (first) return { index, y: first.y };+ }++ return undefined;+}++function bodyAfter(page: DisplayPage, position: number) {+ return page.primitives.flatMap((primitive) => {+ const piece = toPiece(primitive);++ return piece?.start !== undefined && piece.start >= position+ ? [{ start: piece.start, y: piece.rect.y }]+ : [];+ });+}++type Piece = {+ readonly text: string;+ readonly rect: GeoRect;+ readonly baseline: number;+ readonly size: number;+ readonly dir: "ltr" | "rtl";+ readonly href: string | undefined;+ readonly title: string | undefined;+ readonly rotation: number;+ readonly line: string;+ /** A list item's number or bullet, which Word follows with a tab. */+ readonly marker: boolean;+ readonly start: number | undefined;+ readonly end: number | undefined;+};++function regionText(+ primitives: readonly DisplayPrimitive[],+ page: DisplayPage,+ measure: TextMeasure,+): WordSpan[] {+ const lines = primitives+ .flatMap((primitive) => {+ const piece = toPiece(primitive);++ return piece ? [piece] : [];+ })+ .reduce<Piece[][]>((groups, piece) => {+ const line = groups.at(-1);+ const first = line?.[0];++ if (+ line &&+ first &&+ first.line === piece.line &&+ Math.abs(first.baseline - piece.baseline) < first.size * 0.6+ ) {+ line.push(piece);++ return groups;+ }++ groups.push([piece]);++ return groups;+ }, [])+ .map((line) => mergeLine(logical(line)));++ return lines.flatMap((line, index) => {+ const next = lines[index + 1]?.[0];+ const last = line.at(-1);+ // A line that wraps inside its paragraph runs on into the next: copied text joins them as one paragraph.+ const wraps = !!next && last?.end !== undefined && next.start === last.end;++ return line.map((piece, at) => {+ const following = line[at + 1];++ if (!following) return toSpan(piece, page, measure, wraps ? undefined : "br");++ return toSpan(piece, page, measure, separated(piece, following) ? "tab" : undefined);+ });+ });+}++/** Neighbours on a line with a gap between them and no space on either side of it read as separate words. */+function separated(previous: Piece, next: Piece) {+ if (/\s$/u.test(previous.text) || /^\s/u.test(next.text)) return false;++ // A number's painted width runs up to its text, over the tab between them.+ if (previous.marker) return true;++ const gap = Math.max(+ next.rect.x - (previous.rect.x + previous.rect.w),+ previous.rect.x - (next.rect.x + next.rect.w),+ );++ return gap > next.size * 0.35;+}++function toPiece(primitive: DisplayPrimitive): Piece | undefined {+ if (primitive.kind === "glyphRun") return glyphPiece(primitive);++ if (primitive.kind === "text") return textPiece(primitive);++ return undefined;+}++function glyphPiece(primitive: GlyphRunPrimitive): Piece | undefined {+ if (!primitive.text || primitive.glyphs.length === 0 || primitive.decorative) return undefined;++ // Marks sit off the baseline with no advance; the first glyph that advances sits on it.+ const base = primitive.glyphs.find((glyph) => glyph.advance) ?? primitive.glyphs[0];++ return {+ ...common(primitive),+ text: primitive.text,+ rect: glyphRunRect(primitive),+ baseline: base?.y ?? 0,+ size: primitive.size,+ };+}++function textPiece(primitive: TextRunPrimitive): Piece | undefined {+ if (!primitive.text || primitive.decorative) return undefined;++ return {+ ...common(primitive),+ text: primitive.text,+ rect: textRunRect(primitive),+ baseline: primitive.baselineY,+ size: fontSizePxFromShorthand(primitive.font),+ };+}++function common(primitive: GlyphRunPrimitive | TextRunPrimitive) {+ const link = wordLink(primitive.href);++ return {+ dir:+ primitive.rtl || (primitive.bidiLevel ?? 0) % 2 === 1 ? ("rtl" as const) : ("ltr" as const),+ href: link ? primitive.href : undefined,+ title:+ primitive.linkTitle ??+ primitive.tooltip ??+ (link?.kind === "external" ? link.url : undefined),+ rotation: primitive.rotationDeg ?? 0,+ line: `${primitive.lineIndex ?? ""}|${primitive.cell?.cellId ?? `${primitive.cell?.row ?? ""},${primitive.cell?.col ?? ""}`}`,+ marker: primitive.listMarker ?? false,+ start: primitive.docStart,+ end: primitive.docEnd,+ };+}++/** A line paints right-to-left runs in visual order; document positions restore the order they are read in. */+function logical(line: Piece[]) {+ if (line.some((piece) => piece.start === undefined)) return line;++ return line.toSorted((left, right) => (left.start ?? 0) - (right.start ?? 0));+}++/**+ * Joins pieces whose text runs on: same link, direction and size, next in the document and touching on the page. A wide+ * gap, such as a tab or a justified space, starts a new span, so each span's text stays close to its glyphs.+ */+function mergeLine(line: Piece[]) {+ return line.reduce<Piece[]>((merged, piece) => {+ const previous = merged.at(-1);++ if (!previous || !joins(previous, piece)) {+ merged.push(piece);++ return merged;+ }++ const left = Math.min(previous.rect.x, piece.rect.x);+ const right = Math.max(previous.rect.x + previous.rect.w, piece.rect.x + piece.rect.w);++ merged[merged.length - 1] = {+ ...previous,+ text: previous.text + piece.text,+ rect: { ...previous.rect, x: left, w: right - left },+ end: piece.end,+ };++ return merged;+ }, []);+}++function joins(previous: Piece, piece: Piece) {+ if (previous.marker || piece.marker) return false;++ if (previous.href !== piece.href || previous.dir !== piece.dir || previous.title !== piece.title)+ return false;++ if (+ previous.rotation !== 0 ||+ piece.rotation !== 0 ||+ Math.abs(previous.size - piece.size) > 0.01+ )+ return false;++ if (previous.end === undefined || previous.end !== piece.start) return false;++ const gap =+ piece.dir === "rtl"+ ? previous.rect.x - (piece.rect.x + piece.rect.w)+ : piece.rect.x - (previous.rect.x + previous.rect.w);++ return Math.abs(gap) < piece.size * 0.35;+}++function toSpan(+ piece: Piece,+ page: DisplayPage,+ measure: TextMeasure,+ after: WordSpan["after"],+): WordSpan {+ const natural = measure.width(piece.text);+ const stretch = natural > 0 && piece.rect.w > 0 ? piece.rect.w / (natural * piece.size) : 1;+ // The line box puts the baseline this many ems below its top.+ const above = (lineHeight + measure.ascent - measure.descent) / 2;+ const top = piece.baseline - piece.size * above;+ const width = piece.rect.w / piece.size;+ const middle = (piece.rect.y + piece.rect.h / 2 - top) / piece.size;++ // A rotated run turns about its painted box's centre; ems keep the turn in step with the page's scale.+ const rotation =+ piece.rotation === 0+ ? ""+ : `translate(${width / 2}em, ${middle}em) rotate(${piece.rotation}deg) translate(${-width / 2}em, ${-middle}em) `;++ return {+ text: piece.text,+ left: piece.rect.x / page.width,+ top: top / page.height,+ size: piece.size / page.width,+ transform: `${rotation}scaleX(${stretch})`,+ dir: piece.dir,+ link: wordLink(piece.href),+ title: piece.title,+ after,+ };+}diff --git a/apps/web/src/components/files/office/worker-rpc.ts b/apps/web/src/components/files/office/worker-rpc.tsnew file mode 100644index 00000000000..c5471cea87c--- /dev/null+++ b/apps/web/src/components/files/office/worker-rpc.ts@@ -0,0 +1,292 @@+// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.+// The engines run in a worker per open file, so no layout, recalculation or painting holds the window. These are the+// two ends of that worker's protocol: typed calls by method name, a key that lets a newer call replace a queued one+// (as the markdown worker's queue does), transferable payloads, and a worker that fails every pending call when it dies.++/** What one method takes and returns. */+export type Method<Input, Output> = { readonly input: Input; readonly output: Output };++/** A worker's methods by name. */+export type Methods = { readonly [name: string]: Method<unknown, unknown> };++type Request = {+ readonly id: number;+ readonly method: string;+ readonly key?: string | undefined;+ readonly input: unknown;+};++/** Withdraws a call whose caller aborted it. */+type Cancel = { readonly cancel: number };++type Response =+ /** `transferred` lists the objects the reply moved, so a reply nobody waits for can close its bitmaps. */+ | {+ readonly id: number;+ readonly ok: true;+ readonly value: unknown;+ readonly transferred: readonly Transferable[];+ }+ | {+ readonly id: number;+ readonly ok: false;+ readonly superseded: boolean;+ readonly message: string;+ };++/** A value a method returns with the buffers to move to the caller rather than copy. */+export class Transfer<T> {+ constructor(+ readonly value: T,+ readonly transfer: readonly Transferable[],+ ) {}+}++/** A call that a newer call with the same key replaced before it ran. */+export class SupersededError extends Error {}++/** A call made after the worker failed or was closed, or pending when that happened. */+class WorkerClosedError extends Error {}++type CallOptions = {+ /** A newer call with the same key replaces this one while it waits to run. */+ readonly key?: string;+ /** Buffers to move to the worker rather than copy, such as the file's bytes or a transferred canvas. */+ readonly transfer?: readonly Transferable[];+ /** Drops the reply and a call still queued; a call that has started sees its handler's signal abort. */+ readonly signal?: AbortSignal;+};++/** A call waiting for its reply. */+type Pending = {+ readonly settle: (response: Response) => void;+ readonly reject: (error: Error) => void;+};++/** The next call id, and why the worker stopped answering once it has. */+type ClientState = { next: number; failure: Error | undefined };++/** The window's end: starts the worker and calls its methods. */+export function createWorkerClient<M extends Methods>(worker: Worker) {+ const pending = new Map<number, Pending>();+ const state: ClientState = { next: 0, failure: undefined };++ const fail = (error: Error) => {+ state.failure ??= error;+ pending.forEach((call) => call.reject(error));+ pending.clear();+ worker.terminate();+ };++ worker.addEventListener("message", (event: MessageEvent<Response>) => {+ const call = pending.get(event.data.id);++ // A reply that crossed its call's cancel on the way: its bitmaps would hold their memory until collected.+ if (!call) {+ if (event.data.ok) closeBitmaps(event.data.transferred);++ return;+ }++ pending.delete(event.data.id);+ call.settle(event.data);+ });++ worker.addEventListener("error", (event) =>+ fail(new WorkerClosedError(event.message || "The Office engine stopped")),+ );+ worker.addEventListener("messageerror", () =>+ fail(new WorkerClosedError("The Office engine sent an unreadable reply")),+ );++ return {+ call<K extends keyof M & string>(+ method: K,+ input: M[K]["input"],+ options: CallOptions = {},+ ): Promise<M[K]["output"]> {+ if (state.failure) return Promise.reject(state.failure);++ if (options.signal?.aborted)+ return Promise.reject(new WorkerClosedError("The call was aborted"));++ const id = ++state.next;++ return new Promise<M[K]["output"]>((resolve, reject) => {+ const timeout = setTimeout(+ () =>+ fail(+ new WorkerClosedError(+ "This document took too long to preview. Open it in another app.",+ ),+ ),+ 30_000,+ );+ const abort = () => {+ clearTimeout(timeout);+ pending.delete(id);+ reject(new WorkerClosedError("The call was aborted"));+ worker.postMessage({ cancel: id } satisfies Cancel, []);+ };++ options.signal?.addEventListener("abort", abort, { once: true });+ pending.set(id, {+ settle: (response) => {+ clearTimeout(timeout);+ options.signal?.removeEventListener("abort", abort);++ if (!response.ok)+ return reject(+ response.superseded+ ? new SupersededError(response.message)+ : new Error(response.message),+ );++ // SAFETY: the worker answers each id with the output of the method that id called (see `serveWorker`).+ resolve(response.value as M[K]["output"]);+ },+ reject: (error) => {+ clearTimeout(timeout);+ options.signal?.removeEventListener("abort", abort);+ reject(error);+ },+ });+ worker.postMessage({ id, method, key: options.key, input } satisfies Request, [+ ...(options.transfer ?? []),+ ]);+ });+ },+ /** Stops the worker, which frees its engine's memory, and fails every pending call. */+ close() {+ fail(new WorkerClosedError("The Office engine was closed"));+ },+ };+}++/** Whether a call runs, and which call it is, so its caller can abort it. */+type ServerState = {+ running: boolean;+ current: { readonly id: number; readonly controller: AbortController } | undefined;+};++/**+ * The worker's end: runs calls one at a time, in order, letting messages through between them. A handler's signal+ * aborts when its caller aborts the call.+ */+export function serveWorker<M extends Methods>(handlers: {+ readonly [K in keyof M]: (+ input: M[K]["input"],+ signal: AbortSignal,+ ) =>+ | M[K]["output"]+ | Transfer<M[K]["output"]>+ | Promise<M[K]["output"] | Transfer<M[K]["output"]>>;+}) {+ const queue: Request[] = [];++ const state: ServerState = { running: false, current: undefined };++ const reply = (response: Response, transfer: readonly Transferable[] = []) =>+ self.postMessage(response, { transfer: [...transfer] });++ const run = async () => {+ if (state.running) return;++ state.running = true;++ // Each call returns to the event loop before it leaves the queue, so calls that arrived meanwhile can replace it.+ while (queue.length > 0) {+ await new Promise((resolve) => setTimeout(resolve));++ const request = queue.shift();++ if (!request) break;++ const handler = handlers[request.method];+ const controller = new AbortController();++ state.current = { id: request.id, controller };++ if (!handler) {+ reply({+ id: request.id,+ ok: false,+ superseded: false,+ message: `Unknown method ${request.method}`,+ });+ continue;+ }++ // SAFETY: the client sends each method the input its `Methods` entry declares (see `createWorkerClient`).+ const input = request.input as never;++ await Promise.resolve()+ .then(() => handler(input, controller.signal))+ .then(+ (result) => {+ const transfer = result instanceof Transfer ? result.transfer : [];++ // The caller already settled a call it aborted, so nothing would take the reply or its bitmaps.+ if (controller.signal.aborted) return closeBitmaps(transfer);++ reply(+ {+ id: request.id,+ ok: true,+ value: result instanceof Transfer ? result.value : result,+ transferred: transfer,+ },+ transfer,+ );+ },+ (cause: unknown) => {+ if (controller.signal.aborted) return;++ reply({+ id: request.id,+ ok: false,+ superseded: false,+ message: cause instanceof Error ? cause.message : String(cause),+ });+ },+ );+ }++ state.running = false;+ state.current = undefined;+ };++ self.addEventListener("message", (event: MessageEvent<Request | Cancel>) => {+ // The caller already settled a cancelled call, so it gets no reply.+ if ("cancel" in event.data) {+ const id = event.data.cancel;+ const queued = queue.findIndex((request) => request.id === id);++ if (queued !== -1) queue.splice(queued, 1);++ if (state.current?.id === id) state.current.controller.abort();++ return;+ }++ const key = event.data.key;+ const replaced = key === undefined ? -1 : queue.findIndex((request) => request.key === key);++ if (replaced !== -1) {+ const [old] = queue.splice(replaced, 1);++ if (old)+ reply({ id: old.id, ok: false, superseded: true, message: "Replaced by a newer call" });+ }++ queue.push(event.data);+ void run();+ });+}++/** Frees the bitmaps among objects that were moved for a reply nobody takes. */+function closeBitmaps(transfer: readonly Transferable[]) {+ transfer.forEach((item) => {+ if (item instanceof ImageBitmap) item.close();+ });+}diff --git a/apps/web/src/components/files/officeArchive.ts b/apps/web/src/components/files/officeArchive.tsnew file mode 100644index 00000000000..8883fbd8b3c--- /dev/null+++ b/apps/web/src/components/files/officeArchive.ts@@ -0,0 +1,1190 @@+import JSZip from "jszip";+import { checkZipDirectory } from "./zipDirectory";+import { SaxesParser } from "saxes";+import { externalUrl } from "./office/links";++import {+ OFFICE_PREVIEW_MAX_BYTES,+ OFFICE_PREVIEW_MAX_COLUMNS,+ OFFICE_PREVIEW_MAX_ROWS,+ type OfficeWorkerRequest,+} from "./officePreviewProtocol";++function xmlParser() {+ const parser = new SaxesParser({ xmlns: true });+ parser.on("doctype", () => {+ throw new Error("This document contains unsupported XML declarations.");+ });+ return parser;+}++function officeXmlDecoder(bytes: Uint8Array) {+ if ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0x3c && bytes[1] === 0))+ return new TextDecoder("utf-16le");+ if ((bytes[0] === 0xfe && bytes[1] === 0xff) || (bytes[0] === 0 && bytes[1] === 0x3c))+ return new TextDecoder("utf-16be");+ const declaration = new TextDecoder().decode(bytes.subarray(0, 256));+ return new TextDecoder(/^<\?xml\s[^?]*\bencoding\s*=\s*["']([^"']+)["']/i.exec(declaration)?.[1]);+}++function officeXml(bytes: Uint8Array) {+ // Repacked XML is UTF-8, regardless of the source part's encoding.+ return officeXmlDecoder(bytes)+ .decode(bytes)+ .replace(/^(<\?xml\s[^?]*\bencoding\s*=\s*)["'][^"']+["']/i, '$1"UTF-8"');+}++// Section properties terminate the section they describe, so the kept prefix+// may depend on a paragraph or body section beyond the retained input window.+function wordSections() {+ const parser = xmlParser();+ const names: string[] = [];+ const namespaceScopes: Record<string, string>[] = [];+ const sections: { end: number; xml: string; body: boolean }[] = [];+ let window = "";+ let offset = 0;+ let capture: {+ start: number;+ insert: number;+ namespaces: string;+ body: boolean;+ depth: number;+ } | null = null;+ let bytes = 0;+ let tags = 0;+ let nextParagraph = false;+ let paragraphSection = false;+ const escape = (value: string) =>+ value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<");+ parser.on("opentag", (tag) => {+ names.push(tag.local);+ namespaceScopes.push(tag.ns);+ if (names.length > 64) throw new Error("This Word document has excessive XML nesting.");+ const body = names.length === 3 && names[1] === "body";+ if (+ tag.local === "sectPr" &&+ tag.uri === "http://schemas.openxmlformats.org/wordprocessingml/2006/main" &&+ (body || (names.length === 5 && names[2] === "p" && names[3] === "pPr" && !nextParagraph))+ ) {+ let namespaces = "";+ const scope = Object.assign({}, ...namespaceScopes) as Record<string, string>;+ for (const prefix in scope) {+ const name = prefix ? `xmlns:${prefix}` : "xmlns";+ if (prefix !== "xml" && !tag.attributes[name])+ namespaces += ` ${name}="${escape(scope[prefix]!)}"`;+ }+ const start = window.lastIndexOf("<", parser.position - offset - 1);+ if (start < 0) throw new Error("This Word document has too much section markup.");+ capture = {+ start: start + offset,+ insert: parser.position - (tag.isSelfClosing ? 2 : 1),+ namespaces,+ body,+ depth: names.length,+ };+ }+ if (capture && ++tags > 2_000)+ throw new Error("Preview limited: this Word document has too much section markup.");+ });+ parser.on("closetag", (tag) => {+ if (capture && tag.local === "sectPr" && names.length === capture.depth) {+ const xml =+ window.slice(capture.start - offset, capture.insert - offset) ++ capture.namespaces ++ window.slice(capture.insert - offset, parser.position - offset);+ bytes += xml.length;+ if (bytes > 128 * 1024)+ throw new Error("Preview limited: this Word document has too much section markup.");+ sections.push({ end: parser.position, xml, body: capture.body });+ paragraphSection = !capture.body;+ if (!capture.body && parser.position > 4 * 1024 * 1024) nextParagraph = true;+ capture = null;+ }+ if (names.length === 3 && tag.local === "p" && paragraphSection) {+ sections[sections.length - 1]!.end = parser.position;+ paragraphSection = false;+ }+ names.pop();+ namespaceScopes.pop();+ });+ return {+ write(chunk: string) {+ window += chunk;+ parser.write(chunk);+ if (capture && parser.position - capture.start > 128 * 1024)+ throw new Error("Preview limited: this Word document has too much section markup.");+ const keep = capture?.start ?? Math.max(offset, parser.position - 128 * 1024);+ window = window.slice(keep - offset);+ offset = keep;+ },+ finish() {+ parser.close();+ return sections;+ },+ };+}++// Keep whole body elements so every prefix and render batch is valid Word XML.+// Individual tables/paragraphs are bounded too: one giant element must not+// bypass the budget between yields on the main thread.+function wordDocuments(+ xml: string,+ incomplete: boolean,+ sections: ReturnType<ReturnType<typeof wordSections>["finish"]>,+) {+ const parser = xmlParser();+ const names: string[] = [];+ const batches: { content: string; end: number }[] = [];+ let prefix = "";+ let suffix = "";+ let boundary = 0;+ let batchStart = 0;+ let tags = 0;+ let elementTags = 0;+ let batchTags = 0;+ let elements = 0;+ let truncated = incomplete;+ const limit = Symbol("Word preview limit");+ parser.on("opentag", (tag) => {+ names.push(tag.name);+ if (names.length === 2 && tag.local === "body") {+ prefix = xml.slice(0, parser.position).replace(/\/>$/, ">");+ suffix = `</${tag.name}></${names[0]}>`;+ boundary = batchStart = parser.position;+ } else if (prefix && names.length > 2) {+ if (names.length === 3 && ++elements > 5_000) throw limit;+ tags++;+ elementTags++;+ batchTags++;+ if (tags > 100_000 || elementTags > 2_000 || parser.position - boundary > 128 * 1024)+ throw limit;+ }+ if (names.length > 64) throw limit;+ });+ parser.on("closetag", (tag) => {+ if (prefix && names.length === 3 && tag.local !== "sectPr") {+ if (parser.position - prefix.length > 3 * 1024 * 1024) throw limit;+ boundary = parser.position;+ elementTags = 0;+ if (batchTags >= 500) {+ batches.push({ content: xml.slice(batchStart, boundary), end: boundary });+ batchStart = boundary;+ batchTags = 0;+ }+ }+ names.pop();+ });+ try {+ for (let offset = 0; offset < xml.length; offset += 16 * 1024) {+ parser.write(xml.slice(offset, offset + 16 * 1024));+ if (prefix && parser.position - boundary > 128 * 1024) throw limit;+ }+ if (!incomplete) parser.close();+ } catch (cause) {+ if (cause !== limit) throw cause;+ truncated = true;+ }+ if (!prefix) throw new Error("This Word document has no readable body.");+ if (boundary > batchStart || batches.length === 0)+ batches.push({ content: xml.slice(batchStart, boundary), end: boundary });+ const documents: string[] = [];+ let length = 0;+ let markup = 0;+ for (const batch of batches) {+ const section = sections.find((section) => section.body || section.end >= batch.end);+ const document = prefix + batch.content + (section?.xml ?? "") + suffix;+ length += batch.content.length;+ markup += batch.content.match(/<(?![!?/])/g)?.length ?? 0;+ if (length > 3 * 1024 * 1024 || markup > 100_000) {+ truncated = true;+ break;+ }+ documents.push(document);+ }+ if (documents.length === 0) throw new Error("This Word document has too much section markup.");+ return { documents, truncated };+}++function boundedWorksheet(xml: string, strings: readonly string[], budget: { remaining: number }) {+ const parser = xmlParser();+ const rows = new Map<number, Map<number, string>>();+ const rowTags = new Map<number, string>();+ const metadataAttributes = new Map<+ string,+ { ref: string | undefined; min: string | undefined; max: string | undefined }+ >();+ let dataStart = 0;+ let dataEnd = 0;+ let emptyData = false;+ let depth = 0;+ let row = 0;+ let explicitRow = false;+ let rowTag = "";+ let column = 0;+ let cells = new Map<number, string>();+ let cell: {+ start: number;+ opening: string;+ name: string;+ prefix: string;+ selfClosing: boolean;+ text: string;+ value: string;+ reading: string;+ shared: boolean;+ } | null = null;+ let truncated = false;+ const coordinate = (ref: string) => {+ const match = /^([A-Z]{1,3})([1-9]\d{0,6})$/.exec(ref);+ if (!match) throw new Error("This workbook contains invalid cell coordinates.");+ let col = 0;+ for (const letter of match[1]!) col = col * 26 + letter.charCodeAt(0) - 64;+ const line = Number(match[2]);+ if (col > 16384 || line > 1048576)+ throw new Error("This workbook contains invalid worksheet dimensions.");+ return { col, line };+ };+ parser.on("opentag", (tag) => {+ depth++;+ if (depth > 64) throw new Error("This workbook contains excessive XML nesting.");+ if (+ (tag.local === "row" && depth !== 3) ||+ (tag.local === "c" && depth !== 4) ||+ ((tag.local === "dimension" || tag.local === "sheetData") && depth !== 2)+ )+ throw new Error("This workbook contains invalid worksheet structure.");+ const attribute = (name: string) => tag.attributes[name]?.value;+ if (["dimension", "mergeCell", "col"].includes(tag.local))+ metadataAttributes.set(+ xml.slice(xml.lastIndexOf("<", parser.position - 1), parser.position),+ {+ ref: attribute("ref"),+ min: attribute("min"),+ max: attribute("max"),+ },+ );+ if (depth === 2 && tag.local === "sheetData") {+ dataStart = parser.position;+ emptyData = tag.isSelfClosing;+ }+ if (depth === 2 && tag.local === "dimension") {+ for (const ref of (attribute("ref") ?? "").split(":")) {+ const { col, line } = coordinate(ref);+ if (col > OFFICE_PREVIEW_MAX_COLUMNS || line > OFFICE_PREVIEW_MAX_ROWS) truncated = true;+ }+ } else if (depth === 3 && tag.local === "row") {+ explicitRow = attribute("r") !== undefined;+ row = attribute("r") === undefined ? row + 1 : Number(attribute("r"));+ if (!Number.isInteger(row) || row < 1 || row > 1048576)+ throw new Error("This workbook contains invalid row coordinates.");+ rowTag = xml+ .slice(xml.lastIndexOf("<", parser.position - 1), parser.position)+ .replace(/\/>$/, ">");+ column = 0;+ cells = rows.get(row) ?? new Map<number, string>();+ if (row > OFFICE_PREVIEW_MAX_ROWS) truncated = true;+ } else if (depth === 4 && tag.local === "c") {+ const ref = attribute("r");+ const position = ref ? coordinate(ref) : { col: column + 1, line: row };+ if (!explicitRow && column === 0) row = position.line;+ column = position.col;+ if (row < 1 || position.line !== row)+ throw new Error("This workbook contains inconsistent cell rows.");+ if (row > OFFICE_PREVIEW_MAX_ROWS || column > OFFICE_PREVIEW_MAX_COLUMNS) {+ truncated = true;+ return;+ }+ // Explicit coordinates also bound sheets whose rows/cells omit r.+ const letters =+ column <= 26 ? String.fromCharCode(64 + column) : `A${String.fromCharCode(38 + column)}`;+ const style = attribute("s");+ const type = attribute("t");+ if ((style && !/^\d{1,6}$/.test(style)) || (type && !/^[a-zA-Z]+$/.test(type)))+ throw new Error("This workbook contains invalid cell metadata.");+ cell = {+ start: parser.position,+ opening: xml+ .slice(xml.lastIndexOf("<", parser.position - 1), parser.position)+ .replace(/\/?>$/, `${ref ? "" : ` r="${letters}${row}"`}>`),+ name: tag.name,+ prefix: tag.prefix ? `${tag.prefix}:` : "",+ selfClosing: tag.isSelfClosing,+ text: "",+ value: "",+ reading: "",+ shared: type === "s",+ };+ }+ if (cell && (tag.local === "t" || tag.local === "v")) cell.reading = tag.local;+ });+ const readCellText = (chunk: string) => {+ if (cell?.reading === "t") cell.text += chunk;+ if (cell?.reading === "v") cell.value += chunk;+ };+ parser.on("text", readCellText);+ parser.on("cdata", readCellText);+ parser.on("closetag", (tag) => {+ if (depth === 4 && tag.local === "c" && cell) {+ const end = cell.selfClosing ? cell.start : xml.lastIndexOf("<", parser.position - 1);+ const raw = cell.opening + xml.slice(cell.start, end) + `</${cell.name}>`;+ const shown = cell.shared ? (strings[Number(cell.value)] ?? "") : cell.text || cell.value;+ const kept = shown.slice(0, Math.min(4096, budget.remaining));+ budget.remaining -= kept.length;+ if (kept.length < shown.length) {+ truncated = true;+ const escape = (s: string) =>+ s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");+ cells.set(+ column,+ cell.opening+ .replace(/\s+t\s*=\s*(?:"[^"]*"|'[^']*')/, "")+ .replace(/>$/, ' t="inlineStr">') ++ `<${cell.prefix}is><${cell.prefix}t>` ++ escape(kept) ++ `</${cell.prefix}t></${cell.prefix}is></${cell.name}>`,+ );+ } else cells.set(column, raw);+ cell = null;+ } else if (depth === 3 && tag.local === "row" && row <= OFFICE_PREVIEW_MAX_ROWS) {+ rows.set(row, cells);+ rowTags.set(row, rowTag);+ }+ if (depth === 2 && tag.local === "sheetData")+ dataEnd = emptyData ? parser.position : xml.lastIndexOf("<", parser.position - 1);+ if (cell?.reading === tag.local) cell.reading = "";+ depth--;+ });+ parser.write(xml).close();+ if (!dataStart) throw new Error("This workbook has no worksheet data.");+ const boundRange = (ref: string) => {+ const [a, b = a] = ref.split(":");+ const first = coordinate(a!);+ const last = coordinate(b!);+ if (first.col > 50 || first.line > 500) return "";+ const col = Math.min(50, last.col);+ const letters = col <= 26 ? String.fromCharCode(64 + col) : "A" + String.fromCharCode(38 + col);+ return a + ":" + letters + Math.min(500, last.line);+ };+ const metadata = (part: string) =>+ part.replace(+ /(<((?:\w+:)?(?:dimension|mergeCell|col))\b(?:[^"'<>]|"[^"]*"|'[^']*')*>)(?:\s*<\/\2\s*>)?/g,+ (tag: string, opening: string) => {+ const attributes = metadataAttributes.get(opening);+ if (!attributes) return tag;+ const replace = (name: string, value: string) => {+ const pattern = new RegExp(`\\s${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`);+ tag = pattern.test(tag)+ ? tag.replace(pattern, ` ${name}="${value}"`)+ : tag.replace(/\/?>/, (end) => ` ${name}="${value}"${end}`);+ };+ if (attributes.ref !== undefined) {+ const bounded = boundRange(attributes.ref);+ if (!bounded) return "";+ replace("ref", bounded);+ }+ if (/<(?:\w+:)?col\b/.test(opening)) {+ const min = Math.max(1, Number(attributes.min ?? 1));+ const max = Math.min(OFFICE_PREVIEW_MAX_COLUMNS, Number(attributes.max ?? 16384));+ if (!Number.isInteger(min) || !Number.isInteger(max) || min > max) return "";+ replace("min", String(min));+ replace("max", String(max));+ }+ return tag;+ },+ );+ return {+ xml: emptyData+ ? metadata(xml)+ : `${metadata(xml.slice(0, dataStart))}${[...rows]+ .sort(([a], [b]) => a - b)+ .map(+ ([line, values]) =>+ `${rowTags.get(line) ?? `<row r="${line}">`}${[...values]+ .sort(([a], [b]) => a - b)+ .map(([, value]) => value)+ .join("")}</${/^<([^\s>]+)/.exec(rowTags.get(line) ?? "<row>")![1]}>`,+ )+ .join("")}${metadata(xml.slice(dataEnd))}`,+ truncated,+ };+}++async function boundWorkbook(archive: JSZip) {+ const paths = new Map<string, string>();+ let sharedPath = "xl/sharedStrings.xml";+ const relationships = xmlParser();+ relationships.on("opentag", (tag) => {+ if (tag.local !== "Relationship") return;+ const type = tag.attributes.Type?.value;+ const path = new URL(+ tag.attributes.Target?.value ?? "",+ "https://docx.invalid/xl/workbook.xml",+ ).pathname.slice(1);+ if (type?.endsWith("/worksheet")) paths.set(tag.attributes.Id?.value ?? "", path);+ if (type?.endsWith("/sharedStrings")) sharedPath = path;+ });+ relationships+ .write((await archive.file("xl/_rels/workbook.xml.rels")?.async("string")) ?? "")+ .close();+ const sheetPaths: string[] = [];+ const workbook = xmlParser();+ workbook.on("opentag", (tag) => {+ if (tag.local !== "sheet") return;+ const id = Object.values(tag.attributes).find((attribute) => attribute.local === "id")?.value;+ const path = paths.get(id ?? "");+ if (!path || sheetPaths.length === 100)+ throw new Error("This workbook has invalid or too many sheets.");+ sheetPaths.push(path);+ });+ workbook.write((await archive.file("xl/workbook.xml")?.async("string")) ?? "").close();+ const strings: string[] = [];+ const shared = await archive.file(sharedPath)?.async("string");+ if (shared) {+ const parser = xmlParser();+ let text = "";+ let reading = false;+ parser.on("opentag", (tag) => {+ if (tag.local === "si") text = "";+ if (tag.local === "t") reading = true;+ });+ const readSharedText = (chunk: string) => {+ if (reading) text += chunk;+ };+ parser.on("text", readSharedText);+ parser.on("cdata", readSharedText);+ parser.on("closetag", (tag) => {+ if (tag.local === "t") reading = false;+ if (tag.local === "si") strings.push(text);+ });+ parser.write(shared).close();+ }+ const budget = { remaining: 1024 * 1024 };+ const limited = new Map<string, boolean>();+ for (const path of new Set(sheetPaths)) {+ const file = archive.file(path);+ if (!file) throw new Error("This workbook has a missing worksheet.");+ const sheet = boundedWorksheet(await file.async("string"), strings, budget);+ archive.file(path, sheet.xml);+ limited.set(path, sheet.truncated);+ }+ return sheetPaths.map((path) => limited.get(path) ?? false);+}++const WORD_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";+const WORD_EXPANDED_PARTS = new Set(["footnotes", "endnotes", "comments", "header", "footer"]);+const WORD_DISABLED_PARTS = new Set(["commentsExtended", "fontTable", "aFChunk"]);+const WORD_BINARY_PARTS = new Set([+ "image",+ "font",+ "thumbnail",+ "audio",+ "video",+ "oleObject",+ "package",+ "printerSettings",+ "vbaProject",+ "origin",+ "certificate",+ // Package metadata can point to binary payloads; explicit XML still wins below.+ "core-properties",+ "extended-properties",+ "custom-properties",+ "signature",+]);++function wordPartTypes() {+ const defaults = new Map<string, string>();+ const overrides = new Map<string, string>();+ const xmlParts = new Set([+ "word/document.xml",+ "docProps/app.xml",+ "docProps/core.xml",+ "docProps/custom.xml",+ ]);+ const roles = new Map<string, Set<string>>();+ const relationships = new Map<string, Map<string, string>>();+ return {+ roles,+ relationships,+ binary(path: string) {+ const extension = path.split(".").at(-1)?.toLowerCase() ?? "";+ const type = overrides.get(path) ?? defaults.get(extension) ?? "";+ // An XML relationship always wins over a misleading media content type.+ if (+ path === "[Content_Types].xml" ||+ extension === "rels" ||+ extension === "xml" ||+ xmlParts.has(path) ||+ /(?:\+xml|\/xml)$/i.test(type)+ )+ return false;+ return (+ [...(roles.get(path) ?? [])].some((role) => WORD_BINARY_PARTS.has(role)) ||+ /^(?:image|audio|video|font)\//i.test(type) ||+ /^(?:png|jpe?g|gif|webp|bmp|tiff?|ico|bin|sigs|cer|ttf|otf|odttf|woff2?)$/.test(+ extension,+ ) ||+ type === "application/octet-stream" ||+ type === "application/vnd.openxmlformats-package.digital-signature-origin"+ );+ },+ metadata(path: string, xml: string) {+ const parser = xmlParser();+ const removed: { start: number; end: number }[] = [];+ let start = -1;+ parser.on("opentag", (tag) => {+ const attr = (name: string) => tag.attributes[name]?.value ?? "";+ if (path === "[Content_Types].xml") {+ if (tag.local === "Default")+ defaults.set(attr("Extension").toLowerCase(), attr("ContentType"));+ if (tag.local === "Override")+ overrides.set(attr("PartName").replace(/^\//, ""), attr("ContentType"));+ }+ if (tag.local !== "Relationship" || !path.endsWith(".rels")) return;+ const type = attr("Type");+ const role = type.slice(type.lastIndexOf("/") + 1);+ const external =+ attr("TargetMode").toLowerCase() === "external" ||+ /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(attr("Target"));+ const folder = path === "_rels/.rels" ? "" : path.replace(/_rels\/[^/]+\.rels$/, "");+ // Preserve archive URL resolution, including literal query/fragment+ // characters in ZIP names rather than silently classifying another file.+ const target = new URL(attr("Target"), `https://docx.invalid/${folder}`)+ .toString()+ .slice("https://docx.invalid/".length);+ if (!external) {+ if (+ !WORD_BINARY_PARTS.has(role) &&+ role !== "hyperlink" &&+ (type.startsWith(WORD_RELATIONSHIP) ||+ role === "core-properties" ||+ role === "signature")+ )+ xmlParts.add(target);+ const types = roles.get(target) ?? new Set<string>();+ types.add(role);+ roles.set(target, types);+ const owner = path === "_rels/.rels" ? "" : path.replace(/_rels\/([^/]+)\.rels$/, "$1");+ const refs = relationships.get(owner) ?? new Map<string, string>();+ if (!refs.has(attr("Id"))) refs.set(attr("Id"), target);+ relationships.set(owner, refs);+ if (target === "word/document.xml" && role !== "officeDocument")+ throw new Error("Preview limited: this Word document has an aliased document part.");+ if (type === WORD_RELATIONSHIP + "officeDocument" && target !== "word/document.xml")+ throw new Error(+ "Preview limited: this Word document has an unsupported document relationship.",+ );+ }+ if (+ (external && !(role === "hyperlink" && externalUrl(attr("Target")))) ||+ WORD_DISABLED_PARTS.has(role)+ ) {+ start = xml.lastIndexOf("<", parser.position - 1);+ }+ });+ parser.on("closetag", (tag) => {+ if (tag.local === "Relationship" && start >= 0) {+ removed.push({ start, end: parser.position });+ start = -1;+ }+ });+ parser.write(xml).close();+ for (const range of removed.toReversed())+ xml = xml.slice(0, range.start) + xml.slice(range.end);+ return xml;+ },+ };+}++// Bound inherited style and numbering expansion before the engine loads it.+// Picture bullets can duplicate embedded images, so omit those definitions.+const WORD_STYLE_MAX_BYTES = 1024 * 1024;+const WORD_STYLE_MAX_UNITS = 20_000;++function wordXmlCost(xml: string, roles: Set<string> | undefined) {+ const parser = xmlParser();+ let depth = 0;+ let markup = 0;+ const limit = Symbol("Word style budget");+ const exceeded = { bytes: Infinity, markup: Infinity, pictures: false };+ let styleCount = 0;+ let ownUnits = 0;+ const styles = new Map<+ string,+ { properties: Map<string, number>; base: string; linked: string }+ >();+ let style: { id: string; base: string; linked: string; properties: Map<string, number> } | null =+ null;+ const names: string[] = [];+ const definitions = new Map<string, { bytes: number; markup: number }>();+ const references: { id: string; selector: number }[] = [];+ let definition: { id: string; start: number; markup: number } | null = null;+ let reference: { id: string; selector: number } | null = null;+ let pictures = false;+ parser.on("opentag", (tag) => {+ if (++depth > 64)+ throw new Error("Preview limited: this Word document has excessive XML nesting.");+ markup++;+ const attr = (name: string) =>+ Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";+ names.push(tag.local === "tblStylePr" ? `${tag.local}:${attr("type")}` : tag.local);+ if (roles?.has("styles") && (tag.local === "style" || tag.local === "docDefaults")) {+ if (++styleCount > 1_024 || attr("styleId").length > 256) throw limit;+ style = { id: attr("styleId"), properties: new Map(), base: "", linked: "" };+ }+ if (style) {+ if (tag.local === "basedOn") style.base = attr("val");+ else if (tag.local === "link") style.linked = attr("val");+ else if (names.length > 2 && tag.local !== "name") {+ const key = names.slice(2).join("/");+ const size = new TextEncoder().encode(+ xml.slice(xml.lastIndexOf("<", parser.position - 1), parser.position),+ ).length;+ if (++ownUnits > WORD_STYLE_MAX_UNITS) throw limit;+ style.properties.set(key, size);+ }+ }+ if (roles?.has("numbering")) {+ if (tag.local === "abstractNum")+ definition = {+ id: attr("abstractNumId"),+ start: xml.lastIndexOf("<", parser.position - 1),+ markup: markup - 1,+ };+ if (tag.local === "num") {+ if (references.length >= 2_000) throw limit;+ reference = { id: "", selector: attr("numId").length + 32 };+ references.push(reference);+ }+ if (tag.local === "abstractNumId" && reference) reference.id = attr("val");+ }+ if (tag.local === "numPicBullet") pictures = true;+ });+ parser.on("closetag", (tag) => {+ if (definition && tag.local === "abstractNum") {+ const previous = definitions.get(definition.id);+ definitions.set(definition.id, {+ bytes:+ (previous?.bytes ?? 0) ++ new TextEncoder().encode(xml.slice(definition.start, parser.position)).length,+ markup: (previous?.markup ?? 0) + markup - definition.markup,+ });+ definition = null;+ }+ if (tag.local === "num") reference = null;+ if (style && (tag.local === "style" || tag.local === "docDefaults")) {+ styles.set(style.id, style);+ style = null;+ }+ names.pop();+ depth--;+ });+ try {+ parser.write(xml).close();+ } catch (cause) {+ if (cause !== limit) throw cause;+ return exceeded;+ }+ const rawBytes = new TextEncoder().encode(xml).length;+ if (roles?.has("styles")) {+ // Immutable parent pointers match processStyles' ordered merges (including+ // forward links and cycles) without copying an expanding property map.+ type Resolved = {+ properties: Map<string, number>;+ parent?: Resolved | undefined;+ depth: number;+ };+ const resolved = new Map<string, Resolved>();+ for (const [id, style] of styles) resolved.set(id, { properties: style.properties, depth: 1 });+ for (const [id, style] of styles) {+ const parent = style.base ? resolved.get(style.base) : undefined;+ if (parent && parent.depth >= 32) return exceeded;+ resolved.set(id, { properties: style.properties, parent, depth: (parent?.depth ?? 0) + 1 });+ }+ let bytes = 0;+ let expandedMarkup = 0;+ let visited = 0;+ let propertyVisits = 0;+ for (const [id, style] of styles) {+ for (const root of [+ resolved.get(id),+ style.linked ? resolved.get(style.linked) : undefined,+ ]) {+ const seen = new Set<string>();+ for (let node = root; node; node = node.parent) {+ if (++visited > 8_192) return exceeded;+ for (const [key, size] of node.properties) {+ if (++propertyVisits > 100_000) return exceeded;+ if (seen.has(key)) continue;+ // Latent styles never enter properties. Charge each own property+ // once per resolved style, including linked and default selectors.+ const copies = id ? 1 : 2;+ bytes += (size * 2 + id.length + 32) * copies;+ expandedMarkup += copies;+ if (bytes > WORD_STYLE_MAX_BYTES || expandedMarkup > WORD_STYLE_MAX_UNITS)+ return exceeded;+ seen.add(key);+ }+ }+ }+ }+ return { bytes, markup: expandedMarkup, pictures };+ }+ let bytes = rawBytes;+ if (roles?.has("numbering")) {+ for (const ref of references) {+ const cost = definitions.get(ref.id);+ if (!cost) continue;+ bytes += cost.bytes * 2 + cost.markup * ref.selector;+ markup += cost.markup;+ if (bytes > 128 * 1024 || markup > 2_000) return exceeded;+ }+ }+ return { bytes, markup, pictures };+}++// Layout can repeat notes at references and headers/footers across pages.+// Charge those copies, not just the XML that defines them.+async function wordExpansion(+ archive: JSZip,+ parts: ReturnType<typeof wordPartTypes>,+ mediaSizes: Map<string, number>,+ auxiliaryCosts: Map<string, { bytes: number; markup: number }>,+ documents: string[],+) {+ type Cost = { bytes: number; markup: number; media: number; images: Set<string> };+ const empty = (): Cost => ({ bytes: 0, markup: 0, media: 0, images: new Set() });+ const nodes = new Map<string, { xml: string; path: string }>();+ const optional = new Set<string>();+ const noteParts = new Map<string, string>();+ for (const [path, roles] of parts.roles) {+ if (![...roles].some((role) => WORD_EXPANDED_PARTS.has(role))) continue;+ const xml = await archive.file(path)?.async("string");+ if (!xml) continue;+ optional.add(path);+ if (roles.has("header") || roles.has("footer")) nodes.set(path, { xml, path });+ for (const role of ["footnotes", "endnotes", "comments"]) {+ if (!roles.has(role)) continue;+ noteParts.set(role.slice(0, -1), path);+ const parser = xmlParser();+ let start = 0;+ let id = "";+ let depth = 0;+ let prefix = "";+ let suffix = "";+ parser.on("opentag", (tag) => {+ if (++depth === 1) {+ prefix = xml.slice(0, parser.position);+ suffix = `</${tag.name}>`;+ }+ if (tag.local !== role.slice(0, -1)) return;+ start = xml.lastIndexOf("<", parser.position - 1);+ id = Object.values(tag.attributes).find((attr) => attr.local === "id")?.value ?? "";+ });+ parser.on("closetag", (tag) => {+ if (tag.local === role.slice(0, -1))+ nodes.set(`${path}#${id}`, {+ xml: prefix + xml.slice(start, parser.position) + suffix,+ path,+ });+ depth--;+ });+ parser.write(xml).close();+ }+ }+ const used = new Set<string>();+ const memo = new Map<string, Cost>();+ let expandedXmlBytes = 0;+ const scan = (xml: string, path: string, chain: Set<string>, pages = 1, expand = true): Cost => {+ const cost = empty();+ const refs = new Map<string, number>();+ const headers = new Set<string>();+ const parser = xmlParser();+ const add = (key: string) => refs.set(key, (refs.get(key) ?? 0) + 1);+ parser.on("opentag", (tag) => {+ const attr = (name: string) =>+ Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";+ const note = /^(footnote|endnote|comment)Reference$/.exec(tag.local)?.[1];+ if (note && noteParts.has(note)) add(`${noteParts.get(note)}#${attr("id")}`);+ if (tag.local === "headerReference" || tag.local === "footerReference") {+ const target = parts.relationships.get(path)?.get(attr("id"));+ if (target) headers.add(target);+ }+ if (tag.local === "altChunk") cost.bytes = Infinity;+ if (tag.local !== "blip" && tag.local !== "imagedata") return;+ const target = parts.relationships.get(path)?.get(attr("embed") || attr("id"));+ if (target) {+ cost.media += mediaSizes.get(target) ?? OFFICE_PREVIEW_MAX_BYTES + 1;+ cost.images.add(target);+ }+ });+ parser.write(xml).close();+ for (const header of headers) refs.set(header, pages);+ if (!expand) return cost;+ for (const [key, copies] of refs) {+ const node = nodes.get(key);+ if (!node) continue;+ used.add(node.path);+ if (chain.has(key) || chain.size >= 64) {+ cost.bytes = Infinity;+ break;+ }+ let expanded = memo.get(key);+ if (!expanded) {+ expandedXmlBytes += node.xml.length * 2;+ if (expandedXmlBytes > 3 * 1024 * 1024) {+ cost.bytes = Infinity;+ break;+ }+ const own = wordXmlCost(node.xml, undefined);+ expanded = scan(node.xml, node.path, new Set([...chain, key]));+ expanded.bytes += own.bytes;+ expanded.markup += own.markup;+ memo.set(key, expanded);+ }+ cost.bytes += expanded.bytes * copies;+ cost.markup += expanded.markup * copies;+ cost.media += expanded.media * copies;+ for (const image of expanded.images) cost.images.add(image);+ }+ return cost;+ };+ const costs = new Map<string, Cost>();+ let bytes = 0;+ let markup = 0;+ let media = 0;+ // Styles may introduce a page break before each styled paragraph. The page+ // bound also includes explicit breaks and section transitions in each batch.+ let stylePageBreaks = false;+ for (const [path, roles] of parts.roles)+ if (+ roles.has("styles") &&+ /<(?:\w+:)?pageBreakBefore\b/.test((await archive.file(path)?.async("string")) ?? "")+ )+ stylePageBreaks = true;+ for (const document of documents) {+ const pages = Math.max(+ 1,+ document.match(+ stylePageBreaks ? /<(?:\w+:)?p\b/g : /<(?:\w+:)?(?:br|pageBreakBefore|sectPr)\b/g,+ )?.length ?? 0,+ );+ const expanded = scan(document, "word/document.xml", new Set(), pages);+ const body = wordXmlCost(document, undefined);+ bytes += body.bytes + expanded.bytes;+ markup += body.markup + expanded.markup;+ media += expanded.media;+ costs.set(document, expanded);+ }+ for (const [path, cost] of auxiliaryCosts) {+ if (optional.has(path) && !used.has(path)) continue;+ bytes += cost.bytes;+ markup += cost.markup;+ }+ const overBudget =+ bytes > 3 * 1024 * 1024 || markup > 100_000 || media > OFFICE_PREVIEW_MAX_BYTES;+ const truncated = (used.size > 0 && overBudget) || bytes === Infinity;+ const omitted = new Set([...optional].filter((path) => truncated || !used.has(path)));+ for (const path of omitted) archive.remove(path);+ if (truncated)+ for (const document of documents)+ costs.set(document, scan(document, "word/document.xml", new Set(), 1, false));+ // Remove relationships too: related XML is parsed even when not rendered.+ for (const [owner, refs] of parts.relationships) {+ const ids = new Set([...refs].filter(([, path]) => omitted.has(path)).map(([id]) => id));+ if (ids.size === 0) continue;+ const relPath = owner ? owner.replace(/([^/]+)$/, "_rels/$1.rels") : "_rels/.rels";+ let xml = await archive.file(relPath)?.async("string");+ if (!xml) continue;+ const removed: { start: number; end: number }[] = [];+ const parser = xmlParser();+ let start = -1;+ parser.on("opentag", (tag) => {+ if (tag.local === "Relationship" && ids.has(tag.attributes.Id?.value ?? ""))+ start = xml!.lastIndexOf("<", parser.position - 1);+ });+ parser.on("closetag", (tag) => {+ if (tag.local === "Relationship" && start >= 0) {+ removed.push({ start, end: parser.position });+ start = -1;+ }+ });+ parser.write(xml).close();+ for (const range of removed.toReversed())+ xml = xml.slice(0, range.start) + xml.slice(range.end);+ archive.file(relPath, xml);+ }+ return { costs, truncated, omitted };+}++// Stream each entry before handing it to an engine. A tiny compressed archive+// must not turn into an unbounded allocation on the UI thread.+async function boundedArchive(input: Extract<OfficeWorkerRequest, { type: "open" }>) {+ const { bytes } = input;+ if (bytes.byteLength > OFFICE_PREVIEW_MAX_BYTES)+ throw new Error("Preview limited to files under 50 MB.");+ checkZipDirectory(bytes);+ const source = await JSZip.loadAsync(bytes).catch(() => {+ throw new Error("This file is damaged, encrypted, or not a valid Office document.");+ });+ const allEntries = Object.values(source.files);+ if (allEntries.length > 2048)+ throw new Error("This file contains too many archive entries to preview.");+ const entries = allEntries.filter((entry) => !entry.dir);+ if (+ input.kind === "docx" &&+ entries.some((entry) => entry.name.includes("\\") || entry.name.startsWith("/"))+ )+ throw new Error("Preview limited: this Word document has unsupported archive paths.");+ const archive = new JSZip();+ const partTypes = wordPartTypes();+ // Metadata must be bounded and classified before any payload gets a media exemption.+ if (input.kind === "docx")+ entries.sort(+ (a, b) =>+ Number(b.name === "[Content_Types].xml" || b.name.endsWith(".rels")) -+ Number(a.name === "[Content_Types].xml" || a.name.endsWith(".rels")),+ );+ const costs = new Map<string, { bytes: number; markup: number }>();+ const mediaSizes = new Map<string, number>();+ let total = 0;+ let wordAuxiliaryMarkup = 0;+ let wordInputTruncated = false;+ let word: ReturnType<typeof wordDocuments> | null = null;+ for (const entry of entries) {+ const document = input.kind === "docx" && entry.name === "word/document.xml";+ const media = input.kind === "docx" && partTypes.binary(entry.name);+ const chunks: Uint8Array[] = [];+ const sections = document ? wordSections() : null;+ let decoder: TextDecoder | undefined;+ let length = 0;+ await new Promise<void>((resolve, reject) => {+ // JSZip exposes this streaming API at runtime but omits it from its types.+ const stream = (+ entry as JSZip.JSZipObject & {+ internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array>;+ }+ ).internalStream("uint8array");+ stream+ .on("data", (chunk: Uint8Array) => {+ total += chunk.length;+ length += chunk.length;+ if (total > OFFICE_PREVIEW_MAX_BYTES) {+ stream.pause();+ reject(new Error("The expanded document is too large to preview safely."));+ return;+ }+ try {+ if (sections) {+ decoder ??= officeXmlDecoder(chunk);+ sections.write(decoder.decode(chunk, { stream: true }));+ }+ } catch (cause) {+ stream.pause();+ reject(cause);+ return;+ }+ if (document && length > 4 * 1024 * 1024) {+ const kept = Math.max(0, chunk.length - (length - 4 * 1024 * 1024));+ if (kept) chunks.push(chunk.subarray(0, kept));+ wordInputTruncated = true;+ return;+ }+ // Media is bounded independently. Even renamed auxiliary XML must+ // stay small before the engine parses it.+ if (input.kind === "docx" && !document && !media) {+ for (const byte of chunk) if (byte === 0x3c) wordAuxiliaryMarkup++;+ if (length > 1024 * 1024 || wordAuxiliaryMarkup > 50_000) {+ stream.pause();+ reject(+ new Error("Preview limited: this Word document has too much auxiliary markup."),+ );+ return;+ }+ }+ if (+ total > OFFICE_PREVIEW_MAX_BYTES ||+ (!document &&+ (input.kind === "xlsx" || media || entry.name.endsWith(".xml")) &&+ length > 8 * 1024 * 1024)+ ) {+ stream.pause();+ reject(new Error("The expanded document is too large to preview safely."));+ } else chunks.push(chunk);+ })+ .on("error", reject)+ .on("end", resolve)+ .resume();+ });+ const content = new Uint8Array(document ? Math.min(length, 4 * 1024 * 1024) : length);+ let offset = 0;+ for (const chunk of chunks) {+ content.set(chunk, offset);+ offset += chunk.length;+ }+ if (document) {+ sections!.write(decoder?.decode() ?? "");+ word = wordDocuments(officeXml(content), wordInputTruncated, sections!.finish());+ archive.file(entry.name, word.documents[0]!);+ } else if (input.kind === "docx" && !media) {+ let xml = officeXml(content);+ if (entry.name === "[Content_Types].xml" || entry.name.endsWith(".rels"))+ xml = partTypes.metadata(entry.name, xml);+ const roles = partTypes.roles.get(entry.name);+ const cost = wordXmlCost(xml, roles);+ // The renderer parses related parts even when their render option is off.+ if (roles && [...roles].every((role) => WORD_DISABLED_PARTS.has(role))) continue;+ if (+ (roles?.has("numbering") && cost.pictures) ||+ (roles?.has("styles") &&+ (cost.bytes > WORD_STYLE_MAX_BYTES || cost.markup > WORD_STYLE_MAX_UNITS)) ||+ (roles?.has("numbering") && (cost.bytes > 128 * 1024 || cost.markup > 2_000))+ ) {+ wordInputTruncated = true;+ continue;+ }+ costs.set(entry.name, cost);+ archive.file(entry.name, xml);+ } else {+ if (input.kind === "docx" && partTypes.roles.get(entry.name)?.has("font")) {+ continue;+ }+ if (media) mediaSizes.set(entry.name, Math.ceil((content.length * 4) / 3));+ archive.file(entry.name, /\.(?:xml|rels)$/i.test(entry.name) ? officeXml(content) : content);+ }+ }+ if (word) {+ const expansion = await wordExpansion(archive, partTypes, mediaSizes, costs, word.documents);+ wordInputTruncated ||= expansion.truncated;+ for (const path of expansion.omitted) {+ archive.remove(path);+ costs.delete(path);+ }+ let mediaBytes = 0;+ const usedImages = new Set<string>();+ const auxiliary = [...costs.values()].reduce(+ (sum, cost) => ({ bytes: sum.bytes + cost.bytes, markup: sum.markup + cost.markup }),+ { bytes: 0, markup: 0 },+ );+ // The worker engine parses shared parts once, rather than once per legacy render batch.+ let bytes = auxiliary.bytes;+ let markup = auxiliary.markup;+ const documents: string[] = [];+ for (const document of word.documents) {+ const rawCost = wordXmlCost(document, undefined);+ const extra = expansion.costs.get(document)!;+ const cost = { bytes: rawCost.bytes + extra.bytes, markup: rawCost.markup + extra.markup };+ const images = extra.media;+ const batchImages = new Set(extra.images);+ if (+ bytes + cost.bytes > 3 * 1024 * 1024 ||+ markup + cost.markup > 100_000 ||+ mediaBytes + images > OFFICE_PREVIEW_MAX_BYTES+ )+ break;+ bytes += cost.bytes;+ markup += cost.markup;+ mediaBytes += images;+ for (const path of batchImages) usedImages.add(path);+ documents.push(document);+ }+ if (documents.length === 0)+ throw new Error("Preview limited: this Word document has too much expanded markup.");+ word.truncated ||= wordInputTruncated || documents.length < word.documents.length;+ word.documents = documents;+ for (const path of mediaSizes.keys()) if (!usedImages.has(path)) archive.remove(path);+ archive.file("word/document.xml", documents[0]!);+ }+ const truncatedSheets = input.kind === "xlsx" ? await boundWorkbook(archive) : [];+ return { archive, word, truncatedSheets };+}++export async function prepareOffice(+ bytes: ArrayBuffer,+ kind: Extract<OfficeWorkerRequest, { type: "open" }>["kind"],+) {+ const result = await boundedArchive({ type: "open", kind, bytes });+ const root =+ kind === "docx"+ ? "word/document.xml"+ : kind === "xlsx"+ ? "xl/workbook.xml"+ : "ppt/presentation.xml";+ if (!result.archive.file(root))+ throw new Error("This is not a valid Office Open XML file. Encrypted files are not supported.");+ if (result.word) {+ const references = new Map<string, string>();+ const relationships = xmlParser();+ relationships.on("opentag", (tag) => {+ if (tag.local !== "Relationship") return;+ const type = tag.attributes.Type?.value ?? "";+ const target = tag.attributes.Target?.value ?? "";+ const path = new URL(target, "https://docx.invalid/word/").pathname.slice(1);+ if (result.archive.file(path))+ references.set(tag.attributes.Id?.value ?? "", type.slice(type.lastIndexOf("/") + 1));+ });+ const relationshipXml = await result.archive+ .file("word/_rels/document.xml.rels")+ ?.async("string");+ if (relationshipXml) relationships.write(relationshipXml).close();+ let xml = joinWordBatches(result.word.documents);+ const removed: { start: number; end: number }[] = [];+ const parser = xmlParser();+ let start = -1;+ // Bounded parts can be omitted; dangling story references otherwise reject the entire body in the engine.+ parser.on("opentag", (tag) => {+ if (tag.local !== "headerReference" && tag.local !== "footerReference") return;+ const id = Object.values(tag.attributes).find((attr) => attr.local === "id")?.value ?? "";+ if (references.get(id) !== tag.local.replace("Reference", ""))+ start = xml.lastIndexOf("<", parser.position - 1);+ });+ parser.on("closetag", (tag) => {+ if (start >= 0 && (tag.local === "headerReference" || tag.local === "footerReference")) {+ removed.push({ start, end: parser.position });+ start = -1;+ }+ });+ parser.write(xml).close();+ for (const range of removed.toReversed())+ xml = xml.slice(0, range.start) + xml.slice(range.end);+ result.archive.file(root, xml);+ }+ return {+ bytes: await result.archive.generateAsync({ type: "arraybuffer", compression: "STORE" }),+ truncated: result.word?.truncated || result.truncatedSheets.some(Boolean) || false,+ };+}++function joinWordBatches(documents: string[]) {+ let prefix = "";+ let suffix = "";+ let section = "";+ const bodies: string[] = [];+ for (const xml of documents) {+ const parser = xmlParser();+ let depth = 0;+ let start = 0;+ let end = 0;+ let sectionStart = 0;+ parser.on("opentag", (tag) => {+ depth++;+ if (depth === 2 && tag.local === "body") {+ start = parser.position;+ if (!prefix) prefix = xml.slice(0, start);+ }+ if (depth === 3 && tag.local === "sectPr")+ sectionStart = xml.lastIndexOf("<", parser.position - 1);+ });+ parser.on("closetag", (tag) => {+ if (depth === 2 && tag.local === "body") {+ end = xml.lastIndexOf("<", parser.position - 1);+ suffix = xml.slice(end);+ }+ depth--;+ });+ parser.write(xml).close();+ bodies.push(xml.slice(start, sectionStart || end));+ section = sectionStart ? xml.slice(sectionStart, end) : "";+ }+ return prefix + bodies.join("") + section + suffix;+}diff --git a/apps/web/src/components/files/officePreview.worker.ts b/apps/web/src/components/files/officePreview.worker.tsnew file mode 100644index 00000000000..071d70a66ad--- /dev/null+++ b/apps/web/src/components/files/officePreview.worker.ts@@ -0,0 +1,20 @@+import { prepareOffice } from "./officeArchive";+import type { OfficeWorkerRequest, OfficeWorkerResult } from "./officePreviewProtocol";+self.addEventListener("message", (event: MessageEvent<OfficeWorkerRequest>) => {+ if (event.data.type !== "open") return;+ const input = event.data;+ void prepareOffice(input.bytes, input.kind)+ .then((result) => {+ const reply: OfficeWorkerResult = { type: input.kind, ...result };+ self.postMessage(reply, { transfer: [result.bytes] });+ })+ .catch((cause: unknown) => {+ self.postMessage(+ {+ type: "error",+ message: cause instanceof Error ? cause.message : "Could not parse this file.",+ } satisfies OfficeWorkerResult,+ { transfer: [] },+ );+ });+});diff --git a/apps/web/src/components/files/officePreviewProtocol.ts b/apps/web/src/components/files/officePreviewProtocol.tsnew file mode 100644index 00000000000..b24b167f73c--- /dev/null+++ b/apps/web/src/components/files/officePreviewProtocol.ts@@ -0,0 +1,16 @@+import type { OfficePreviewKind } from "@t3tools/shared/filePreview";+export const OFFICE_PREVIEW_MAX_BYTES = 50 * 1024 * 1024;+export const OFFICE_PREVIEW_MAX_ROWS = 500;+export const OFFICE_PREVIEW_MAX_COLUMNS = 50;+export type OfficeWorkerRequest = {+ readonly type: "open";+ readonly kind: OfficePreviewKind;+ readonly bytes: ArrayBuffer;+};+export type OfficeWorkerResult =+ | { readonly type: "error"; readonly message: string }+ | {+ readonly type: OfficePreviewKind;+ readonly bytes: ArrayBuffer;+ readonly truncated: boolean;+ };diff --git a/apps/web/src/components/files/zipDirectory.ts b/apps/web/src/components/files/zipDirectory.tsnew file mode 100644index 00000000000..4f04c6ed6de--- /dev/null+++ b/apps/web/src/components/files/zipDirectory.ts@@ -0,0 +1,75 @@+export function checkZipDirectory(bytes: ArrayBuffer, entryLimit = 2048) {+ // Reject oversized directories before JSZip allocates objects for their entries.+ const view = new DataView(bytes);+ let directoryEnd = -1;+ let directorySize = 0;+ for (+ let offset = bytes.byteLength - 22;+ offset >= Math.max(0, bytes.byteLength - 65557);+ offset--+ ) {+ if (view.getUint32(offset, true) !== 0x06054b50) continue;+ if (offset + 22 + view.getUint16(offset + 20, true) !== bytes.byteLength)+ throw new Error("This is not a readable ZIP archive.");+ let count = view.getUint16(offset + 10, true);+ directorySize = view.getUint32(offset + 12, true);+ let directoryOffset = view.getUint32(offset + 16, true);+ directoryEnd = offset;+ if (+ [4, 6, 8, 10].some((field) => view.getUint16(offset + field, true) === 0xffff) ||+ directorySize === 0xffffffff ||+ directoryOffset === 0xffffffff+ ) {+ const locator = offset - 20;+ const record = locator - 56;+ // JSZip uses the last locator, including signatures inside the archive comment.+ for (let candidate = bytes.byteLength - 4; candidate > locator; candidate--)+ if (view.getUint32(candidate, true) === 0x07064b50)+ throw new Error("Unsupported ZIP64 directory.");+ if (+ record < 0 ||+ view.getUint32(locator, true) !== 0x07064b50 ||+ view.getUint32(record, true) !== 0x06064b50 ||+ view.getBigUint64(record + 4, true) !== 44n ||+ view.getUint32(record + 16, true) !== 0 ||+ view.getUint32(record + 20, true) !== 0 ||+ view.getUint32(locator + 4, true) !== 0 ||+ view.getUint32(locator + 16, true) !== 1 ||+ view.getBigUint64(locator + 8, true) !== BigInt(record)+ )+ throw new Error("Unsupported ZIP64 directory.");+ const records = view.getBigUint64(record + 32, true);+ const size = view.getBigUint64(record + 40, true);+ const start = view.getBigUint64(record + 48, true);+ if (+ records > BigInt(entryLimit) ||+ size > BigInt(record) ||+ start > BigInt(record) ||+ view.getBigUint64(locator + 8, true) !== start + size ||+ view.getBigUint64(record + 24, true) !== records+ )+ throw new Error("This ZIP64 directory is too large or damaged.");+ count = Number(records);+ directorySize = Number(size);+ directoryOffset = Number(start);+ directoryEnd = record;+ }+ if (count > entryLimit) throw new Error("This archive contains more than 2,048 entries.");+ if (directoryOffset > directoryEnd - directorySize)+ throw new Error("This ZIP directory is damaged.");+ break;+ }+ if (directoryEnd < 0 || directorySize > directoryEnd)+ throw new Error("This is not a readable ZIP archive.");+ let records = 0;+ for (let offset = directoryEnd - directorySize; offset < directoryEnd;) {+ if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50)+ throw new Error("This ZIP directory is damaged.");+ if (++records > entryLimit) throw new Error("This archive contains more than 2,048 entries.");+ const nameLength = view.getUint16(offset + 28, true);+ if (nameLength > 1024) throw new Error("An archive path is too long to preview.");+ offset +=+ 46 + nameLength + view.getUint16(offset + 30, true) + view.getUint16(offset + 32, true);+ if (offset > directoryEnd) throw new Error("This ZIP directory is damaged.");+ }+}diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex 38a4cccf5de..67493e48481 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -97,9 +97,22 @@ const browserTestApiPort = 61_000 + ((Hash.string(import.meta.dirname) >>> 0) %const browserTestProject = {extends: true,- // Pre-bundled so a late first import does not trigger a mid-run reload. The- // dependency scan misses autocomplete because tests reach it only through lazy imports.- optimizeDeps: { include: ["vite-plus/test/browser", "@base-ui/react/autocomplete"] },+ // Pre-bundle lazy browser and worker dependencies to avoid mid-run reloads.+ optimizeDeps: {+ include: [+ "vite-plus/test/browser",+ "@base-ui/react/autocomplete",+ "saxes",+ "@betteroffice/docx/editor",+ "@betteroffice/docx/layout",+ "@betteroffice/docx/layout/render",+ "@betteroffice/docx/yrs",+ "@betteroffice/fonts",+ "@betteroffice/pptx",+ "@betteroffice/xlsx",+ "@betteroffice/xlsx/headless",+ ],+ },test: {name: "browser",include: ["src/**/*.browser.test.{ts,tsx}"],@@ -274,6 +287,12 @@ export default defineConfig(() => {},resolve: {tsconfigPaths: true,+ alias: {+ "@betteroffice/fonts-cjk": new URL(+ "./src/components/files/office/fonts-cjk.ts",+ import.meta.url,+ ).pathname,+ },dedupe: ["react", "react-dom"],},experimental: {@@ -325,6 +344,7 @@ export default defineConfig(() => {manifest: true,sourcemap: buildSourcemap,},+ worker: { format: "es" },test: {projects: [defineProject(unitTestProject),diff --git a/packages/shared/src/filePreview.test.ts b/packages/shared/src/filePreview.test.tsindex 0c40ca3af7e..0153166252d 100644--- a/packages/shared/src/filePreview.test.ts+++ b/packages/shared/src/filePreview.test.ts@@ -4,18 +4,87 @@ import {filePreviewKind,decodeFilePreviewText,FILE_TEXT_PREVIEW_MAX_BYTES,+ hostPreviewMimeTypeFromExtension,+ isWorkspaceFontPreviewPath,+ isWorkspaceImagePreviewPath,isWorkspacePreviewEntryPath,mediaKindFromPath,+ officePreviewKind,} from "./filePreview.ts";describe("workspace file previews", () => {+ it.each(["ttf", "otf", "woff", "woff2"])(+ "previews %s fonts through signed host assets",+ (extension) => {+ expect(+ filePreviewKind({ name: `sample.${extension}`, mimeType: "application/octet-stream" }),+ ).toBe("font");+ expect(filePreviewKind({ name: "download", mimeType: `font/${extension}` })).toBe("font");+ expect(isWorkspaceFontPreviewPath(`/tmp/sample.${extension.toUpperCase()}`)).toBe(true);+ expect(isWorkspacePreviewEntryPath(`sample.${extension}`)).toBe(true);+ expect(hostPreviewMimeTypeFromExtension(`.${extension}`)).toBe(`font/${extension}`);+ expect(isWorkspaceFontPreviewPath(`sample.${extension}?download=1`)).toBe(false);+ expect(filePreviewKind({ name: `sample.${extension}`, mimeType: "application/zip" })).toBe(+ "unsupported",+ );+ },+ );+ it.each([+ [+ "quarterly-report.DOCX",+ "docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ ],+ [+ "finance#q4/operating-plan.xlsx",+ "xlsx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ ],+ [+ "slides?review/quarterly-review.pptx",+ "pptx",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ ],+ ])("recognizes Office assets at literal path %s", (name, kind, mimeType) => {+ expect(officePreviewKind({ name })).toBe(kind);+ expect(filePreviewKind({ name, mimeType: "application/octet-stream" })).toBe(kind);+ expect(isWorkspacePreviewEntryPath(name)).toBe(true);+ expect(hostPreviewMimeTypeFromExtension(`.${kind}`)).toBe(mimeType);+ expect(filePreviewKind({ name: "download", mimeType })).toBe(kind);+ expect(filePreviewKind({ name, mimeType: "application/zip" })).toBe("unsupported");+ });// regression: #10311 previews classify by the literal filename, not URL-like suffixes- it.each(["image.png.ts", "image.png#notes.txt", "image%2Epng"])(- "rejects non-preview path %s",+ it.each([+ "image.png.ts",+ "image.png#notes.txt",+ "image%2Epng",+ "report.docx#notes.txt",+ "report.xlsx?download=1",+ "slides%2Epptx",+ "report.docm",+ "slides.ppt",+ ])("rejects non-preview path %s", (path) => {+ expect(isWorkspacePreviewEntryPath(path)).toBe(false);+ });++ it.each(["picture.bmp", "photo.heic", "scan.tif", "scan.TIFF"])(+ "recognizes image preview path %s",(path) => {- expect(isWorkspacePreviewEntryPath(path)).toBe(false);+ expect(isWorkspaceImagePreviewPath(path)).toBe(true);+ expect(isWorkspacePreviewEntryPath(path)).toBe(true);},);++ it("serves audio in place from the host like video and browser documents", () => {+ expect(hostPreviewMimeTypeFromExtension(".m4a")).toBe("audio/mp4");+ expect(hostPreviewMimeTypeFromExtension(".weba")).toBe("audio/webm");+ expect(hostPreviewMimeTypeFromExtension(".mp4")).toBe("video/mp4");+ expect(hostPreviewMimeTypeFromExtension(".txt")).toBeNull();+ expect(hostPreviewMimeTypeFromExtension(".constructor")).toBeNull();+ expect(hostPreviewMimeTypeFromExtension(".toString")).toBeNull();+ expect(hostPreviewMimeTypeFromExtension(".__proto__")).toBeNull();+ expect(hostPreviewMimeTypeFromExtension(".webm-audio")).toBe("audio/webm");+ });});describe("media path parsing", () => {@@ -48,6 +117,17 @@ describe("attachment preview classification", () => {it.each([["example.json", "application/octet-stream", "text"],["report.pdf", "application/pdf", "pdf"],+ ["page.HTML", "", "html"],+ ["diagram.mmd", "", "mermaid"],+ ["diagram.MERMAID", "text/plain", "mermaid"],+ ["download", "text/vnd.mermaid", "mermaid"],+ ["source-code.otf", "application/vnd.oasis.opendocument.formula-template", "font"],+ ["notes.rtf", "application/rtf", "text"],+ ["notes.rtf", "", "text"],+ ["clip.weba", "", "audio"],+ ["image.bmp", "application/octet-stream", "image"],+ ["photo.heic", "application/octet-stream", "image"],+ ["scan.tiff", "application/octet-stream", "image"],["recording.mp3", "", "audio"],["recording.webm-audio", "", "audio"],["recording.webm", "audio/webm", "audio"],@@ -61,6 +141,12 @@ describe("attachment preview classification", () => {expect(() => decodeFilePreviewText(new Uint8Array([65, 0, 66]))).toThrow("binary");expect(() => decodeFilePreviewText(new Uint8Array([255]))).toThrow("UTF-8");});+ it.each(["doc", "xls", "ppt", "odt", "ods", "odp", "epub", "zip", "tar", "gz", "7z", "rar"])(+ "retains the binary fallback for %s, which opencode does not render",+ (extension) => {+ expect(filePreviewKind({ name: `sample.${extension}` })).toBe("unsupported");+ },+ );it("does not corrupt a multi-byte character at the preview boundary", () => {const bytes = new Uint8Array(FILE_TEXT_PREVIEW_MAX_BYTES + 1).fill(97);bytes[FILE_TEXT_PREVIEW_MAX_BYTES - 1] = 0xe2;diff --git a/packages/shared/src/filePreview.ts b/packages/shared/src/filePreview.tsindex 718c9aaaba7..2703c4bdef3 100644--- a/packages/shared/src/filePreview.ts+++ b/packages/shared/src/filePreview.ts@@ -26,20 +26,39 @@ export type FilePreviewKind =| "pdf"| "html"| "markdown"+ | "mermaid"+ | "font"+ | "docx"+ | "xlsx"+ | "pptx"| "text"| "unsupported";-export function filePreviewKind(file: {- readonly name: string;- readonly mimeType?: string;-}): FilePreviewKind {+export function filePreviewKind(+ file: { readonly name: string; readonly mimeType?: string },+ options?: { readonly richDocuments?: boolean },+): FilePreviewKind {const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";const name = file.name.toLowerCase();const extension = name.slice(name.lastIndexOf("."));const generic = !mime || mime === "application/octet-stream" || mime === "text/plain";+ const richDocuments = options?.richDocuments !== false;+ const office = richDocuments ? officePreviewKind(file) : null;+ if (office) return office;if (mime === "application/pdf") return "pdf";if (mime === "text/html") return "html";if (mime === "text/markdown" || mime === "text/x-markdown") return "markdown";+ if (richDocuments && mime === "text/vnd.mermaid") return "mermaid";+ if (richDocuments && mime.startsWith("font/")) return "font";+ // Linux's MIME database also assigns .otf to OpenDocument formula templates.+ // FontFace validates the actual bytes before a specimen is shown.+ if (+ richDocuments &&+ extension === ".otf" &&+ mime === "application/vnd.oasis.opendocument.formula-template"+ )+ return "font";+ if (richDocuments && mime === "application/rtf") return "text";if (mime.startsWith("image/")) return "image";if (mime.startsWith("video/")) return "video";if (mime.startsWith("audio/")) return "audio";@@ -47,6 +66,9 @@ export function filePreviewKind(file: {if (extension === ".pdf") return "pdf";if (/^\.html?$/.test(extension)) return "html";if (/^\.(md|markdown|mdown|mkd|mdx)$/.test(extension)) return "markdown";+ if (richDocuments && /^\.(mmd|mermaid)$/.test(extension)) return "mermaid";+ if (richDocuments && isWorkspaceFontPreviewPath(name)) return "font";+ if (richDocuments && extension === ".rtf") return "text";const media = mediaMimeTypeFromExtension(extension);if (media?.startsWith("image/")) return "image";if (media?.startsWith("video/")) return "video";@@ -73,6 +95,30 @@ export function filePreviewKind(file: {export const FILE_TEXT_PREVIEW_MAX_BYTES = 1024 * 1024;+const OFFICE_MIME_TYPES = {+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",+} as const;++export type OfficePreviewKind = keyof typeof OFFICE_MIME_TYPES;++export function officePreviewKind(file: {+ readonly name: string;+ readonly mimeType?: string;+}): OfficePreviewKind | null {+ const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";+ for (const kind of ["docx", "xlsx", "pptx"] as const) {+ if (mime === OFFICE_MIME_TYPES[kind]) return kind;+ if (+ (!mime || mime === "application/octet-stream" || mime === "text/plain") &&+ file.name.toLowerCase().endsWith(`.${kind}`)+ )+ return kind;+ }+ return null;+}+export function decodeFilePreviewText(bytes: Uint8Array, truncated = false) {const bounded = bytes.subarray(0, FILE_TEXT_PREVIEW_MAX_BYTES);if (bounded.some((byte) => byte === 0))@@ -92,23 +138,31 @@ export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] asexport const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [".avif",+ ".bmp",".gif",".ico",+ ".heic",".jpeg",".jpg",".png",".svg",+ ".tif",+ ".tiff",".webp",] as const;const IMAGE_MIME_TYPE_BY_EXTENSION = new Map([[".avif", "image/avif"],+ [".bmp", "image/bmp"],+ [".heic", "image/heic"],[".gif", "image/gif"],[".ico", "image/x-icon"],[".jpeg", "image/jpeg"],[".jpg", "image/jpeg"],[".png", "image/png"],[".svg", "image/svg+xml"],+ [".tif", "image/tiff"],+ [".tiff", "image/tiff"],[".webp", "image/webp"],]);@@ -129,8 +183,20 @@ const AUDIO_MIME_TYPE_BY_EXTENSION = new Map([[".opus", "audio/ogg"],[".aiff", "audio/aiff"],[".webm-audio", "audio/webm"],+ [".weba", "audio/webm"],+]);++const FONT_MIME_TYPE_BY_EXTENSION = new Map([+ [".ttf", "font/ttf"],+ [".otf", "font/otf"],+ [".woff", "font/woff"],+ [".woff2", "font/woff2"],]);+export function isWorkspaceFontPreviewPath(path: string): boolean {+ return /\.(ttf|otf|woff2?)$/i.test(path);+}+export function audioMimeTypeFromExtension(extension: string): string | null {if (!/^\.[a-z0-9-]+$/i.test(extension)) return null;return AUDIO_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ?? null;@@ -151,6 +217,10 @@ export function hostPreviewMimeTypeFromExtension(extension: string): string | numediaMimeTypeFromExtension(extension) ??audioMimeTypeFromExtension(extension) ??BROWSER_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??+ FONT_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??+ (Object.hasOwn(OFFICE_MIME_TYPES, extension.toLowerCase().slice(1))+ ? OFFICE_MIME_TYPES[extension.toLowerCase().slice(1) as OfficePreviewKind]+ : null) ??null);}@@ -215,5 +285,10 @@ export function isWorkspaceAudioPreviewPath(path: string): boolean {}export function isWorkspacePreviewEntryPath(path: string): boolean {- return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);+ return (+ isWorkspaceBrowserPreviewPath(path) ||+ isWorkspaceImagePreviewPath(path) ||+ isWorkspaceFontPreviewPath(path) ||+ officePreviewKind({ name: path }) !== null+ );}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f37e52e9598..579d8ca7f27 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -992,6 +992,18 @@ importers:'@base-ui/react':specifier: ^1.4.1version: 1.5.0(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])+ '@betteroffice/docx':+ specifier: 0.4.3+ version: 0.4.3(@betteroffice/[email protected])+ '@betteroffice/fonts':+ specifier: 0.4.0+ version: 0.4.0+ '@betteroffice/pptx':+ specifier: 0.2.0+ version: 0.2.0+ '@betteroffice/xlsx':+ specifier: 0.3.0+ version: 0.3.0'@clerk/clerk-js':specifier: 6.40.0@@ -1175,6 +1187,9 @@ importers:remark-parse:specifier: 'catalog:'version: 11.0.0([email protected])+ saxes:+ specifier: 6.0.0+ version: 6.0.0tailwind-merge:specifier: ^3.4.0version: 3.6.0@@ -2904,6 +2919,28 @@ packages:'@types/react':optional: true+ '@betteroffice/[email protected]':+ resolution: {integrity: sha512-CEErXJH3iCsi2a61gTNkAofLCzSTcktLmp710gGhMwbBfOqwQ2yI7dRFBV3ElGa9JxkS03IfejvLX0sAvlTrUQ==}+ peerDependencies:+ '@betteroffice/fonts': ^0+ peerDependenciesMeta:+ '@betteroffice/fonts':+ optional: true++ '@betteroffice/[email protected]':+ resolution: {integrity: sha512-x1BVwYDAgY5R6TWI4t9NLguSiAEbH5GItN2ZlpBIFoRXTIJgjBsXd6sUxPGpexXOyY6KdhRjG8XvHjyAYxEGCw==}+ peerDependencies:+ '@betteroffice/fonts-cjk': ^0+ peerDependenciesMeta:+ '@betteroffice/fonts-cjk':+ optional: true++ '@betteroffice/[email protected]':+ resolution: {integrity: sha512-pNPQ58tlA+pVibERbLdQNskvP7a0GIMf4jhkCU/gPp8043Ichf6gB3PSb4ra9sfqoIaWqOaZKCWyptovA2+Q0A==}++ '@betteroffice/[email protected]':+ resolution: {integrity: sha512-K2bHtdk/epAxsmvxJlIWBRndjP3ltQU0Oh3p4gcZd2n5/YgXglo3SmMYX4nQe8WEm/yvz91p+aIasKyXXQP9Wg==}+'@blazediff/[email protected]':resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==}@@ -13140,6 +13177,16 @@ snapshots:optionalDependencies:'@types/react': 19.3.0+ '@betteroffice/[email protected](@betteroffice/[email protected])':+ optionalDependencies:+ '@betteroffice/fonts': 0.4.0++ '@betteroffice/[email protected]': {}++ '@betteroffice/[email protected]': {}++ '@betteroffice/[email protected]': {}+'@blazediff/[email protected]': {}'@bramus/[email protected]':diff --git a/third-party-licenses.config.json b/third-party-licenses.config.jsonindex 2378e82fcc3..83a30f0edce 100644--- a/third-party-licenses.config.json+++ b/third-party-licenses.config.json@@ -1,5 +1,12 @@{"customNotices": [+ {+ "name": "opencode Office viewers",+ "bundles": ["web"],+ "license": "MIT",+ "sourceUrl": "https://github.com/anomalyco/opencode",+ "noticeFile": "apps/web/src/components/files/office/LICENSE.opencode"+ },{"bundles": ["desktop", "web"],"license": "MIT",@@ -222,6 +229,33 @@}],"packageOverrides": [+ {+ "name": "@betteroffice/xlsx",+ "version": "0.3.0",+ "license": "Apache-2.0",+ "sourceUrl": "https://github.com/openooxml/betteroffice",+ "generatedNotice": {+ "licenseId": "Apache-2.0"+ }+ },+ {+ "name": "@betteroffice/pptx",+ "version": "0.2.0",+ "license": "Apache-2.0",+ "sourceUrl": "https://github.com/openooxml/betteroffice",+ "generatedNotice": {+ "licenseId": "Apache-2.0"+ }+ },+ {+ "name": "@betteroffice/docx",+ "version": "0.4.3",+ "license": "Apache-2.0",+ "sourceUrl": "https://github.com/openooxml/betteroffice",+ "generatedNotice": {+ "licenseId": "Apache-2.0"+ }+ },{"name": "character-entities","version": "2.0.2",@@ -240,11 +274,26 @@"generatedNotice": {"licenseId": "ISC","copyrights": [+ "Copyright (c) 2018-2021 Louis-Dominique Dubeau","Copyright (c) Contributors","Copyright (c) Isaac Z. Schlueter and Contributors"]}},+ {+ "name": "@betteroffice/fonts",+ "version": "0.4.0",+ "license": "Apache-2.0 AND OFL-1.1",+ "generatedNotices": [+ { "licenseId": "Apache-2.0" },+ {+ "licenseId": "OFL-1.1",+ "copyrights": [+ "Copyright 2013 The Carlito Project Authors (https://github.com/googlefonts/carlito), with Reserved Font Name \"Carlito\""+ ]+ }+ ]+ },{"name": "remark-math","version": "6.0.0",