TypeScript
feat(web): preview opendocument, epub, rich text, and notebooks (#21469)
maria34ead566d448
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.tsindex b208f09d96e..103da32bbdb 100644--- a/apps/server/src/assets/AssetAccess.test.ts+++ b/apps/server/src/assets/AssetAccess.test.ts@@ -221,6 +221,12 @@ describe("AssetAccess", () => {["recording.webm", "video/webm"],["report.html", "text/html"],["report.pdf", "application/pdf"],+ ["notes.odt", "application/vnd.oasis.opendocument.text"],+ ["budget.ods", "application/vnd.oasis.opendocument.spreadsheet"],+ ["slides.odp", "application/vnd.oasis.opendocument.presentation"],+ ["notes.rtf", "application/rtf"],+ ["book.epub", "application/epub+zip"],+ ["analysis.ipynb", "application/x-ipynb+json"],["tone.wav", "audio/wav"],["tone.webm-audio", "audio/webm"],["archive.zip", "application/zip"],@@ -944,6 +950,20 @@ describe("AssetAccess", () => {expect(yield* resolveAsset(token, ".env")).toBeNull();expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();for (const extension of [+ "odt",+ "ods",+ "odp",+ "rtf",+ "epub",+ "ipynb",+ "zip",+ "jar",+ "tar",+ "gz",+ "tgz",+ "sqlite",+ "sqlite3",+ "db","docx","xlsx","pptx",@@ -1018,6 +1038,12 @@ describe("AssetAccess", () => {);for (const extension of ["pdf",+ "odt",+ "ods",+ "odp",+ "rtf",+ "epub",+ "ipynb","png","bmp","heic",@@ -1082,6 +1108,12 @@ describe("AssetAccess", () => {"report.docx","workbook.xlsx","slides.pptx",+ "notes.odt",+ "budget.ods",+ "slides.odp",+ "notes.rtf",+ "book.epub",+ "analysis.ipynb","specimen.ttf","specimen.otf","specimen.woff",diff --git a/apps/web/package.json b/apps/web/package.jsonindex 938feb52a93..27565feebba 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -61,6 +61,7 @@"culori": "^4.0.2","dompurify": "^3.4.16","effect": "catalog:",+ "entities": "8.1.0","fast-xml-parser": "5.7.3","hast-util-to-html": "^9.0.5","hast-util-to-jsx-runtime": "^2.3.6",@@ -72,6 +73,7 @@"lucide": "^0.564.0","lucide-react": "^0.564.0","morphicons": "^1.7.1",+ "pdfjs-dist": "6.4.299","pele": "^1.8.0","react": "catalog:","react-dom": "catalog:",diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsxindex 4b0ad2daa7d..4d20d5b5cb1 100644--- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx+++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx@@ -1,3 +1,4 @@+import { documentIconColorForFileName } from "~/pierre-icons";import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";import {@@ -45,6 +46,7 @@ import {useLayoutEffect,useRef,useState,+ type CSSProperties,type KeyboardEvent as ReactKeyboardEvent,type RefObject,} from "react";@@ -260,9 +262,11 @@ const ComposerMentionExtension = Node.create({function ComposerMentionNodeView({ node }: NodeViewProps) {const actions = use(ComposerContextActionsContext);const path = (node.attrs.path as string) ?? "";+ const accent = documentIconColorForFileName(path);const chip = (<ContextChipkind="mention"+ style={accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined}dir="ltr"render={<button type="button" />}onClick={() => actions.openMention(path)}diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsxindex e8620bf0111..872ce0de8dc 100644--- a/apps/web/src/components/chat/MarkdownFileLink.tsx+++ b/apps/web/src/components/chat/MarkdownFileLink.tsx@@ -5,12 +5,13 @@ import {type AtomCommandResult,} from "@t3tools/client-runtime/state/runtime";import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";-import { memo, type MouseEvent as ReactMouseEvent } from "react";+import { memo, type CSSProperties, type MouseEvent as ReactMouseEvent } from "react";import { readLocalApi } from "../../localApi";import { cn } from "../../lib/utils";import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links";import type { markdownFileCopyPaths } from "../../markdownFileHostPath";+import { documentIconColorForFileName } from "../../pierre-icons";import { ContextChip } from "../ContextChip";import { stackedThreadToast, toastManager } from "../ui/toast";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";@@ -320,6 +321,8 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({canOpenInBrowser,canOpenInPanel,});+ const accent = documentIconColorForFileName(iconPath);+ const chipStyle = accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined;return (<Tooltip>@@ -331,6 +334,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({dir="ltr"render={<a href={href} />}className={MARKDOWN_FILE_LINK_CLASS_NAME}+ style={chipStyle}data-markdown-copy={copyMarkdown}onClick={(event) => {event.preventDefault();@@ -362,6 +366,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({aria-label={`File options for ${label}`}aria-haspopup="menu"className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")}+ style={chipStyle}data-markdown-copy={copyMarkdown}onClick={handleContextMenu}onContextMenu={handleContextMenu}diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsxindex 6d9c566c52f..8b6b8301fd9 100644--- a/apps/web/src/components/chat/UserMessageContextChips.tsx+++ b/apps/web/src/components/chat/UserMessageContextChips.tsx@@ -1,3 +1,4 @@+import { documentIconColorForFileName } from "~/pierre-icons";import { isSvgAttachment } from "@t3tools/shared/image";import { useRenderedAppearance } from "../../hooks/useTheme";import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";@@ -5,7 +6,7 @@ import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";import { useRightPanelStore } from "~/rightPanelStore";import { COMPOSER_CONTEXT_KINDS } from "@t3tools/contracts";import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";-import { use, type ReactNode } from "react";+import { use, type CSSProperties, type ReactNode } from "react";import { FileDiff } from "@pierre/diffs/react";import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";import {@@ -61,12 +62,14 @@ function UserMessageMentionChip(props: {copyMarkdown: string;}) {const ctx = use(TimelineRowCtx);+ const accent = documentIconColorForFileName(props.record.path);return (<Tooltip><TooltipTriggerrender={<ContextChipkind="mention"+ style={accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined}render={<button type="button" />}aria-label={`Preview ${props.record.path}`}data-markdown-copy={props.copyMarkdown}diff --git a/apps/web/src/components/contextChipParts.tsx b/apps/web/src/components/contextChipParts.tsxindex d6c3b842b5f..0917efc269d 100644--- a/apps/web/src/components/contextChipParts.tsx+++ b/apps/web/src/components/contextChipParts.tsx@@ -9,6 +9,7 @@ import {type ReactNode,} from "react";import { useAssetUrlState } from "~/assets/assetUrls";+import { documentIconColorForFileName } from "~/pierre-icons";import { PULL_REQUEST_STATE_PRESENTATION } from "~/components/pullRequest/pullRequestIcons";import type { PullRequestContextDisplayState } from "~/lib/composerContextRecords";@@ -242,6 +243,7 @@ export function FileChip(props: {}) {if (props.svgPreview && !props.unresolved) return <SvgFileChip {...props} />;const content = <FileChipContent {...props} />;+ const accent = props.isVideo ? undefined : documentIconColorForFileName(props.name);const state = props.unresolved? ("unresolved" as const): props.error@@ -249,6 +251,7 @@ export function FileChip(props: {: null;const attributes = {kind: props.isVideo ? "video" : "file",+ style: accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined,...(state ? { state } : {}),"aria-label": [props.accessibleLabel, props.suffix].filter(Boolean).join(", "),"data-markdown-copy": props.copyMarkdown,diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsxindex aa21c06f803..6b173c5362c 100644--- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx+++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx@@ -1,3 +1,4 @@+import DocumentPages, { sanitizeDocumentHtml } from "./DocumentPages";import { act, render, stubGlobal, type Screen } from "../../../test/render";import { EnvironmentId, ThreadId } from "@t3tools/contracts";import { describe, expect, it, vi } from "vite-plus/test";@@ -2057,6 +2058,40 @@ describe("attachment HTML preview recovery", () => {});});+describe("document output sanitization", () => {+ it("fits saved HTML outputs to their content and resizes when the content changes", async () => {+ await using screen = await render(+ <DocumentPages html="<table><tr><td>42</td></tr></table>" name="Output" output />,+ );+ const frame = screen.container.querySelector("iframe")!;+ await vi.waitFor(() => {+ expect(frame.contentDocument?.querySelector("td")?.textContent).toBe("42");+ expect(frame.clientHeight).toBeGreaterThan(32);+ expect(frame.clientHeight).toBeLessThan(120);+ });+ const initialHeight = frame.clientHeight;+ await screen.rerender(+ <DocumentPages html={"<p>More saved output</p>".repeat(10)} name="Output" output />,+ );+ await vi.waitFor(() => {+ expect(frame.contentDocument?.querySelectorAll("p")).toHaveLength(10);+ expect(frame.clientHeight).toBeGreaterThan(initialHeight);+ expect(frame.contentDocument!.body.scrollHeight).toBeLessThanOrEqual(frame.clientHeight);+ });+ });++ it("preserves table content and raster data while removing scripts and network resources", () => {+ const html = sanitizeDocumentHtml(+ '<script>alert(1)</script><style>@import "https://example.com/style.css";</style><iframe src="https://example.com"></iframe><img src="https://example.com/tracker.png" onerror="alert(1)"><img src="data:image/png;base64,iVBORw0KGgo="><table><tr><td>Research</td></tr></table><a href="https://example.com">Results</a>',+ );+ const doc = new DOMParser().parseFromString(html, "text/html");+ expect(doc.querySelector("td")?.textContent).toBe("Research");+ expect(doc.images).toHaveLength(1);+ expect(doc.images[0]!.getAttribute("src")).toBe("data:image/png;base64,iVBORw0KGgo=");+ expect(doc.querySelector("script,style,iframe,a,[onerror]")).toBeNull();+ expect(html).not.toContain("https://");+ });+});it("opens a known empty attachment even when its range response is inaccessible", async () => {refresh.mockResolvedValue("https://unreachable.invalid/empty.txt");await using screen = await render(@@ -2295,3 +2330,432 @@ it("toggles a Mermaid attachment between diagram and source through the lazy pre);expect(screen.container.querySelector('[role="alert"]')).toBeNull();});++it("navigates, searches, zooms, and selects mixed-height PDF pages", async () => {+ const objects = [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Count 3 /Kids [3 0 R 5 0 R 7 0 R] >>",+ ];+ for (const [index, title] of [+ "Quarterly outlook",+ "Delivery milestones",+ "Budget and risks",+ ].entries()) {+ const text = `/GS1 gs BT /F1 24 Tf 30 ${index === 0 ? 70 : 700} Td ${index === 0 ? "(Quarter) Tj /F2 24 Tf (ly outlook) Tj" : `(${title}) Tj`} ET`;+ objects.push(+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 ${index === 0 ? 140 : 792}] /Rotate ${index === 2 ? 90 : 0} /Resources << /Font << /F1 9 0 R /F2 10 0 R >> /ExtGState << /GS1 << /TR << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >> >> >> >> /Contents ${4 + index * 2} 0 R >>`,+ `<< /Length ${text.length} >>\nstream\n${text}\nendstream`,+ );+ }+ objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");+ objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>");+ let source = "%PDF-1.4\n";+ const offsets = [0];+ for (const [index, object] of objects.entries()) {+ offsets.push(source.length);+ source += `${index + 1} 0 obj\n${object}\nendobj\n`;+ }+ const xref = source.length;+ source += `xref\n0 11\n0000000000 65535 f \n${offsets+ .slice(1)+ .map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)+ .join("")}trailer\n<< /Size 11 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;+ const file = new Blob([source], { type: "application/pdf" });+ const { default: PdfViewer } = await import("./PdfViewer");+ const url = URL.createObjectURL(file);+ try {+ await using screen = await render(+ <div style={{ display: "flex", height: 600, width: 320 }}>+ <PdfViewer src={url} title="Planning PDF" />+ </div>,+ );+ await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"), {+ timeout: 15_000,+ });+ const region = screen.container.querySelector<HTMLElement>('[role="region"]')!;+ await vi.waitFor(() => {+ expect(region.scrollWidth).toBe(region.clientWidth);+ expect(region.querySelector("canvas")!.getBoundingClientRect().width).toBeLessThan(+ region.clientWidth,+ );+ expect(screen.container.textContent).toContain("Fit width");+ });+ await act(() => {+ (screen.container.firstElementChild as HTMLElement).style.width = "500px";+ });+ await vi.waitFor(() =>+ expect(region.querySelector("canvas")!.getBoundingClientRect().width).toBe(468),+ );+ await screen.getByRole("button", { name: "Next page", exact: true }).click();+ await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));+ await screen.getByRole("button", { name: "Previous page", exact: true }).click();+ await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"));+ await screen.getByRole("button", { name: "Zoom in", exact: true }).click();+ await vi.waitFor(() => expect(region.scrollWidth).toBeGreaterThan(region.clientWidth));+ await screen.getByRole("button", { name: "Fit width", exact: true }).click();+ await vi.waitFor(() => expect(region.scrollWidth).toBe(region.clientWidth));+ await screen.getByRole("searchbox", { name: "Find in PDF" }).fill("Quarterly outlook");+ await vi.waitFor(() => {+ expect(screen.container.querySelector('[role="status"]')?.textContent).toBe("1/1");+ expect(+ Array.from(region.querySelectorAll(".pdf-find-match")).map((span) => span.textContent),+ ).toEqual(["Quarter", "ly outlook"]);+ });+ await screen.getByRole("searchbox", { name: "Find in PDF" }).fill("Budget");+ await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));+ await screen.getByRole("button", { name: "Zoom in", exact: true }).click();+ await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));+ await vi.waitFor(() => {+ const span = Array.from(screen.container.querySelectorAll("[data-pdf-text-layer] span")).find(+ (node) => node.textContent === "Budget and risks",+ );+ expect(span).toBeDefined();+ const textBounds = span!.getBoundingClientRect();+ const pageBounds = span!.parentElement!.getBoundingClientRect();+ expect(textBounds.width).toBeGreaterThan(0);+ expect(textBounds.height).toBeGreaterThan(0);+ expect(textBounds.left).toBeGreaterThanOrEqual(pageBounds.left - 1);+ expect(textBounds.top).toBeGreaterThanOrEqual(pageBounds.top - 1);+ expect(textBounds.right).toBeLessThanOrEqual(pageBounds.right + 1);+ expect(textBounds.bottom).toBeLessThanOrEqual(pageBounds.bottom + 1);+ const range = document.createRange();+ range.selectNodeContents(span!);+ const selection = window.getSelection()!;+ selection.removeAllRanges();+ selection.addRange(range);+ expect(selection.toString()).toBe("Budget and risks");+ expect(getComputedStyle(span!).userSelect).toBe("text");+ selection.removeAllRanges();+ });+ await screen.getByRole("button", { name: "Fit width", exact: true }).click();+ await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));+ await screen.getByRole("searchbox", { name: "Find in PDF" }).fill(" ");+ await vi.waitFor(() =>+ expect(screen.container.querySelector('[role="status"]')?.textContent).toBe("0/0"),+ );+ } finally {+ URL.revokeObjectURL(url);+ }+});+it("mounts a bounded set of saved notebook outputs as the reader scrolls", async () => {+ const notebook = {+ nbformat: 4,+ metadata: {},+ cells: Array.from({ length: 20 }, (_, cell) => ({+ cell_type: "code",+ source: [],+ metadata: {},+ outputs: Array.from({ length: 100 }, (_, output) => ({+ output_type: "display_data",+ data: { "text/html": `<p>saved ${cell}-${output}</p>` },+ })),+ })),+ };+ const file = new Blob([JSON.stringify(notebook)]);+ await using screen = await render(+ <div style={{ display: "flex", height: 400, width: 600 }}>+ <AttachmentFilePreview+ name="observations.ipynb"+ mimeType="application/json"+ sizeBytes={file.size}+ file={file}+ />+ </div>,+ );+ await vi.waitFor(() =>+ expect(screen.container.querySelectorAll("iframe").length).toBeGreaterThan(0),+ );+ expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16);+ const first = screen.container.querySelector("iframe")!;+ expect(first.srcdoc).toContain("saved 0-0");+ const viewport = screen.container.querySelector<HTMLElement>(".scrollbar-gutter-both")!;+ await act(() => {+ viewport.scrollTop = viewport.scrollHeight;+ });+ await vi.waitFor(() => {+ expect(+ [...screen.container.querySelectorAll("iframe")].some((frame) =>+ frame.srcdoc.includes("saved 19-99"),+ ),+ ).toBe(true);+ expect(first.isConnected).toBe(false);+ });+ expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16);+ await act(() => {+ viewport.scrollTop = 0;+ });+ await vi.waitFor(() =>+ expect(screen.container.querySelector("iframe")?.srcdoc).toContain("saved 0-0"),+ );+});++it.each([+ [String.raw`{\rtf1\uc1\u945{\b bold}Hello}`, "αboldHello"],+ [String.raw`{\rtf1\uc1{\u945}Hello}`, "αHello"],+ [+ String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset204 Cyrillic;}{\f1\fcharset0 Latin;}}\f0\'c0{\f1\'c0}\'c1}`,+ "АÀБ",+ ],+ [String.raw`{\rtf1\ansi\deff1{\fonttbl{\f1\fcharset204 Cyrillic;}}\'c0\plain\'c1}`, "АБ"],+])("retains RTF grouped Unicode and font text in %s", async (source, expected) => {+ const { openRtf } = await import("./extendedDocumentPreview");+ const result = openRtf(new TextEncoder().encode(source).buffer);+ if (result.type !== "document") throw new Error("Expected rich text document");+ const html = result.pages.map((page) => page.html).join("");+ expect(new DOMParser().parseFromString(html, "text/html").body.textContent).toBe(expected);+});++it.each(["odt", "odp"] as const)("preserves rendered %s spaces and tabs", async (kind) => {+ const archive = new JSZip().file(+ "content.xml",+ `<office:document>${kind === "odt" ? "<office:text>" : "<draw:page>"}<text:p>A<text:s text:c="3"/>B<text:tab/>C</text:p>${kind === "odt" ? "</office:text>" : "</draw:page>"}</office:document>`,+ );+ 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, bytes }, [bytes]);+ });+ if (result.type !== "document") throw new Error("Expected document");+ await using screen = await render(+ <DocumentPages html={result.pages[0]!.html} name="spacing" output />,+ );+ await vi.waitFor(() => {+ const doc = screen.container.querySelector("iframe")?.contentDocument;+ const spans = doc?.querySelectorAll<HTMLElement>("span[data-odf-whitespace]");+ expect(doc?.querySelector("p")?.textContent).toBe("A B\tC");+ expect(spans).toHaveLength(2);+ for (const span of spans!) {+ expect(doc!.defaultView!.getComputedStyle(span).whiteSpace).toBe("pre-wrap");+ expect(span.getBoundingClientRect().width).toBeGreaterThan(0);+ }+ expect(spans![0]!.getBoundingClientRect().width).toBeGreaterThan(10);+ });+ } finally {+ worker.terminate();+ }+});++it.each(["rtf", "epub", "ods"] as const)(+ "preserves %s document text through the worker and attachment viewer",+ async (kind) => {+ const archive = new JSZip();+ if (kind === "epub") {+ archive.file(+ "META-INF/container.xml",+ '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',+ );+ archive.file(+ "book.opf",+ '<package><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>',+ );+ archive.file(+ "chapter.xhtml",+ "<html><head><title>Handbook</title></head><body><p>first<br/>second<br/>third</p><hr/></body></html>",+ );+ } else if (kind === "ods") {+ archive.file(+ "content.xml",+ '<office:document><table:table table:name="Forecast"><table:table-row><table:table-cell><text:p>North<office:annotation><text:p>nested note</text:p></office:annotation></text:p><office:annotation><text:p>private note</text:p></office:annotation></table:table-cell><table:table-cell office:value="150"><office:annotation><text:p>revised from 120</text:p></office:annotation></table:table-cell><table:table-cell table:number-columns-repeated="1024"/></table:table-row><table:table-row table:number-rows-repeated="1048570"><table:table-cell table:number-columns-repeated="1024"/></table:table-row></table:table></office:document>',+ );+ }+ const file =+ kind === "rtf"+ ? new Blob([+ String.raw`{\rtf1\ansi 10\endash 20 \emdash \bullet \lquote a\rquote \ldblquote b\rdblquote\par Name\cell Value\cell\row 12\cell 34\cell\row{\*\private hidden\endash\cell\row}Unicode:\u8211\endash end}`,+ ])+ : await archive.generateAsync({ type: "blob" });+ const bytes = await file.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, bytes }, [bytes]);+ });+ if (kind === "ods") {+ expect(result.type).toBe("ods");+ if (result.type !== "ods") throw new Error("Expected spreadsheet");+ expect(result.sheets[0]!.rows).toEqual([["North", "150"]]);+ } else {+ expect(result.type).toBe("document");+ if (result.type !== "document") throw new Error("Expected document");+ const body = new DOMParser().parseFromString(result.pages[0]!.html, "text/html").body;+ if (kind === "epub") {+ expect(body.querySelectorAll("br")).toHaveLength(2);+ expect(body.querySelectorAll("hr")).toHaveLength(1);+ } else {+ expect(body.textContent).toContain("10–20 —•‘a’“b”");+ expect(body.textContent).toContain("Name\tValue\t12\t34\t");+ expect(body.textContent).toContain("Unicode:–end");+ expect(body.textContent).not.toContain("hidden");+ expect(body.querySelectorAll("br")).toHaveLength(3);+ }+ }+ } finally {+ worker.terminate();+ }+ await using screen = await render(+ <div style={{ display: "flex", height: 400, width: 600 }}>+ <AttachmentFilePreview+ name={`report.${kind}`}+ mimeType="application/octet-stream"+ sizeBytes={file.size}+ file={file}+ />+ </div>,+ );+ await vi.waitFor(() => {+ if (kind === "ods") {+ expect(screen.container.textContent).toContain("North");+ expect(screen.container.textContent).toContain("150");+ expect(screen.container.textContent).not.toContain("private note");+ expect(screen.container.textContent).toContain("1 rows · 2 columns");+ expect(screen.container.textContent).not.toContain("Limited to 500");+ } else {+ const frame = screen.container.querySelector("iframe");+ expect(frame?.srcdoc).toContain(kind === "rtf" ? "10–20" : "first<br>second<br>third");+ }+ });+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();+ },+);++it.each(["epub", "odt", "ipynb", "html", "encoded-html"] as const)(+ "bounds %s image pixels before returning browser markup",+ async (kind) => {+ const canvas = new OffscreenCanvas(2, 3);+ canvas.getContext("2d");+ const blob = await canvas.convertToBlob({ type: "image/png" });+ for (const width of [2, 12000]) {+ const image = await blob.arrayBuffer();+ new DataView(image).setUint32(16, width);+ new DataView(image).setUint32(20, width === 2 ? 3 : 12000);+ const archive = new JSZip();+ archive.file("cover.png", image);+ if (kind === "epub") {+ archive.file(+ "META-INF/container.xml",+ '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',+ );+ archive.file(+ "book.opf",+ '<package><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>',+ );+ archive.file(+ "chapter.xhtml",+ '<html><body><p>retained caption</p><img src="cover.png"/></body></html>',+ );+ } else+ archive.file(+ "content.xml",+ '<office:document><office:text><text:p>retained caption</text:p><draw:image xlink:href="cover.png"/></office:text></office:document>',+ );+ const base64 = btoa(String.fromCharCode(...new Uint8Array(image)));+ const bytes =+ kind === "ipynb" || kind === "html" || kind === "encoded-html"+ ? new TextEncoder().encode(+ JSON.stringify({+ nbformat: 4,+ cells: [+ {+ cell_type: "code",+ source: "plot()",+ outputs: [+ {+ data: {+ ...(kind === "html" || kind === "encoded-html"+ ? {+ "text/html": `<table><tr><td>retained caption</td></tr></table><img src="${kind === "encoded-html" ? "data" : "data"}:image/png;base64,${base64}">`,+ }+ : { "image/png": base64 }),+ "text/plain": "retained caption",+ },+ },+ ],+ },+ ],+ }),+ ).buffer+ : 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: kind === "html" || kind === "encoded-html" ? "ipynb" : kind,+ bytes,+ },+ [bytes],+ );+ });+ if (result.type === "notebook") {+ const output = result.cells[0]!.outputs[0]!;+ expect(output.kind).toBe(+ width === 2 ? (kind === "html" || kind === "encoded-html" ? "html" : "image") : "text",+ );+ if (output.kind === "html") {+ const rendered = new DOMParser().parseFromString(+ sanitizeDocumentHtml(output.text),+ "text/html",+ );+ expect(rendered.images).toHaveLength(1);+ expect(rendered.querySelector("td")!.textContent).toBe("retained caption");+ }+ if (width !== 2) expect(result.cells[0]!.outputs[0]!.text).toBe("retained caption");+ } else {+ expect(result.type).toBe("document");+ if (result.type !== "document") throw new Error("Expected document");+ expect(result.pages[0]!.html.includes("<img")).toBe(width === 2);+ expect(result.pages[0]!.html).toContain("retained caption");+ }+ } finally {+ worker.terminate();+ }+ }+ },+);++it.each([+ ["standardFontDataUrl", "FoxitSerif.pfb", "standard_fonts"],+ ["cMapUrl", "78-EUC-H.bcmap", "cmaps"],+ ["wasmUrl", "openjpeg.wasm", "wasm"],+])("validates PDF %s assets before decoding", async (kind, filename, directory) => {+ const { BinaryDataFactory } = await import("./pdfDocument");+ const factory = new BinaryDataFactory();+ const fetchAsset = vi.fn(+ async () =>+ new Response("<html>app</html>", {+ headers: { "content-type": "text/html; charset=utf-8" },+ }),+ );+ using _fetch = stubGlobal("fetch", fetchAsset);+ await expect(factory.fetch({ kind, filename })).rejects.toThrow(+ `PDF ${directory} asset unavailable.`,+ );+ fetchAsset.mockImplementation(async () => new Response(new Uint8Array([1, 2, 3])));+ await expect(factory.fetch({ kind, filename })).resolves.toEqual(new Uint8Array([1, 2, 3]));+ await expect(factory.fetch({ kind, filename: "missing" })).rejects.toThrow(+ `Unsupported PDF ${directory} asset.`,+ );+});diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsxindex 670695cf5a3..ab7b67a609f 100644--- a/apps/web/src/components/files/BrowserDocumentFrame.tsx+++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx@@ -22,7 +22,17 @@ import {matchesKeybindingShortcut,normalizeEventKey,} from "@t3tools/shared/keybindings";-import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";+import {+ lazy,+ Suspense,+ useEffect,+ useEffectEvent,+ useLayoutEffect,+ useRef,+ useState,+} from "react";+import { isElectron } from "~/env";+import { FileSurfaceLoading } from "./fileSurfaceChrome";import { useOpenLink } from "~/browser/useOpenLink";import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";@@ -61,9 +71,34 @@ const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([export const isPdfPreviewFile = (path: string): boolean =>/\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");+const PdfViewer = lazy(() => import("./PdfViewer"));++function PdfDocument(props: { src: string; title: string }) {+ const [src] = useState(props.src);+ // The Electron shell does not enable PDF plugins. WebKit embeds on iOS+ // expose only the first page, even when pdfViewerEnabled reports support.+ const native =+ !isElectron &&+ navigator.pdfViewerEnabled &&+ !/iPad|iPhone|iPod/.test(navigator.userAgent) &&+ !(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);+ return native ? (+ // oxlint-disable-next-line react/iframe-missing-sandbox -- Chromium's PDF plugin requires an unsandboxed frame; src is an exact-file asset grant.+ <iframe+ src={`${src.split("#", 1)[0]}#navpanes=0&view=FitH`}+ title={props.title}+ className="block h-full min-h-0 w-full flex-1 border-0 bg-white"+ />+ ) : (+ <Suspense fallback={<FileSurfaceLoading />}>+ <PdfViewer src={src} title={props.title} />+ </Suspense>+ );+}+/*** HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach- * the app's session or storage. PDFs use the browser's native viewer.+ * the app's session or storage. PDFs use a native viewer or the lazy PDF.js fallback.*/export function BrowserDocumentFrame(props: {readonly src: string;@@ -76,13 +111,7 @@ export function BrowserDocumentFrame(props: {}) {const key = props.documentKey ?? props.src;return props.pdf ? (- <embed- key={props.src}- src={props.src}- type="application/pdf"- title={props.title}- className="min-h-0 w-full flex-1 border-0"- />+ <PdfDocument key={key} src={props.src} title={props.title} />) : props.htmlRender ? (<HtmlRenderDocumentkey={key}diff --git a/apps/web/src/components/files/DocumentPages.tsx b/apps/web/src/components/files/DocumentPages.tsxnew file mode 100644index 00000000000..02715be64fb--- /dev/null+++ b/apps/web/src/components/files/DocumentPages.tsx@@ -0,0 +1,145 @@+import DOMPurify from "dompurify";+import { MinusIcon, PlusIcon, RotateCcwIcon } from "lucide-react";+import { FileSurfaceAction } from "./fileSurfaceChrome";+import { useEffect, useRef, useState } from "react";+import { useTheme } from "~/hooks/useTheme";+import { observeResize } from "~/lib/observeResize";++export function sanitizeDocumentHtml(source: string): string {+ const fragment = DOMPurify.sanitize(source, {+ RETURN_DOM_FRAGMENT: true,+ ALLOWED_TAGS: [+ "p",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "div",+ "span",+ "strong",+ "b",+ "em",+ "i",+ "u",+ "s",+ "ul",+ "ol",+ "li",+ "blockquote",+ "pre",+ "code",+ "table",+ "thead",+ "tbody",+ "tr",+ "th",+ "td",+ "caption",+ "figure",+ "figcaption",+ "br",+ "hr",+ "sub",+ "sup",+ "dl",+ "dt",+ "dd",+ "img",+ ],+ ALLOWED_ATTR: ["src", "alt", "colspan", "rowspan", "data-odf-whitespace"],+ });+ for (const image of fragment.querySelectorAll("img")) {+ if (+ !/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/]*={0,2}$/i.test(+ image.getAttribute("src") ?? "",+ )+ )+ image.remove();+ }+ const container = document.createElement("div");+ container.append(fragment);+ return container.innerHTML;+}++function documentColors() {+ const style = getComputedStyle(document.documentElement);+ return ["background", "foreground", "card", "border"].map((token) =>+ style.getPropertyValue(`--${token}`),+ );+}++export default function DocumentPages(props: {+ readonly html: string;+ readonly name: string;+ readonly output?: boolean;+ readonly details?: string;+}) {+ const { theme, resolvedTheme, themeHalves } = useTheme();+ const [colors, setColors] = useState(documentColors);+ // oxlint-disable-next-line t3code/react-effect-budget -- Read the host DOM's applied theme tokens so the sandboxed document receives the current palette.+ useEffect(() => {+ // The iframe cannot inherit the host palette across its sandbox boundary.+ // oxlint-disable-next-line react/set-state-in-effect -- Read tokens after useTheme applies the selected palette.+ setColors(documentColors());+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Theme values invalidate the palette read from the host DOM.+ }, [theme, resolvedTheme, themeHalves]);+ const [zoom, setZoom] = useState(1);+ const [outputHeight, setOutputHeight] = useState(0);+ const stopObserving = useRef<(() => void) | null>(null);+ // oxlint-disable-next-line t3code/react-effect-budget -- Disconnect the iframe body's resize observer when the document unmounts.+ useEffect(() => () => stopObserving.current?.(), []);+ const html = sanitizeDocumentHtml(props.html);+ const srcDoc = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><style>:root{color-scheme:${resolvedTheme}}html{background:${colors[0]};color:${colors[1]};font:${15 * zoom}px/1.65 system-ui,sans-serif}body{box-sizing:border-box;margin:${props.output ? "0" : "20px auto"};padding:${props.output ? "16px" : "32px"};width:${props.output ? "100%" : "calc(100% - 40px)"};max-width:${860 * zoom}px;min-height:${props.output ? "0" : "calc(100vh - 40px)"};display:flow-root;background:${colors[2]};overflow-wrap:anywhere}h1,h2,h3{line-height:1.25}img{max-width:100%;height:auto}table{border-collapse:collapse;min-width:100%;max-width:100%}td,th{border:1px solid ${colors[3]};padding:6px 12px;text-align:left}th{background:${colors[0]}}tr:nth-child(even){background:${colors[0]}}pre,span[data-odf-whitespace]{white-space:pre-wrap}*{scrollbar-width:thin}${props.output ? "" : "@media(max-width:420px){body{padding:20px;width:calc(100% - 24px);margin:12px auto}}"}</style></head><body>${html}</body></html>`;+ return (+ <>+ {!props.output ? (+ <div className="flex min-h-10 shrink-0 flex-wrap items-center gap-1 border-b border-border/60 px-3 py-1 text-xs text-muted-foreground">+ <span className="min-w-0 flex-1 text-muted-foreground tabular-nums" role="status">+ {props.details}+ </span>+ <FileSurfaceAction+ label="Decrease reading size"+ disabled={zoom <= 0.5}+ onPress={() => setZoom((value) => Math.max(0.5, value - 0.25))}+ >+ <MinusIcon className="size-3.5" />+ </FileSurfaceAction>+ <span className="min-w-10 text-center tabular-nums">{Math.round(zoom * 100)}%</span>+ <FileSurfaceAction+ label="Increase reading size"+ disabled={zoom >= 2}+ onPress={() => setZoom((value) => Math.min(2, value + 0.25))}+ >+ <PlusIcon className="size-3.5" />+ </FileSurfaceAction>+ <FileSurfaceAction+ label="Reset reading size"+ disabled={zoom === 1}+ onPress={() => setZoom(1)}+ >+ <RotateCcwIcon className="size-3.5" />+ </FileSurfaceAction>+ </div>+ ) : null}+ <iframe+ title={props.name}+ srcDoc={srcDoc}+ // Same-origin access lets the parent measure saved output; scripts remain blocked.+ sandbox={props.output ? "allow-same-origin" : ""}+ onLoad={(event) => {+ if (!props.output) return;+ stopObserving.current?.();+ const body = event.currentTarget.contentDocument?.body;+ if (!body) return;+ const measure = () => setOutputHeight(Math.ceil(body.getBoundingClientRect().height));+ stopObserving.current = observeResize(body, measure);+ measure();+ }}+ style={props.output ? { height: outputHeight } : undefined}+ className={props.output ? "block w-full border-0" : "min-h-0 flex-1 border-0"}+ />+ </>+ );+}diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.tsindex 728ae04e0b1..ddc77e5748f 100644--- a/apps/web/src/components/files/FilePreviewPanel.test.ts+++ b/apps/web/src/components/files/FilePreviewPanel.test.ts@@ -1,7 +1,9 @@+import JSZip from "jszip";+import { openRtf, openNotebook, openDocument, openEpub } from "./extendedDocumentPreview";import type { ScopedThreadRef } from "@t3tools/contracts";import { ProjectReadFileError } from "@t3tools/contracts";import * as Schema from "effect/Schema";-import { describe, expect, it } from "vite-plus/test";+import { describe, expect, it, vi } from "vite-plus/test";import { remapFileCommentAnnotations } from "./fileCommentAnnotations";import {@@ -144,3 +146,255 @@ describe("workspaceAssetResource", () => {).toEqual({ _tag: "draft-workspace-file", cwd: "/repo", path: "/tmp/screenshots/shot.png" });});});++describe("document preview contents", () => {+ const bytes = (text: string) => new TextEncoder().encode(text).buffer;++ it.each(["?", String.raw`\'3f`, String.raw`\\`])(+ "consumes skipped rich text Unicode fallback %s",+ (fallback) => {+ const result = openRtf(bytes(String.raw`{\rtf1{\*\unknown\u945` + fallback + "}Hello}"));+ if (result.type !== "document") throw new Error("Expected document");+ expect(result.pages[0]!.html).toBe("<p>Hello</p>");+ },+ );++ it("bounds EPUB markup made entirely of empty allowed elements", async () => {+ const archive = new JSZip()+ .file(+ "META-INF/container.xml",+ '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',+ )+ .file(+ "book.opf",+ '<package><manifest><item id="a" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine>' ++ '<itemref idref="a"/>'.repeat(30) ++ "</spine></package>",+ )+ .file("chapter.xhtml", "<html><body>" + "<figcaption/>".repeat(30_000) + "</body></html>");+ await expect(openEpub(archive)).rejects.toThrow("too large");+ });++ it("decodes rich text formatting and Unicode without showing hidden destinations", () => {+ const result = openRtf(+ bytes(+ String.raw`{\rtf1\ansi{\fonttbl{\f0 Hidden font;}}Hello \b bold\b0\par Unicode: \u945?{\*\unknown hidden}{\field{\*\fldinst HYPERLINK "https://example.com"}{\fldrslt visible}}}`,+ ),+ );+ expect(result.type).toBe("document");+ if (result.type !== "document") throw new Error("Expected document");+ const html = result.pages[0]!.html;+ expect(html.replaceAll(/<[^>]*>/g, "")).toBe("Hello boldUnicode: αvisible");+ expect(html).toContain("<strong>");+ expect(html).not.toContain("https:");+ });++ it("preserves rich text page breaks and formatting without splitting hidden destinations", () => {+ const result = openRtf(+ bytes(String.raw`{\rtf1\b First\page Second\b0{\*\unknown \page hidden}\page Third\page}`),+ );+ if (result.type !== "document") throw new Error("Expected document");+ expect(result.navigation).toBe("page");+ expect(result.pages.map((page) => page.html)).toEqual([+ "<p><strong>First</strong></p>",+ "<p><strong>Second</strong></p>",+ "<p>Third</p>",+ ]);+ expect(() => openRtf(bytes(String.raw`{\rtf1 ` + String.raw`\page`.repeat(501) + "}"))).toThrow(+ "500 pages",+ );+ });++ it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => {+ const input = new TextEncoder().encode(+ String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`,+ );+ input[input.indexOf(65)] = 0xc0;+ const result = openRtf(input.buffer);+ if (result.type !== "document") throw new Error("Expected document");+ expect(result.pages[0]!.html).toBe("<p>А А<br>あ</p>");+ expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow("code page");+ });++ it("resolves scoped ODF namespaces and explicit spreadsheet whitespace", async () => {+ const archive = new JSZip().file(+ "content.xml",+ '<o:document-content xmlns:o="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:t="urn:oasis:names:tc:opendocument:xmlns:table:1.0"><o:body><o:spreadsheet><t:table t:name="Accounts & names"><t:table-row><t:table-cell><p xmlns="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:x="urn:oasis:names:tc:opendocument:xmlns:text:1.0">Account<s/>Name<s x:c="3"/>A<tab/>B<line-break/>C</p></t:table-cell></t:table-row></t:table></o:spreadsheet></o:body></o:document-content>',+ );+ const result = await openDocument(archive, "ods");+ if (result.type !== "ods") throw new Error("Expected workbook");+ expect(result.sheets[0]!.name).toBe("Accounts & names");+ expect(result.sheets[0]!.rows[0]).toEqual(["Account Name A\tB\nC"]);+ });++ it("stops repeated slide images before encoding beyond the output budget", async () => {+ const pixels = new Uint8Array(4 * 1024 * 1024);+ pixels.set(+ Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",+ "base64",+ ),+ );+ const archive = new JSZip()+ .file(+ "content.xml",+ '<o:document-content xmlns:o="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:d="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:l="http://www.w3.org/1999/xlink"><o:body>' ++ '<d:page><d:image l:href="picture.png"/></d:page>'.repeat(500) ++ "</o:body></o:document-content>",+ )+ .file("picture.png", pixels);+ const image = archive.file("picture.png")!;+ const read = vi.spyOn(image, "async");+ await expect(openDocument(archive, "odp")).rejects.toThrow("too large");+ expect(read.mock.calls.filter(([type]) => type === "base64")).toHaveLength(2);+ expect(read).toHaveBeenCalledTimes(5);+ });++ it("reads saved notebook cells and preferred outputs without executing code", () => {+ const result = openNotebook(+ bytes(+ JSON.stringify({+ nbformat: 4,+ metadata: { language_info: { name: "python" } },+ cells: [+ { cell_type: "markdown", source: ["# Results"] },+ {+ cell_type: "code",+ source: ["print(42)"],+ outputs: [+ { output_type: "stream", text: ["\n "] },+ { output_type: "display_data", data: {} },+ { data: { "text/html": [""] } },+ { data: { "text/html": [], "text/plain": "array fallback" } },+ { data: { "text/html": "", "text/plain": "string fallback" } },+ { data: { "text/html": " ", "text/plain": "space fallback" } },+ { output_type: "stream", text: ["42\n"] },+ { data: { "text/html": ["<b>Results</b>"], "text/plain": ["Results"] } },+ ],+ },+ ],+ }),+ ),+ );+ expect(result).toEqual({+ type: "notebook",+ language: "python",+ cells: [+ { kind: "markdown", source: "# Results", outputs: [] },+ {+ kind: "code",+ source: "print(42)",+ outputs: [+ { kind: "text", text: "array fallback" },+ { kind: "text", text: "string fallback" },+ { kind: "text", text: "space fallback" },+ { kind: "text", text: "42\n" },+ { kind: "html", text: "<b>Results</b>" },+ ],+ },+ ],+ });+ expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow("version 4");+ expect(() =>+ openNotebook(+ bytes(JSON.stringify({ nbformat: 4, cells: Array.from({ length: 501 }, () => ({})) })),+ ),+ ).toThrow("500 cells");+ });++ it("bounds repeated OpenDocument spreadsheet cells and keeps sheet names and values", async () => {+ const archive = new JSZip().file(+ "content.xml",+ '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet><table:table table:name="Budget"><table:table-row table:number-rows-repeated="999999999"><table:table-cell table:number-columns-repeated="999999999"><text:p>Research & design</text:p></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>',+ );+ const result = await openDocument(archive, "ods");+ expect(result.type).toBe("ods");+ if (result.type !== "ods") throw new Error("Expected workbook");+ expect(result.sheets[0]!.name).toBe("Budget");+ expect(result.sheets[0]!.truncated).toBe(true);+ expect(result.sheets[0]!.rows).toHaveLength(500);+ expect(result.sheets[0]!.rows[0]).toHaveLength(50);+ expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design");+ });++ it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {+ const archive = new JSZip().file(+ "content.xml",+ `<office:document><table:table><table:table-row table:number-rows-repeated="${count}"><table:table-cell><text:p>North</text:p></table:table-cell><table:table-cell table:number-columns-repeated="1024"/></table:table-row><table:table-row table:number-rows-repeated="1048570"><table:table-cell table:number-columns-repeated="1024"/></table:table-row></table:table></office:document>`,+ );+ const result = await openDocument(archive, "ods");+ if (result.type !== "ods") throw new Error("Expected workbook");+ expect(result.sheets[0]).toMatchObject({ rowCount: count, columns: 1, truncated: false });+ expect(result.sheets[0]!.rows).toEqual(Array.from({ length: count }, () => ["North"]));+ });++ it.each([2, 999999])(+ "preserves internal ODS gaps of %s rows and reports real overflow",+ async (gap) => {+ const archive = new JSZip().file(+ "content.xml",+ `<office:document><table:table><table:table-row><table:table-cell><text:p>First</text:p></table:table-cell></table:table-row><table:table-row table:number-rows-repeated="${gap}"><table:table-cell/></table:table-row><table:table-row><table:table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Last</text:p></table:table-cell></table:table-row></table:table></office:document>`,+ );+ const result = await openDocument(archive, "ods");+ if (result.type !== "ods") throw new Error("Expected workbook");+ expect(result.sheets[0]).toMatchObject({+ rowCount: Math.min(gap + 2, 500),+ columns: gap === 2 ? 3 : 1,+ truncated: gap !== 2,+ });+ expect(result.sheets[0]!.rows[1]).toEqual([]);+ if (gap === 2) expect(result.sheets[0]!.rows[3]).toEqual(["", "", "Last"]);+ },+ );++ it.each(["odt", "odp"] as const)("reads %s text and rejects XML entities", async (kind) => {+ const archive = new JSZip().file(+ "content.xml",+ `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"><office:body>${kind === "odt" ? "<office:text><text:p>Field notes</text:p></office:text>" : '<draw:page draw:name="Overview"><text:h>Launch plan</text:h></draw:page>'}</office:body></office:document-content>`,+ );+ const result = await openDocument(archive, kind);+ expect(result.type).toBe("document");+ if (result.type !== "document") throw new Error("Expected document");+ expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan");+ archive.file(+ "content.xml",+ '<!DOCTYPE x [<!ENTITY external SYSTEM "file:///etc/passwd">]><x>&external;</x>',+ );+ await expect(openDocument(archive, kind)).rejects.toThrow("unsupported XML");+ });++ it("reads EPUB chapters in spine order and removes active and remote content", async () => {+ const archive = new JSZip()+ .file(+ "META-INF/container.xml",+ '<container><rootfiles><rootfile full-path="Book/book.opf"/></rootfiles></container>',+ )+ .file(+ "Book/book.opf",+ '<package><manifest><item id="a" href="one.xhtml" media-type="application/xhtml+xml"/><item id="b" href="two&&&.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',+ )+ .file(+ "Book/one.xhtml",+ '<html><head><title>First</title></head><body><h1>First chapter</h1><img src="cover.png" alt="Cover"/><img src="https://example.com/tracker.png"/><script>alert(1)</script><style>@import "https://example.com/style.css";</style></body></html>',+ )+ .file(+ "Book/two&&&.xhtml",+ '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head><title>Second</title></head><body><h1>Second chapter</h1><p>A B © — ≂̸ &lt;</p><img src="cover.png" alt="© ≂̸"/></body></html>',+ )+ .file(+ "Book/cover.png",+ Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",+ "base64",+ ),+ );+ const result = await openEpub(archive);+ expect(result.type).toBe("document");+ if (result.type !== "document") throw new Error("Expected document");+ expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]);+ expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &lt;");+ expect(result.pages[0]!.html).toContain('alt="© ≂̸"');+ expect(result.pages[1]!.html).toContain('src="data:image/png;base64,');+ expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/);+ });+});diff --git a/apps/web/src/components/files/NotebookPreview.tsx b/apps/web/src/components/files/NotebookPreview.tsxnew file mode 100644index 00000000000..c32b9f84cd2--- /dev/null+++ b/apps/web/src/components/files/NotebookPreview.tsx@@ -0,0 +1,182 @@+/* oxlint-disable react/no-array-index-key -- Notebook cells and outputs retain their saved source order. */+import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";+import { useEffect, useRef, useState } from "react";+import type { Root, RootContent } from "mdast";+import ChatMarkdown from "~/components/ChatMarkdown";+import { Button } from "~/components/ui/button";+import ReadOnlySourcePreview from "./ReadOnlySourcePreview";+import DocumentPages from "./DocumentPages";+import { FileSurfaceNotice } from "./fileSurfaceChrome";+import type { OfficeWorkerResult } from "./officePreviewProtocol";++// Saved notebooks must not load URLs or turn authored links into app actions.+function inertNotebookMarkdown() {+ function clean(nodes: RootContent[]): RootContent[] {+ return nodes.flatMap((node): RootContent[] => {+ if (node.type === "html" || node.type === "definition") return [];+ if (node.type === "image" || node.type === "imageReference")+ return [{ type: "text", value: node.alt ?? "" }];+ if (node.type === "link" || node.type === "linkReference") return clean(node.children);+ if (node.type === "inlineCode") return [{ type: "text", value: node.value }];+ if (node.type === "code" && node.lang === "mermaid") return [{ ...node, lang: "text" }];+ if ("children" in node) node.children = clean(node.children) as typeof node.children;+ return [node];+ });+ }+ return (tree: Root) => {+ tree.children = clean(tree.children) as Root["children"];+ };+}+const NOTEBOOK_PLUGINS = [inertNotebookMarkdown];++function NotebookSource(props: { readonly name: string; readonly text: string }) {+ const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16));+ const measure = (node: HTMLElement) => {+ setHeight(Math.min(360, Math.ceil(node.getBoundingClientRect().height)));+ };+ return (+ <div className="flex min-h-0 flex-col" style={{ height }}>+ <ReadOnlySourcePreview {...props} onPostRender={measure} />+ </div>+ );+}++export default function NotebookPreview(props: {+ readonly notebook: Extract<OfficeWorkerResult, { type: "notebook" }>;+ readonly sizeBytes?: number | undefined;+}) {+ const [visible, setVisible] = useState(20);+ const scroll = useRef<HTMLDivElement>(null);+ const [outputView, setOutputView] = useState(() => ({+ mounted: new Set<string>(),+ heights: new Map<string, number>(),+ }));+ const outputCount = props.notebook.cells+ .slice(0, visible)+ .reduce(+ (count, cell) => count + cell.outputs.filter((output) => output.kind === "html").length,+ 0,+ );+ // oxlint-disable-next-line t3code/react-effect-budget -- Observe output visibility and measure departing outputs to bound iframe lifetimes while preserving scroll height.+ useEffect(() => {+ const root = scroll.current;+ if (!root || !outputCount) return;+ const candidates = new Map<Element, string>();+ let active: Element[] = [];+ const observer = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting)+ candidates.set(entry.target, (entry.target as HTMLElement).dataset.notebookOutput!);+ else candidates.delete(entry.target);+ }+ // Bound browsing contexts even when a cell contains hundreds of tiny HTML outputs.+ const next = [...candidates.keys()].slice(0, 16);+ const measured = active+ .filter((node) => !next.includes(node))+ .map(+ (node) =>+ [+ (node as HTMLElement).dataset.notebookOutput!,+ node.getBoundingClientRect().height,+ ] as const,+ );+ active = next;+ setOutputView((old) => ({+ mounted: new Set(next.map((node) => candidates.get(node)!)),+ heights: new Map([...old.heights, ...measured]),+ }));+ },+ { root, rootMargin: "160px" },+ );+ for (const node of root.querySelectorAll("[data-notebook-output]")) observer.observe(node);+ return () => observer.disconnect();+ }, [outputCount]);+ return (+ <>+ <div+ className="border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"+ role="status"+ >+ {props.notebook.cells.length.toLocaleString()} cells · {props.notebook.language}+ {props.sizeBytes !== undefined+ ? ` · ${props.sizeBytes === 0 ? "0 bytes" : formatAttachmentSize(props.sizeBytes)}`+ : ""}+ </div>+ <FileSurfaceNotice>Saved outputs only. Code is never executed.</FileSurfaceNotice>+ <div ref={scroll} className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto">+ <div className="mx-auto max-w-4xl space-y-5 px-5 py-6">+ {props.notebook.cells.slice(0, visible).map((cell, index) => (+ <section+ key={index}+ aria-label={`Cell ${index + 1}`}+ className="min-w-0 overflow-hidden rounded-md border border-border/60"+ >+ <div className="border-b border-border/60 bg-muted/30 px-3 py-1.5 text-xs text-muted-foreground">+ {cell.kind === "code" ? props.notebook.language : cell.kind} · {index + 1}+ </div>+ {cell.kind === "markdown" ? (+ <ChatMarkdown+ text={cell.source}+ cwd={undefined}+ parseRawHtml={false}+ extraRemarkPlugins={NOTEBOOK_PLUGINS}+ className="px-4 py-3"+ />+ ) : cell.source.trim() ? (+ <NotebookSource+ name={`cell.${cell.kind === "code" ? (({ python: "py", javascript: "js", typescript: "ts", julia: "jl" } as Record<string, string>)[props.notebook.language] ?? props.notebook.language) : "txt"}`}+ text={cell.source}+ />+ ) : null}+ {cell.outputs.map((output, outputIndex) => (+ <div+ key={outputIndex}+ data-notebook-output={+ output.kind === "html" ? `${index}-${outputIndex}` : undefined+ }+ className="border-t border-border/60"+ style={{+ minHeight:+ output.kind !== "html" || outputView.mounted.has(`${index}-${outputIndex}`)+ ? undefined+ : (outputView.heights.get(`${index}-${outputIndex}`) ?? 80),+ }}+ >+ {output.kind === "html" ? (+ !outputView.mounted.has(`${index}-${outputIndex}`) ? null : (+ <DocumentPages+ html={output.text}+ name={`Cell ${index + 1} HTML output`}+ output+ />+ )+ ) : output.kind === "image" ? (+ <img+ src={output.text}+ alt={`Cell ${index + 1} output`}+ loading="lazy"+ className="max-h-96 max-w-full p-4 object-contain"+ />+ ) : (+ <pre className="overflow-x-auto p-4 text-xs whitespace-pre-wrap break-words">+ {output.text}+ </pre>+ )}+ </div>+ ))}+ </section>+ ))}+ {props.notebook.cells.length === 0 ? (+ <p className="text-sm text-muted-foreground">This notebook is empty.</p>+ ) : null}+ {visible < props.notebook.cells.length ? (+ <Button variant="outline" size="sm" onClick={() => setVisible((count) => count + 20)}>+ Show more cells ({props.notebook.cells.length - visible} remaining)+ </Button>+ ) : null}+ </div>+ </div>+ </>+ );+}diff --git a/apps/web/src/components/files/OfficeViewer.tsx b/apps/web/src/components/files/OfficeViewer.tsxindex c9e86801988..dcec1626745 100644--- a/apps/web/src/components/files/OfficeViewer.tsx+++ b/apps/web/src/components/files/OfficeViewer.tsx@@ -1,15 +1,29 @@-import { useStableCallback } from "~/hooks/useStableCallback";+/* oxlint-disable react/no-array-index-key -- Spreadsheet rows and columns retain their source positions. */+import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";import type { OfficePreviewKind } from "@t3tools/shared/filePreview";-import { lazy, Suspense, useEffect, useState } from "react";+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";+import { lazy, Suspense, useEffect, useRef, useState } from "react";++import VirtualTablePreview from "./VirtualTablePreview";+import {- FileSurfaceLoading,- FileSurfaceNotice,- FILE_SURFACE_SUBHEADER_CLASS,-} from "./fileSurfaceChrome";+ Select,+ SelectItem,+ SelectPopup,+ SelectTrigger,+ SelectValue,+} from "~/components/ui/select";++import { FileSurfaceAction, FileSurfaceLoading, FileSurfaceNotice } 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"));++const DocumentPages = lazy(() => import("./DocumentPages"));+const NotebookPreview = lazy(() => import("./NotebookPreview"));++type Workbook = Extract<OfficeWorkerResult, { type: "ods" }>;++const OpenXmlOfficeViewer = lazy(() => import("./OpenXmlOfficeViewer"));+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.");@@ -38,59 +52,108 @@ export default function OfficeViewer(props: {readonly name: string;readonly kind: OfficePreviewKind;readonly sizeBytes?: number;+}) {+ if (props.kind === "docx" || props.kind === "xlsx" || props.kind === "pptx")+ return (+ <Suspense fallback={<FileSurfaceLoading />}>+ <OpenXmlOfficeViewer {...props} kind={props.kind} />+ </Suspense>+ );+ return <ExtendedOfficeViewer {...props} />;+}++function ExtendedOfficeViewer(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."),- );+ const [sheetPages, setSheetPages] = useState(new Map<string, string[][]>());+ const pendingPages = useRef(new Set<string>());+ const [previewDocument, setDocument] = useState<Extract<+ OfficeWorkerResult,+ { type: "document" }+ > | null>(null);+ const [notebook, setNotebook] = useState<Extract<+ OfficeWorkerResult,+ { type: "notebook" }+ > | null>(null);+ const [workbook, setWorkbook] = useState<Workbook | null>(null);+ const [count, setCount] = useState(0);+ const [fileSize, setFileSize] = useState(props.sizeBytes);+ const [page, setPage] = useState(0);+ const workerRef = useRef<Worker | null>(null);+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);// 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(() => {+ const controller = new AbortController();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+ // oxlint-disable-next-line react/set-state-in-effect -- The file metadata can reject the preview before loading bytes or engines.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);+ workerRef.current = worker;+ const fail = (message: string) => {+ if (!controller.signal.aborted) setError(message);controller.abort();worker.terminate();+ if (timerRef.current) clearTimeout(timerRef.current);};- const timer = setTimeout(- () => failure(new Error("This document took too long to preview. Open it in another app.")),- 30000,+ timerRef.current = setTimeout(+ () => fail("This document took too long to preview. Open it in another app."),+ 30_000,);- 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("error", () =>+ fail("Could not load the Office viewer. Close the file and try again."),);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();+ const result = event.data;+ if (result.type === "error") fail(result.message);+ else if (result.type === "document") {+ if (timerRef.current) clearTimeout(timerRef.current);+ setDocument(result);+ setCount(result.pages.length > 1 ? result.pages.length : 0);+ } else if (result.type === "notebook") {+ if (timerRef.current) clearTimeout(timerRef.current);+ setNotebook(result);+ } else if (result.type === "ods") {+ if (timerRef.current) clearTimeout(timerRef.current);+ setWorkbook(result);+ setCount(result.sheets.length);+ } else if (result.type === "sheet-page") {+ const key = `${result.sheet}:${result.index}`;+ pendingPages.current.delete(key);+ setSheetPages((old) => {+ const next = new Map(old);+ next.set(key, result.rows);+ if (next.size > 12) next.delete(next.keys().next().value!);+ return next;+ });}});void readOfficeFile(props.src, controller.signal).then((bytes) => {- if (!controller.signal.aborted)+ if (!controller.signal.aborted) {+ setFileSize(bytes.byteLength);worker.postMessage({ type: "open", kind: props.kind, bytes }, [bytes]);+ }})- .catch(failure);+ .catch((cause: unknown) =>+ fail(cause instanceof Error ? cause.message : "Could not read this file."),+ );return () => {controller.abort();worker.terminate();- clearTimeout(timer);+ workerRef.current = null;+ if (timerRef.current) clearTimeout(timerRef.current);};- }, [props.src, props.kind, props.sizeBytes, fail]);+ }, [props.src, props.kind, props.sizeBytes]);+ const selectPage = setPage;if (error)return (<div@@ -103,27 +166,143 @@ export default function OfficeViewer(props: {</p></div>);- if (!prepared) return <FileSurfaceLoading />;- const Viewer =- props.kind === "docx" ? WordDocument : props.kind === "xlsx" ? Spreadsheet : Presentation;+ if (notebook)+ return (+ <Suspense fallback={<FileSurfaceLoading />}>+ <NotebookPreview notebook={notebook} sizeBytes={fileSize} />+ </Suspense>+ );+ const sheet = workbook?.sheets[page];+ const documentPage = previewDocument?.pages[page];+ const navigation = workbook ? "sheet" : (previewDocument?.navigation ?? "slide");+ const documentCount = previewDocument?.pages.length ?? 0;+ const documentDetails =+ navigation === "chapter"+ ? `Chapter ${page + 1} of ${documentCount}`+ : `${documentCount} ${navigation}${documentCount === 1 ? "" : "s"}`;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>+ {count > 0 ? (+ <div className="flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3 text-xs">+ <FileSurfaceAction+ label={`Previous ${navigation}`}+ disabled={page === 0}+ onPress={() => selectPage(page - 1)}+ >+ <ChevronLeftIcon className="size-3.5" />+ </FileSurfaceAction>+ {workbook ? (+ <div className="min-w-0 flex-1">+ <Select+ value={page}+ onValueChange={(value) => {+ if (value !== null) selectPage(value);+ }}+ >+ <SelectTrigger aria-label="Sheet" size="xs">+ <SelectValue>{sheet?.name}</SelectValue>+ </SelectTrigger>+ <SelectPopup>+ {workbook.sheets.map((item, index) => (+ <SelectItem key={index} value={index}>+ {item.name}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ </div>+ ) : previewDocument?.navigation === "chapter" ? (+ <div className="min-w-0 flex-1">+ <Select+ value={page}+ onValueChange={(value) => {+ if (value !== null) selectPage(value);+ }}+ >+ <SelectTrigger aria-label="Chapter" size="xs">+ <SelectValue>{documentPage?.title}</SelectValue>+ </SelectTrigger>+ <SelectPopup>+ {previewDocument.pages.map((item, index) => (+ <SelectItem key={index} value={index}>+ {item.title}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ </div>+ ) : (+ <span className="flex-1 text-center tabular-nums" aria-live="polite">+ {navigation === "slide" ? "Slide" : "Page"} {page + 1} of {count}+ </span>+ )}+ <FileSurfaceAction+ label={`Next ${navigation}`}+ disabled={page + 1 === count}+ onPress={() => selectPage(page + 1)}+ >+ <ChevronRightIcon className="size-3.5" />+ </FileSurfaceAction></div>) : null}- {prepared.truncated ? (- <FileSurfaceNotice>- Preview limited. Save it or open it in another app to read the full document.- </FileSurfaceNotice>+ {props.kind === "ods" && sheet ? (+ <div+ className="flex min-h-10 shrink-0 flex-wrap items-center gap-x-1 border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"+ role="status"+ >+ Sheet {page + 1} of {count} · {sheet.rowCount.toLocaleString()} rows ·{" "}+ {sheet.columns.toLocaleString()} columns+ {fileSize !== undefined+ ? ` · ${fileSize === 0 ? "0 bytes" : formatAttachmentSize(fileSize)}`+ : ""}+ </div>) : null}- <Suspense fallback={<FileSurfaceLoading />}>- <Viewer bytes={prepared.bytes} onDetails={setDetails} onError={fail} />- </Suspense>+ {documentPage ? (+ <>+ {props.kind !== "epub" ? (+ <FileSurfaceNotice>+ Text and images. Layout and embedded objects may differ from the original.+ </FileSurfaceNotice>+ ) : null}+ <Suspense fallback={<FileSurfaceLoading />}>+ <DocumentPages+ html={documentPage.html}+ name={`${props.name}: ${documentPage.title}`}+ details={`${documentDetails}${fileSize !== undefined ? ` · ${fileSize === 0 ? "0 bytes" : formatAttachmentSize(fileSize)}` : ""}`}+ />+ </Suspense>+ </>+ ) : sheet ? (+ <>+ <FileSurfaceNotice>+ Cell values only. Charts, images, and formatting are not shown.+ {sheet.truncated+ ? props.kind === "ods"+ ? " Limited to 500 rows and 50 columns."+ : " Preview limited to 250,000 rows, 1,024 columns, and bounded cell text."+ : ""}+ </FileSurfaceNotice>+ {sheet.rowCount === 0 ? (+ <p className="p-6 text-xs text-muted-foreground">This sheet is empty.</p>+ ) : (+ <VirtualTablePreview+ key={page}+ name={`${props.name}: ${sheet.name}`}+ count={sheet.rowCount}+ columns={sheet.columns}+ getRows={(index) => (index === 0 ? sheet.rows : sheetPages.get(`${page}:${index}`))}+ loadPage={(index) => {+ const key = `${page}:${index}`;+ if (pendingPages.current.has(key)) return;+ pendingPages.current.add(key);+ workerRef.current?.postMessage({ type: "sheet-page", sheet: page, index });+ }}+ />+ )}+ </>+ ) : (+ <FileSurfaceLoading />+ )}</div>);}diff --git a/apps/web/src/components/files/OpenXmlOfficeViewer.tsx b/apps/web/src/components/files/OpenXmlOfficeViewer.tsxnew file mode 100644index 00000000000..d17d1393807--- /dev/null+++ b/apps/web/src/components/files/OpenXmlOfficeViewer.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: Extract<OfficePreviewKind, "docx" | "xlsx" | "pptx">;+ readonly sizeBytes?: number;+}) {+ const [error, setError] = useState<string | null>(null);+ const [prepared, setPrepared] = useState<Extract<OfficeWorkerResult, { bytes: ArrayBuffer }>>();+ 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 Open XML 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 if ("bytes" in event.data) {+ 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/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsxnew file mode 100644index 00000000000..70f005a532e--- /dev/null+++ b/apps/web/src/components/files/PdfViewer.tsx@@ -0,0 +1,431 @@+import {+ useEffect,+ useEffectEvent,+ useLayoutEffect,+ useRef,+ useState,+ type CSSProperties,+} from "react";+import { TextLayer, type PDFDocumentProxy } from "pdfjs-dist";+import { ChevronDownIcon, ChevronUpIcon, MinusIcon, PlusIcon, ScanIcon } from "lucide-react";+import { Input } from "~/components/ui/input";+import { observeResize } from "~/lib/observeResize";+import { FileSurfaceAction, FileSurfaceFailure, FileSurfaceLoading } from "./fileSurfaceChrome";+import { readBoundedDocument } from "./readBoundedDocument";+import { openPdf } from "./pdfDocument";+import "./pdfViewer.css";++const MAX_PAGES = 2000;+const MAX_FIND_TEXT = 4 * 1024 * 1024;++function PdfPage(props: {+ document: PDFDocumentProxy;+ index: number;+ width: number;+ query: string;+ onSize: (index: number, ratio: number) => void;+ onError: (error: string) => void;+}) {+ const canvas = useRef<HTMLCanvasElement>(null);+ const text = useRef<HTMLDivElement>(null);+ const { document: pdf, index, width, onSize, onError } = props;+ // oxlint-disable-next-line t3code/react-effect-budget -- Render the PDF page canvas and text layer, cancelling tasks and releasing pdf.js page resources on cleanup.+ useEffect(() => {+ let cancelled = false;+ let paint: ReturnType<Awaited<ReturnType<PDFDocumentProxy["getPage"]>>["render"]> | undefined;+ let layer: TextLayer | undefined;+ let loadedPage: Awaited<ReturnType<PDFDocumentProxy["getPage"]>> | undefined;+ void (async () => {+ const page = await pdf.getPage(index + 1);+ loadedPage = page;+ if (cancelled || !canvas.current || !text.current) {+ page.cleanup();+ return;+ }+ const natural = page.getViewport({ scale: 1 });+ onSize(index, natural.height / natural.width);+ const viewport = page.getViewport({ scale: width / natural.width });+ const ratio = Math.min(+ 2,+ window.devicePixelRatio || 1,+ Math.sqrt((8 * 1024 * 1024) / (viewport.width * viewport.height)),+ );+ canvas.current.width = Math.ceil(viewport.width * ratio);+ canvas.current.height = Math.ceil(viewport.height * ratio);+ paint = page.render({+ canvas: canvas.current,+ viewport,+ transform: [ratio, 0, 0, ratio, 0, 0],+ background: "white",+ });+ text.current.replaceChildren();+ text.current.style.setProperty("--total-scale-factor", String(viewport.scale));+ layer = new TextLayer({+ container: text.current,+ viewport,+ textContentSource: page.streamTextContent(),+ });+ await Promise.all([paint.promise, layer.render()]);+ })().catch((cause: unknown) => {+ if (!cancelled)+ onError(cause instanceof Error ? cause.message : "This PDF page could not render.");+ });+ return () => {+ cancelled = true;+ paint?.cancel();+ layer?.cancel();+ // Release operator lists when virtual pages leave the viewport.+ void Promise.allSettled([paint?.promise]).then(() => loadedPage?.cleanup());+ };+ }, [pdf, index, width, onSize, onError]);+ // oxlint-disable-next-line t3code/react-effect-budget -- Highlight pdf.js-owned text nodes and observe asynchronous text layer mutations for the current search query.+ useEffect(() => {+ const node = text.current;+ if (!node) return;+ const mark = () => {+ const runs = Array.from(node.querySelectorAll('span[role="presentation"], br')).map(+ (element) => ({+ element,+ text: element.tagName === "BR" ? "\n" : (element.textContent ?? "").toLowerCase(),+ }),+ );+ const text = runs.map((run) => run.text).join("");+ const query = props.query.toLowerCase();+ let match = query.trim() ? text.indexOf(query) : -1;+ let offset = 0;+ for (const run of runs) {+ while (match !== -1 && match + query.length <= offset)+ match = text.indexOf(query, match + query.length);+ run.element.classList.toggle(+ "pdf-find-match",+ match !== -1 && match < offset + run.text.length,+ );+ offset += run.text.length;+ }+ };+ mark();+ const observer = new MutationObserver(mark);+ observer.observe(node, { childList: true, subtree: true });+ return () => observer.disconnect();+ }, [props.query]);+ return (+ <>+ <canvas ref={canvas} aria-label={`Page ${index + 1}`} className="block h-full w-full" />+ <div ref={text} data-pdf-text-layer />+ </>+ );+}++export default function PdfViewer(props: { src: string; title: string }) {+ const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [revision, setRevision] = useState(0);+ const [ratios, setRatios] = useState<number[]>([]);+ const [zoom, setZoom] = useState<number | null>(null);+ const [pageWidth, setPageWidth] = useState(612);+ const [viewport, setViewport] = useState({ width: 600, height: 800 });+ const [scrollTop, setScrollTop] = useState(0);+ const [query, setQuery] = useState("");+ const [matches, setMatches] = useState<number[]>([]);+ const [finding, setFinding] = useState(false);+ const [findError, setFindError] = useState<string | null>(null);+ const [match, setMatch] = useState(0);+ const scroll = useRef<HTMLDivElement>(null);+ const find = useRef<HTMLInputElement>(null);+ const zoomAnchor = useRef<{ page: number; offset: number; width: number } | null>(null);+ // oxlint-disable-next-line t3code/react-effect-budget -- Own the PDF fetch, load timeout, and pdf.js document task across source changes, retries, and unmounts.+ useEffect(() => {+ const controller = new AbortController();+ let disposed = false;+ let task: ReturnType<typeof openPdf> | undefined;+ const timeout = setTimeout(() => {+ setError("This PDF took too long to load. Try again.");+ controller.abort();+ void task?.destroy();+ }, 30_000);+ void readBoundedDocument(+ props.src,+ controller.signal,+ 50 * 1024 * 1024,+ revision > 0 ? "reload" : "default",+ )+ .then(async (bytes) => {+ controller.signal.throwIfAborted();+ task = openPdf(bytes);+ const document = await task.promise;+ if (document.numPages > MAX_PAGES)+ throw new Error("Preview limited to 2,000 pages. Save this PDF to read it in full.");+ const first = (await document.getPage(1)).getViewport({ scale: 1 });+ if (controller.signal.aborted) return;+ setPageWidth(first.width);+ setRatios(Array.from({ length: document.numPages }, () => first.height / first.width));+ setPdf(document);+ })+ .catch((cause: unknown) => {+ if (!disposed && !controller.signal.aborted)+ setError(cause instanceof Error ? cause.message : "Unable to open PDF.");+ })+ .finally(() => clearTimeout(timeout));+ return () => {+ disposed = true;+ controller.abort();+ clearTimeout(timeout);+ void task?.destroy();+ };+ }, [props.src, revision]);+ // oxlint-disable-next-line t3code/react-effect-budget -- Measure the PDF viewport before paint and observe resizes for fit-width sizing and visible-page selection.+ useLayoutEffect(() => {+ const node = scroll.current;+ if (!node) return;+ const update = () => setViewport({ width: node.clientWidth, height: node.clientHeight });+ update();+ return observeResize(node, update);+ }, []);+ const fitWidth = Math.max(1, viewport.width - 32);+ const scale = zoom ?? fitWidth / pageWidth;+ const width = zoom === null ? fitWidth : pageWidth * zoom;+ const offsets = (() => {+ const result = [16];+ for (const ratio of ratios) result.push(result[result.length - 1]! + width * ratio + 16);+ return result;+ })();+ const current = Math.max(+ 0,+ ratios.findIndex((_, index) => offsets[index + 1]! > scrollTop + 17),+ );+ const visible = ratios.flatMap((ratio, index) =>+ offsets[index + 1]! >= scrollTop - viewport.height &&+ offsets[index]! <= scrollTop + viewport.height * 2+ ? [{ index, ratio }]+ : [],+ );+ // Stable callbacks let page canvases survive scroll and find updates.+ const [onSize] = useState(+ () => (index: number, ratio: number) =>+ setRatios((old) =>+ old[index] === ratio ? old : old.map((value, i) => (i === index ? ratio : value)),+ ),+ );+ const jumpToPage = useEffectEvent((index: number) => {+ scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });+ });+ const showPage = (index: number) => {+ scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });+ };+ const changeZoom = (value: number | null) => {+ zoomAnchor.current = {+ page: current,+ offset: (scroll.current?.scrollTop ?? 0) - (offsets[current]! - 16),+ width,+ };+ setZoom(value);+ };+ // oxlint-disable-next-line t3code/react-effect-budget -- Restore the DOM scroll anchor after the new zoom width has committed to page layout.+ useLayoutEffect(() => {+ const anchor = zoomAnchor.current;+ zoomAnchor.current = null;+ if (!anchor || anchor.width === width) return;+ scroll.current?.scrollTo({+ top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,+ });+ });+ // oxlint-disable-next-line t3code/react-effect-budget -- Scroll to the first asynchronous search result after its measured page offsets have committed.+ useLayoutEffect(() => {+ if (matches.length) jumpToPage(matches[0]!);+ }, [matches]);+ // oxlint-disable-next-line t3code/react-effect-budget -- Debounce pdf.js text extraction and cancel obsolete searches when the query or document changes.+ useEffect(() => {+ if (!pdf || !query.trim()) {+ // oxlint-disable-next-line react/set-state-in-effect -- A blank query cancels the previous search.+ setFinding(false);+ return;+ }+ let cancelled = false;+ const timer = setTimeout(() => {+ setFinding(true);+ setFindError(null);+ setMatches([]);+ setMatch(0);+ void (async () => {+ const found: number[] = [];+ const sizes: number[] = [];+ let size = 0;+ for (let index = 0; index < pdf.numPages; index++) {+ if (cancelled) return;+ const page = await pdf.getPage(index + 1);+ const pageSize = page.getViewport({ scale: 1 });+ sizes.push(pageSize.height / pageSize.width);+ const content = await page.getTextContent();+ const text = content.items+ .map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : ""))+ .join("");+ size += text.length;+ if (size > MAX_FIND_TEXT)+ throw new Error(+ "This PDF has too much text to search. Save it to search in another app.",+ );+ if (text.toLowerCase().includes(query.toLowerCase())) found.push(index);+ }+ if (cancelled) return;+ setRatios(sizes);+ setMatches(found);+ })()+ .catch((cause: unknown) => {+ if (!cancelled)+ setFindError(cause instanceof Error ? cause.message : "Could not search this PDF.");+ })+ .finally(() => {+ if (!cancelled) setFinding(false);+ });+ }, 250);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [pdf, query]);+ return (+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">+ <div className="flex min-h-10 shrink-0 flex-wrap items-center gap-1 border-b border-border/60 px-2 py-1 text-xs">+ <span className="mr-auto px-1 tabular-nums" aria-live="polite">+ {pdf ? `${current + 1} / ${pdf.numPages} pages` : "PDF"}+ </span>+ <FileSurfaceAction+ label="Previous page"+ disabled={!pdf || current === 0}+ onPress={() => showPage(current - 1)}+ >+ <ChevronUpIcon className="size-3.5" />+ </FileSurfaceAction>+ <FileSurfaceAction+ label="Next page"+ disabled={!pdf || current + 1 >= pdf.numPages}+ onPress={() => showPage(current + 1)}+ >+ <ChevronDownIcon className="size-3.5" />+ </FileSurfaceAction>+ <FileSurfaceAction+ label="Zoom out"+ disabled={scale <= 0.25}+ onPress={() => changeZoom(Math.max(0.25, scale - 0.25))}+ >+ <MinusIcon className="size-3.5" />+ </FileSurfaceAction>+ <span className="min-w-14 text-center tabular-nums">+ {zoom === null ? "Fit width" : `${Math.round(scale * 100)}%`}+ </span>+ <FileSurfaceAction+ label="Zoom in"+ disabled={scale >= 3}+ onPress={() => changeZoom(Math.min(3, scale + 0.25))}+ >+ <PlusIcon className="size-3.5" />+ </FileSurfaceAction>+ <FileSurfaceAction+ label="Fit width"+ onPress={() => {+ changeZoom(null);+ scroll.current?.scrollTo({ left: 0 });+ }}+ >+ <ScanIcon className="size-3.5" />+ </FileSurfaceAction>+ <div className="w-28">+ <Input+ ref={find}+ size="compact"+ type="search"+ aria-label="Find in PDF"+ placeholder="Find in PDF"+ value={query}+ onChange={(event) => {+ setQuery(event.target.value);+ setMatches([]);+ setFindError(null);+ }}+ />+ </div>+ {query ? (+ <>+ <span role="status">+ {finding+ ? "Searching…"+ : (findError ?? `${matches.length ? match + 1 : 0}/${matches.length}`)}+ </span>+ <FileSurfaceAction+ label="Next matching page"+ disabled={!matches.length}+ onPress={() => {+ const next = (match + 1) % matches.length;+ setMatch(next);+ showPage(matches[next]!);+ }}+ >+ <ChevronDownIcon className="size-3.5" />+ </FileSurfaceAction>+ </>+ ) : null}+ </div>+ <div+ ref={scroll}+ role="region"+ aria-label={props.title}+ tabIndex={0}+ className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto bg-muted/40"+ onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}+ onKeyDown={(event) => {+ if ((event.ctrlKey || event.metaKey) && event.key === "f") {+ event.preventDefault();+ event.stopPropagation();+ find.current?.focus();+ }+ }}+ >+ {error ? (+ <FileSurfaceFailure+ message={error}+ onRetry={() => {+ setError(null);+ setPdf(null);+ setRevision((value) => value + 1);+ }}+ />+ ) : !pdf ? (+ <FileSurfaceLoading />+ ) : (+ <div+ className="relative"+ style={{+ height: `max(${offsets.at(-1) ?? 0}px, calc(100% + ${(offsets.at(-2) ?? 16) - 16}px))`,+ minWidth: width + 32,+ }}+ >+ {visible.map(({ index, ratio }) => (+ <div+ key={index}+ className="absolute bg-white shadow-sm"+ style={+ {+ top: offsets[index],+ left: Math.max(16, (viewport.width - width) / 2),+ width,+ height: width * ratio,+ "--total-scale-factor": 1,+ } as CSSProperties+ }+ >+ <PdfPage+ document={pdf}+ index={index}+ width={width}+ query={query}+ onSize={onSize}+ onError={setError}+ />+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.tsnew file mode 100644index 00000000000..589ae62265c--- /dev/null+++ b/apps/web/src/components/files/extendedDocumentPreview.ts@@ -0,0 +1,672 @@+import {+ IMAGE_DIMENSIONS_HEADER_BYTES,+ readImageDimensions,+} from "@t3tools/shared/imageDimensions";+import { XMLParser, XMLValidator } from "fast-xml-parser";+import { decodeHTMLAttribute, decodeHTMLStrict as decodeEntities } from "entities";+import type JSZip from "jszip";++import { type OfficeWorkerResult, type NotebookCell } from "./officePreviewProtocol";++const ODS_PREVIEW_MAX_ROWS = 500;+const ODS_PREVIEW_MAX_COLUMNS = 50;++type XmlNode = { name: string; attrs: Record<string, string>; children: XmlNode[]; text: string };+type OrderedXml = { [key: string]: OrderedXml[] | Record<string, string> | string };+const escape = (value: string) =>+ value+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll('"', """);++const namespacePrefixes: Record<string, string> = {+ "urn:oasis:names:tc:opendocument:xmlns:office:1.0": "office",+ "urn:oasis:names:tc:opendocument:xmlns:table:1.0": "table",+ "urn:oasis:names:tc:opendocument:xmlns:text:1.0": "text",+ "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0": "draw",+ "http://www.w3.org/1999/xlink": "xlink",+ "http://www.w3.org/1999/xhtml": "",+ "http://www.idpf.org/2007/opf": "",+ "urn:oasis:names:tc:opendocument:xmlns:container": "",+};+function parseXml(source: string): XmlNode {+ // EPUB XHTML commonly declares an external DTD. Discard it without resolving it.+ source = source.replaceAll(/<!DOCTYPE\s+[^<>[\]]*>/gi, "");+ if (+ source.length > 8 * 1024 * 1024 ||+ /<!\s*(DOCTYPE|ENTITY)/i.test(source) ||+ XMLValidator.validate(source) !== true+ )+ throw new Error("This document contains invalid or unsupported XML.");+ const parser = new XMLParser({+ preserveOrder: true,+ ignoreAttributes: false,+ attributeNamePrefix: "",+ processEntities: false,+ trimValues: false,+ parseTagValue: false,+ });+ const ordered = parser.parse(source) as OrderedXml[];+ let count = 0;+ function convert(+ items: OrderedXml[],+ depth: number,+ inherited: Record<string, string>,+ ): XmlNode[] {+ if (depth > 100) throw new Error("This document is nested too deeply to preview.");+ return items.map((item) => {+ if (++count > 100_000) throw new Error("This document has too much content to preview.");+ const name = Object.keys(item).find((key) => key !== ":@") ?? "#text";+ const value = item[name];+ const attrs = Object.fromEntries(+ Object.entries((item[":@"] ?? {}) as Record<string, string>).map(([key, value]) => [+ key,+ decodeEntities(value),+ ]),+ );+ const namespaces = Object.create(inherited) as Record<string, string>;+ for (const [key, value] of Object.entries(attrs)) {+ if (key === "xmlns") namespaces[""] = value;+ else if (key.startsWith("xmlns:")) namespaces[key.slice(6)] = value;+ }+ const expanded = (name: string, attribute = false) => {+ if (name.startsWith("#")) return name;+ const colon = name.indexOf(":");+ if (colon < 0 && attribute) return name;+ const uri = namespaces[colon < 0 ? "" : name.slice(0, colon)];+ if (!uri) return name;+ const prefix = Object.hasOwn(namespacePrefixes, uri) ? namespacePrefixes[uri] : undefined;+ const local = name.slice(colon + 1);+ return prefix === undefined+ ? "{" + uri + "}" + local+ : prefix+ ? prefix + ":" + local+ : local;+ };+ return {+ name: expanded(name),+ attrs: Object.fromEntries(+ Object.entries(attrs).map(([key, value]) => [expanded(key, true), value]),+ ),+ children: Array.isArray(value) ? convert(value, depth + 1, namespaces) : [],+ text: typeof value === "string" ? value : "",+ };+ });+ }+ return {+ name: "root",+ attrs: {},+ children: convert(ordered, 0, Object.create(null) as Record<string, string>),+ text: "",+ };+}+function find(node: XmlNode, name: string, skip?: string): XmlNode[] {+ return node.children.flatMap((child) =>+ child.name === skip+ ? []+ : child.name === name || (!name.includes(":") && child.name.endsWith(`:${name}`))+ ? [child]+ : find(child, name, skip),+ );+}+function text(node: XmlNode): string {+ if (node.name === "office:annotation") return "";+ if (node.name === "text:s") return " ".repeat(repeat(node.attrs["text:c"], 100));+ if (node.name === "text:tab") return "\t";+ if (node.name === "text:line-break") return "\n";+ return node.name === "#text" ? decodeEntities(node.text) : node.children.map(text).join("");+}+function archivePath(base: string, href: string): string | null {+ if (/^(?:[a-z][a-z\d+.-]*:|\/|\\)/i.test(href)) return null;+ const parts = base.split("/").slice(0, -1);+ let decoded: string;+ try {+ decoded = decodeURIComponent(href.split(/[?#]/, 1)[0] ?? "");+ } catch {+ return null;+ }+ for (const part of decoded.split("/")) {+ if (part === "..") {+ if (!parts.length) return null;+ parts.pop();+ } else if (part && part !== ".") parts.push(part);+ }+ return parts.join("/");+}+function imageFits(bytes: Uint8Array) {+ const size = readImageDimensions(bytes.subarray(0, IMAGE_DIMENSIONS_HEADER_BYTES));+ return size !== null && size.width <= 16_777_216 / size.height;+}+function base64ImageFits(base64: string) {+ return (+ /^[a-z\d+/]*={0,2}$/i.test(base64) &&+ base64.length % 4 !== 1 &&+ (!base64.endsWith("=") || base64.length % 4 === 0) &&+ imageFits(+ Uint8Array.from(+ atob(base64.slice(0, 4 * Math.ceil(IMAGE_DIMENSIONS_HEADER_BYTES / 3))),+ (char) => char.charCodeAt(0),+ ),+ )+ );+}+function htmlImagesFit(html: string) {+ // HTML attribute entities can obscure a data URL until the client parses it.+ for (const match of decodeHTMLAttribute(html).matchAll(+ /data:image\/(?:png|jpeg|gif|webp);base64,([a-z\d+/]*={0,2})/gi,+ ))+ if (!base64ImageFits(match[1]!)) return false;+ return true;+}+async function imageData(archive: JSZip, path: string | null): Promise<string> {+ if (!path) return "";+ const mime = (+ { png: "png", jpg: "jpeg", jpeg: "jpeg", gif: "gif", webp: "webp" } as Record<string, string>+ )[path.split(".").at(-1)?.toLowerCase() ?? ""];+ const entry = archive.file(path);+ if (!mime || !entry) return "";+ const bytes = await entry.async("uint8array");+ if (bytes.length > 4 * 1024 * 1024 || !imageFits(bytes)) return "";+ reserveMarkup(4 * Math.ceil(bytes.length / 3) + 100);+ return `data:image/${mime};base64,${await entry.async("base64")}`;+}+let markupBytes = 0;+function reserveMarkup(size: number) {+ markupBytes += size;+ if (markupBytes > 16 * 1024 * 1024)+ throw new Error("The rendered document is too large to preview.");+}+function boundedMarkup(value: string): string {+ reserveMarkup(value.length);+ return value;+}+const HTML_TAGS = new Set([+ "p",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "div",+ "span",+ "strong",+ "b",+ "em",+ "i",+ "u",+ "s",+ "ul",+ "ol",+ "li",+ "blockquote",+ "pre",+ "code",+ "table",+ "thead",+ "tbody",+ "tr",+ "th",+ "td",+ "caption",+ "figure",+ "figcaption",+ "br",+ "hr",+ "sub",+ "sup",+ "dl",+ "dt",+ "dd",+]);+async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise<string> {+ if (node.name === "#text") return boundedMarkup(escape(text(node)));+ const tag =+ node.name+ .replace(/^\{[^}]*\}/, "")+ .split(":")+ .at(-1) ?? "";+ if (["head", "script", "style", "iframe", "object", "embed", "svg", "math", "form"].includes(tag))+ return "";+ if (tag === "br" || tag === "hr") return boundedMarkup(`<${tag}>`);+ if (tag === "img") {+ const src = await imageData(archive, archivePath(base, node.attrs.src ?? ""));+ return src ? `<img src="${src}" alt="${boundedMarkup(escape(node.attrs.alt ?? ""))}">` : "";+ }+ let children = "";+ for (const child of node.children) children += await epubHtml(child, archive, base);+ if (!HTML_TAGS.has(tag)) return children;+ const spans =+ tag === "td" || tag === "th"+ ? ["colspan", "rowspan"]+ .map((name) =>+ /^\d{1,4}$/.test(node.attrs[name] ?? "") ? ` ${name}="${node.attrs[name]}"` : "",+ )+ .join("")+ : "";+ reserveMarkup(tag.length * 2 + spans.length + 5);+ return `<${tag}${spans}>${children}</${tag}>`;+}+async function odfHtml(node: XmlNode, archive: JSZip): Promise<string> {+ if (node.name === "#text") return boundedMarkup(escape(text(node)));+ if (node.name === "text:s" || node.name === "text:tab")+ return boundedMarkup(+ `<span data-odf-whitespace>${node.name === "text:tab" ? "	" : " ".repeat(repeat(node.attrs["text:c"], 100))}</span>`,+ );+ if (node.name === "text:line-break") return boundedMarkup("<br>");+ if (node.name === "draw:image") {+ const src = await imageData(+ archive,+ archivePath("content.xml", node.attrs["xlink:href"] ?? ""),+ );+ return src ? `<img src="${src}" alt="">` : "";+ }+ if (+ [+ "office:annotation",+ "text:tracked-changes",+ "office:scripts",+ "draw:object",+ "draw:object-ole",+ ].includes(node.name)+ )+ return "";+ let children = "";+ for (const child of node.children) children += await odfHtml(child, archive);+ const tags: Record<string, string> = {+ "text:p": "p",+ "text:h": "h2",+ "text:span": "span",+ "text:list": "ul",+ "text:list-item": "li",+ "table:table": "table",+ "table:table-row": "tr",+ "table:table-cell": "td",+ };+ const tag = tags[node.name];+ if (!tag) return children;+ reserveMarkup(tag.length * 2 + 5);+ return `<${tag}>${children}</${tag}>`;+}+function repeat(value: string | undefined, max: number) {+ const count = Number(value ?? 1);+ if (!Number.isSafeInteger(count) || count < 1)+ throw new Error("This spreadsheet contains invalid repeated cells.");+ return Math.min(count, max);+}+export async function openDocument(+ archive: JSZip,+ kind: "odt" | "ods" | "odp",+): Promise<OfficeWorkerResult> {+ markupBytes = 0;+ const source = await archive.file("content.xml")?.async("string");+ if (!source) throw new Error("This OpenDocument file has no readable content.");+ const root = parseXml(source);+ if (kind === "ods") {+ const tables = find(root, "table:table");+ if (!tables.length || tables.length > 100)+ throw new Error("This workbook has no sheets or too many sheets to preview.");+ let cellBytes = 0;+ return {+ type: "ods",+ sheets: tables.map((table, index) => {+ const rows: string[][] = [];+ let truncated = false;+ let pendingEmptyRows = 0;+ for (const row of find(table, "table:table-row")) {+ const cells: string[] = [];+ for (const cell of row.children.filter((child) =>+ ["table:table-cell", "table:covered-table-cell"].includes(child.name),+ )) {+ const value =+ find(cell, "text:p", "office:annotation").map(text).join("\n") ||+ cell.attrs["office:value"] ||+ cell.attrs["office:date-value"] ||+ cell.attrs["office:boolean-value"] ||+ cell.attrs["office:string-value"] ||+ "";+ const count = repeat(+ cell.attrs["table:number-columns-repeated"],+ ODS_PREVIEW_MAX_COLUMNS + 1,+ );+ if (value && cells.length + count > ODS_PREVIEW_MAX_COLUMNS) truncated = true;+ for (let i = 0; i < count && cells.length < ODS_PREVIEW_MAX_COLUMNS; i++) {+ if (value.length > 10_000)+ throw new Error("A spreadsheet cell is too large to preview.");+ cells.push(value);+ }+ }+ while (cells.at(-1) === "") cells.pop();+ const count = repeat(row.attrs["table:number-rows-repeated"], ODS_PREVIEW_MAX_ROWS + 1);+ if (!cells.length) {+ pendingEmptyRows = Math.min(ODS_PREVIEW_MAX_ROWS + 1, pendingEmptyRows + count);+ continue;+ }+ while (pendingEmptyRows > 0 && rows.length < ODS_PREVIEW_MAX_ROWS) {+ rows.push([]);+ pendingEmptyRows--;+ }+ pendingEmptyRows = 0;+ if (rows.length + count > ODS_PREVIEW_MAX_ROWS) truncated = true;+ if (rows.length >= ODS_PREVIEW_MAX_ROWS) break;+ for (let i = 0; i < count && rows.length < ODS_PREVIEW_MAX_ROWS; i++) {+ cellBytes += cells.reduce((size, cell) => size + cell.length, 0);+ if (cellBytes > 8 * 1024 * 1024)+ throw new Error("This spreadsheet has too much text to preview.");+ rows.push(cells);+ }+ }+ return {+ name: table.attrs["table:name"] || `Sheet ${index + 1}`,+ rows,+ rowCount: rows.length,+ columns: rows.reduce((columns, row) => Math.max(columns, row.length), 1),+ truncated,+ };+ }),+ };+ }+ const pages = kind === "odp" ? find(root, "draw:page") : find(root, "office:text");+ if (!pages.length || pages.length > 500)+ throw new Error("This document has no pages or too many pages to preview.");+ const rendered = [];+ for (const [index, page] of pages.entries()) {+ rendered.push({+ title: page.attrs["draw:name"] || `Page ${index + 1}`,+ html: await odfHtml(page, archive),+ });+ }+ return { type: "document", navigation: kind === "odp" ? "slide" : "page", pages: rendered };+}+export async function openEpub(archive: JSZip): Promise<OfficeWorkerResult> {+ markupBytes = 0;+ const container = parseXml((await archive.file("META-INF/container.xml")?.async("string")) ?? "");+ const rootfile = find(container, "rootfile")[0]?.attrs["full-path"];+ if (!rootfile || !archive.file(rootfile)) throw new Error("This EPUB has no readable package.");+ const packageRoot = parseXml(await archive.file(rootfile)!.async("string"));+ const manifest = new Map(find(packageRoot, "item").map((item) => [item.attrs.id, item]));+ const spine = find(packageRoot, "itemref");+ if (!spine.length || spine.length > 500)+ throw new Error("This EPUB has no chapters or too many chapters to preview.");+ const pages = [];+ for (const itemref of spine) {+ const item = manifest.get(itemref.attrs.idref);+ if (!item || item.attrs["media-type"] !== "application/xhtml+xml") continue;+ const path = archivePath(rootfile, item.attrs.href ?? "");+ const entry = path ? archive.file(path) : null;+ if (!entry || !path) continue;+ const chapter = parseXml(await entry.async("string"));+ pages.push({+ title:+ text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter).slice(0, 120) ||+ `Chapter ${pages.length + 1}`,+ html: await epubHtml(chapter, archive, path),+ });+ }+ if (!pages.length) throw new Error("This EPUB has no readable XHTML chapters.");+ return { type: "document", navigation: "chapter", pages };+}+function record(value: unknown): Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}+function notebookText(value: unknown, limit = 256_000): string {+ const result =+ typeof value === "string"+ ? value+ : Array.isArray(value)+ ? value.filter((part) => typeof part === "string").join("")+ : "";+ if (result.length > limit) throw new Error("A notebook cell is too large to preview.");+ return result;+}+export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult {+ if (bytes.byteLength > 8 * 1024 * 1024)+ throw new Error("Notebook preview limited to files under 8 MB.");+ const notebook = record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));+ if (notebook.nbformat !== 4 || !Array.isArray(notebook.cells) || notebook.cells.length > 500)+ throw new Error("Preview supports version 4 notebooks with up to 500 cells.");+ const language = String(record(record(notebook.metadata).language_info).name ?? "text")+ .replaceAll(/[^a-z\d+#-]/gi, "")+ .slice(0, 40);+ const cells: NotebookCell[] = notebook.cells.map((value) => {+ const cell = record(value);+ const outputs = Array.isArray(cell.outputs) ? cell.outputs : [];+ if (outputs.length > 100) throw new Error("A notebook cell has too many outputs to preview.");+ return {+ kind: cell.cell_type === "markdown" ? "markdown" : cell.cell_type === "code" ? "code" : "raw",+ source: notebookText(cell.source),+ outputs: outputs+ .map((value) => {+ const output = record(value);+ const data = record(output.data);+ for (const mime of ["image/png", "image/jpeg", "image/gif", "image/webp"]) {+ if (data[mime]) {+ const base64 = notebookText(data[mime], 4 * 1024 * 1024).replaceAll(/\s/g, "");+ if (base64ImageFits(base64))+ return { kind: "image" as const, text: `data:${mime};base64,${base64}` };+ }+ }+ const html = notebookText(data["text/html"]);+ if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html };+ return {+ kind: "text" as const,+ text: notebookText(output.text ?? data["text/plain"] ?? output.traceback),+ };+ })+ .filter((output) => output.text.trim().length > 0),+ };+ });+ return { type: "notebook", language, cells };+}++export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult {+ if (bytes.byteLength > 8 * 1024 * 1024)+ throw new Error("Rich text preview limited to files under 8 MB.");+ // Keep byte offsets intact for binary destinations and multibyte code pages.+ const input = new Uint8Array(bytes);+ let source = "";+ for (let offset = 0; offset < input.length; offset += 8192)+ source += String.fromCharCode(...input.subarray(offset, offset + 8192));+ if (!source.startsWith("{\\rtf")) throw new Error("This is not a valid rich text document.");+ let state = {+ skip: false,+ bold: false,+ italic: false,+ underline: false,+ uc: 1,+ font: 0,+ fontTable: false,+ decoder: new TextDecoder("windows-1252"),+ };+ const fonts = new Map<number, TextDecoder>();+ let defaultFont = 0;+ const stack: (typeof state)[] = [];+ let html = "";+ const pages: { title: string; html: string }[] = [];+ let completedLength = 0;+ const finishPage = () => {+ if (pages.length >= 500) throw new Error("Rich text preview limited to 500 pages.");+ pages.push({ title: `Page ${pages.length + 1}`, html: `<p>${html}</p>` });+ completedLength += html.length;+ html = "";+ };+ let run = "";+ let fallback = 0;+ const encoded = new Uint8Array(bytes.byteLength);+ let encodedLength = 0;+ const flush = () => {+ if (encodedLength) {+ run += escape(+ (fonts.get(state.font) ?? state.decoder).decode(encoded.subarray(0, encodedLength)),+ );+ encodedLength = 0;+ }+ if (completedLength + html.length + run.length > 8 * 1024 * 1024)+ throw new Error("This rich text document has too much content to preview.");+ if (!run) return;+ let span = run;+ if (state.bold) span = `<strong>${span}</strong>`;+ if (state.italic) span = `<em>${span}</em>`;+ if (state.underline) span = `<u>${span}</u>`;+ html += span;+ run = "";+ };+ const emit = (value: string) => {+ if (fallback > 0) {+ fallback--;+ return;+ }+ if (state.skip) return;+ run += escape(value);+ if (completedLength + html.length + run.length > 8 * 1024 * 1024)+ throw new Error("This rich text document has too much content to preview.");+ };+ const emitByte = (value: number) => {+ if (fallback > 0) fallback--;+ else if (!state.skip) encoded[encodedLength++] = value;+ };+ for (let i = 0; i < source.length;) {+ const char = source[i++];+ if (char === "{") {+ flush();+ fallback = 0;+ if (stack.length > 100) throw new Error("This rich text document is nested too deeply.");+ stack.push({ ...state });+ } else if (char === "}") {+ flush();+ fallback = 0;+ const parent = stack.pop();+ if (!parent) throw new Error("This rich text document is damaged.");+ state = parent;+ } else if (char === "\\") {+ const next = source[i];+ if (next === "'") {+ const hex = source.slice(i + 1, i + 3);+ if (!/^[\da-f]{2}$/i.test(hex)) throw new Error("Invalid rich text byte escape.");+ i += 3;+ emitByte(Number.parseInt(hex, 16));+ continue;+ }+ flush();+ if (next === "\\" || next === "{" || next === "}") {+ i++;+ emit(next);+ continue;+ }+ if (next === "*") {+ state.skip = true;+ i++;+ continue;+ }+ const match = /^([a-z]+)(-?\d+)? ?/i.exec(source.slice(i));+ if (!match) {+ if (next === "~") emit("\u00a0");+ i++;+ continue;+ }+ i += match[0].length;+ const word = match[1];+ const arg = match[2] === undefined ? 1 : Number(match[2]);+ if (word === "fonttbl") {+ state.fontTable = true;+ state.skip = true;+ } else if (word === "deff") state.font = defaultFont = arg;+ else if (word === "f") state.font = arg;+ else if (word === "fcharset" && state.fontTable) {+ const label = (+ {+ 0: state.decoder.encoding,+ 1: state.decoder.encoding,+ 77: "macintosh",+ 128: "shift_jis",+ 129: "euc-kr",+ 134: "gbk",+ 136: "big5",+ 161: "windows-1253",+ 162: "windows-1254",+ 163: "windows-1258",+ 177: "windows-1255",+ 178: "windows-1256",+ 186: "windows-1257",+ 204: "windows-1251",+ 222: "windows-874",+ 238: "windows-1250",+ 255: "ibm866",+ } as Record<number, string>+ )[arg];+ if (label) fonts.set(state.font, new TextDecoder(label));+ } else if (+ [+ "colortbl",+ "stylesheet",+ "info",+ "pict",+ "object",+ "fldinst",+ "header",+ "headerl",+ "headerr",+ "headerf",+ "footer",+ "footerl",+ "footerr",+ "footerf",+ "filetbl",+ "datastore",+ "themedata",+ ].includes(word!)+ )+ state.skip = true;+ else if (word === "bin") {+ if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i)+ throw new Error("Invalid rich text binary data.");+ i += arg;+ } else if (word === "ansicpg") {+ const label =+ (+ {+ 65001: "utf-8",+ 932: "shift_jis",+ 936: "gbk",+ 949: "euc-kr",+ 950: "big5",+ 874: "windows-874",+ } as Record<number, string>+ )[arg] ?? `windows-${arg}`;+ try {+ state.decoder = new TextDecoder(label);+ } catch {+ throw new Error("This rich text code page is not supported.");+ }+ } else if (word === "b") state.bold = arg !== 0;+ else if (word === "i") state.italic = arg !== 0;+ else if (word === "ul") state.underline = arg !== 0;+ else if (word === "ulnone") state.underline = false;+ else if (word === "plain")+ state = { ...state, bold: false, italic: false, underline: false, font: defaultFont };+ else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg));+ else if (word === "u") {+ fallback = 0;+ emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg));+ fallback = state.uc;+ } else if (!state.skip && word === "page") finishPage();+ else if (!state.skip && (word === "par" || word === "line" || word === "row")) html += "<br>";+ else if (word === "tab" || word === "cell") emit("\t");+ else if (word === "endash") emit("–");+ // oxlint-disable-next-line t3code/no-em-dash-copy -- Preserve the RTF document's punctuation.+ else if (word === "emdash") emit("—");+ else if (word === "bullet") emit("•");+ else if (word === "lquote") emit("‘");+ else if (word === "rquote") emit("’");+ else if (word === "ldblquote") emit("“");+ else if (word === "rdblquote") emit("”");+ } else if (char !== "\r" && char !== "\n" && char) emitByte(char.charCodeAt(0));+ }+ if (stack.length) throw new Error("This rich text document is damaged.");+ flush();+ if (html || !pages.length) finishPage();+ return { type: "document", navigation: "page", pages };+}diff --git a/apps/web/src/components/files/officeArchive.ts b/apps/web/src/components/files/officeArchive.tsindex 2b288699bb2..fe098f6979d 100644--- a/apps/web/src/components/files/officeArchive.ts+++ b/apps/web/src/components/files/officeArchive.ts@@ -225,6 +225,8 @@ function boundedWorksheet(let explicitRow = false;let rowTag = "";let column = 0;+ let maxRow = 0;+ let maxColumn = 0;let cells = new Map<number, string>();let cell: {start: number;@@ -299,7 +301,9 @@ function boundedWorksheet(truncated = true;return;}- if (++budget.cells > 2_000_000 || row * column > 8_000_000)+ maxRow = Math.max(maxRow, row);+ maxColumn = Math.max(maxColumn, column);+ if (++budget.cells > 2_000_000 || maxRow * maxColumn > 8_000_000)throw new Error("This workbook exceeds the preview limit: 2 million cells or 8 million grid positions.",);@@ -934,7 +938,7 @@ async function wordExpansion(// 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" }>) {+export async function boundedArchive(input: Extract<OfficeWorkerRequest, { type: "open" }>) {const { bytes } = input;const spreadsheet = input.kind === "xlsx";if (bytes.byteLength > OFFICE_PREVIEW_MAX_BYTES)diff --git a/apps/web/src/components/files/officePreview.worker.ts b/apps/web/src/components/files/officePreview.worker.tsindex 071d70a66ad..4ba65fb5de0 100644--- a/apps/web/src/components/files/officePreview.worker.ts+++ b/apps/web/src/components/files/officePreview.worker.ts@@ -1,20 +1,52 @@-import { prepareOffice } from "./officeArchive";+import { boundedArchive, prepareOffice } from "./officeArchive";+import { PREVIEW_PAGE_ROWS } from "./largeTextProtocol";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: [] },- );++let workbook: string[][][] = [];+function reply(result: OfficeWorkerResult) {+ self.postMessage(result, { transfer: "bytes" in result ? [result.bytes] : [] });+}+async function handle(input: OfficeWorkerRequest) {+ if (input.type === "sheet-page") {+ const rows = workbook[input.sheet];+ if (!rows) throw new Error("This sheet is unavailable.");+ reply({+ type: "sheet-page",+ sheet: input.sheet,+ index: input.index,+ rows: rows.slice(input.index * PREVIEW_PAGE_ROWS, (input.index + 1) * PREVIEW_PAGE_ROWS),+ });+ return;+ }+ if (input.kind === "docx" || input.kind === "xlsx" || input.kind === "pptx") {+ reply({ type: input.kind, ...(await prepareOffice(input.bytes, input.kind)) });+ return;+ }+ const { openDocument, openEpub, openNotebook, openRtf } =+ await import("./extendedDocumentPreview");+ if (input.kind === "ipynb" || input.kind === "rtf") {+ reply(input.kind === "ipynb" ? openNotebook(input.bytes) : openRtf(input.bytes));+ return;+ }+ const { archive } = await boundedArchive(input);+ const result =+ input.kind === "epub" ? await openEpub(archive) : await openDocument(archive, input.kind);+ if (result.type === "ods") {+ workbook = result.sheets.map((sheet) => sheet.rows);+ reply({+ ...result,+ sheets: result.sheets.map((sheet) => ({+ ...sheet,+ rows: sheet.rows.slice(0, PREVIEW_PAGE_ROWS),+ })),});+ } else reply(result);+}+self.addEventListener("message", (event: MessageEvent<OfficeWorkerRequest>) => {+ void handle(event.data).catch((cause: unknown) =>+ reply({+ type: "error",+ message: cause instanceof Error ? cause.message : "Could not parse this file.",+ }),+ );});diff --git a/apps/web/src/components/files/officePreviewProtocol.ts b/apps/web/src/components/files/officePreviewProtocol.tsindex f0075fe439a..51f3b8f4cd1 100644--- a/apps/web/src/components/files/officePreviewProtocol.ts+++ b/apps/web/src/components/files/officePreviewProtocol.ts@@ -1,16 +1,45 @@import type { OfficePreviewKind } from "@t3tools/shared/filePreview";+export const OFFICE_PREVIEW_MAX_BYTES = 50 * 1024 * 1024;export const OFFICE_PREVIEW_MAX_ROWS = 250_000;export const OFFICE_PREVIEW_MAX_COLUMNS = 1024;-export type OfficeWorkerRequest = {- readonly type: "open";- readonly kind: OfficePreviewKind;- readonly bytes: ArrayBuffer;++export type OfficeWorkerRequest =+ | { readonly type: "open"; readonly kind: OfficePreviewKind; readonly bytes: ArrayBuffer }+ | { readonly type: "sheet-page"; readonly sheet: number; readonly index: number };++export type NotebookCell = {+ readonly kind: "markdown" | "code" | "raw";+ readonly source: string;+ readonly outputs: { readonly kind: "text" | "image" | "html"; readonly text: string }[];};+export type OfficeWorkerResult =+ | {+ readonly type: "document";+ readonly navigation: "page" | "slide" | "chapter";+ readonly pages: { title: string; html: string }[];+ }+ | { readonly type: "notebook"; readonly language: string; readonly cells: NotebookCell[] }| { readonly type: "error"; readonly message: string }| {- readonly type: OfficePreviewKind;+ readonly type: "docx" | "xlsx" | "pptx";readonly bytes: ArrayBuffer;readonly truncated: boolean;+ }+ | {+ readonly type: "ods";+ readonly sheets: {+ name: string;+ rows: string[][];+ truncated: boolean;+ rowCount: number;+ columns: number;+ }[];+ }+ | {+ readonly type: "sheet-page";+ readonly sheet: number;+ readonly index: number;+ readonly rows: string[][];};diff --git a/apps/web/src/components/files/pdfDocument.ts b/apps/web/src/components/files/pdfDocument.tsnew file mode 100644index 00000000000..2cc5493718b--- /dev/null+++ b/apps/web/src/components/files/pdfDocument.ts@@ -0,0 +1,45 @@+import { getDocument, GlobalWorkerOptions } from "pdfjs-dist";+import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";+import fallbackUrl from "pdfjs-dist/wasm/openjpeg_nowasm_fallback.js?url";++GlobalWorkerOptions.workerSrc = workerUrl;++const standardFonts = import.meta.glob<string>(+ "../../../node_modules/pdfjs-dist/standard_fonts/*",+ { query: "?url", import: "default", eager: true },+);+const cMaps = import.meta.glob<string>("../../../node_modules/pdfjs-dist/cmaps/*.bcmap", {+ query: "?url",+ import: "default",+ eager: true,+});+const wasm = import.meta.glob<string>("../../../node_modules/pdfjs-dist/wasm/*.{wasm,js}", {+ query: "?url",+ import: "default",+ eager: true,+});+export class BinaryDataFactory {+ async fetch({ kind, filename }: { kind: string; filename: string }) {+ const assets = kind === "cMapUrl" ? cMaps : kind === "wasmUrl" ? wasm : standardFonts;+ const directory = kind === "cMapUrl" ? "cmaps" : kind === "wasmUrl" ? "wasm" : "standard_fonts";+ const url = assets[`../../../node_modules/pdfjs-dist/${directory}/${filename}`];+ if (!url) throw new Error(`Unsupported PDF ${directory} asset.`);+ const response = await fetch(url);+ if (!response.ok || response.headers.get("content-type")?.startsWith("text/html"))+ throw new Error(`PDF ${directory} asset unavailable.`);+ return new Uint8Array(await response.arrayBuffer());+ }+}++export function openPdf(bytes: ArrayBuffer) {+ return getDocument({+ data: new Uint8Array(bytes),+ useSystemFonts: true,+ useWorkerFetch: false,+ BinaryDataFactory,+ // PDF.js imports JavaScript decoders directly, bypassing BinaryDataFactory.+ wasmUrl: new URL(".", new URL(fallbackUrl, window.location.href)).href,+ canvasMaxAreaInBytes: 32 * 1024 * 1024,+ useWasm: true,+ });+}diff --git a/apps/web/src/components/files/pdfViewer.css b/apps/web/src/components/files/pdfViewer.cssnew file mode 100644index 00000000000..2dde14c4591--- /dev/null+++ b/apps/web/src/components/files/pdfViewer.css@@ -0,0 +1,52 @@+/* TextLayer geometry follows PDF.js' text layer contract (Apache-2.0). */+[data-pdf-text-layer] {+ position: absolute;+ inset: 0;+ overflow: clip;+ line-height: 1;+ text-align: initial;+ letter-spacing: normal;+ word-spacing: normal;+ text-size-adjust: none;+ forced-color-adjust: none;+ transform-origin: 0 0;+ --min-font-size: 1;+ --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));+ --min-font-size-inv: calc(1 / var(--min-font-size));+ --scale-round-x: 1px;+ --scale-round-y: 1px;+}+[data-pdf-text-layer][data-main-rotation="90"] {+ transform: rotate(90deg) translateY(-100%);+}+[data-pdf-text-layer][data-main-rotation="180"] {+ transform: rotate(180deg) translate(-100%, -100%);+}+[data-pdf-text-layer][data-main-rotation="270"] {+ transform: rotate(270deg) translateX(-100%);+}+[data-pdf-text-layer] :is(span, br) {+ color: transparent;+ position: absolute;+ white-space: pre;+ cursor: text;+ transform-origin: 0 0;+ user-select: text;+}+[data-pdf-text-layer] > :not(.markedContent),+[data-pdf-text-layer] .markedContent span:not(.markedContent) {+ --font-height: 0;+ --scale-x: 1;+ --rotate: 0deg;+ font-size: calc(var(--text-scale-factor) * var(--font-height));+ transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv));+}+[data-pdf-text-layer] .markedContent {+ display: contents;+}+[data-pdf-text-layer] ::selection {+ background: #4a90e266;+}+[data-pdf-text-layer] .pdf-find-match {+ background: #ffc80066;+}diff --git a/apps/web/src/components/files/readBoundedDocument.ts b/apps/web/src/components/files/readBoundedDocument.tsnew file mode 100644index 00000000000..5b9276009d4--- /dev/null+++ b/apps/web/src/components/files/readBoundedDocument.ts@@ -0,0 +1,26 @@+export async function readBoundedDocument(+ src: string,+ signal: AbortSignal,+ limit: number,+ cache: RequestCache = "default",+) {+ const response = await fetch(src, { signal, cache });+ if (!response.ok || Number(response.headers.get("content-length")) > limit)+ throw new Error("This file is unavailable or too large to preview.");+ const reader = response.body?.getReader();+ if (!reader) throw new Error("This file is unavailable.");+ const chunks: Uint8Array<ArrayBuffer>[] = [];+ let size = 0;+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ size += value.length;+ if (size > limit) throw new Error("This file is too large to preview.");+ chunks.push(value);+ }+ } finally {+ await reader.cancel();+ }+ return new Blob(chunks).arrayBuffer();+}diff --git a/apps/web/src/pierre-icons.test.ts b/apps/web/src/pierre-icons.test.tsindex 1379100702c..0ffceec7013 100644--- a/apps/web/src/pierre-icons.test.ts+++ b/apps/web/src/pierre-icons.test.ts@@ -31,6 +31,28 @@ describe("Pierre file icons", () => {);});+ it.each([+ ["pdf", "pdf"],+ ["doc", "word"],+ ["docx", "word"],+ ["odt", "word"],+ ["rtf", "word"],+ ["xls", "spreadsheet"],+ ["xlsx", "spreadsheet"],+ ["ods", "spreadsheet"],+ ["csv", "spreadsheet"],+ ["tsv", "spreadsheet"],+ ["ppt", "slides"],+ ["pptx", "slides"],+ ["odp", "slides"],+ ["epub", "epub"],+ ])("uses the document family icon for %s", (extension, family) => {+ for (const path of [`report.${extension}`, `folder/REPORT.${extension.toUpperCase()}`]) {+ assert.equal(resolvePierreIconForEntry(path, "file")?.name, `t3-file-icon-${family}`);+ assert.isTrue(hasSpecificPierreIconForFileName(path));+ }+ });+it("ships every custom icon referenced by the extended resolver", () => {const customIconNames = new Set([diff --git a/apps/web/src/pierre-icons.ts b/apps/web/src/pierre-icons.tsindex ace85fc6355..bd98717caad 100644--- a/apps/web/src/pierre-icons.ts+++ b/apps/web/src/pierre-icons.ts@@ -13,6 +13,14 @@ export interface PierreIconResolution {const PIERRE_ICON_SPRITE_ID = "t3code-pierre-file-icon-sprite";+const DOCUMENT_ICON_COLORS: Readonly<Record<string, string>> = {+ "t3-file-icon-pdf": "light-dark(#d52c36, #ff6762)",+ "t3-file-icon-word": "light-dark(#1a85d4, #69b1ff)",+ "t3-file-icon-spreadsheet": "light-dark(#199f43, #5ecc71)",+ "t3-file-icon-slides": "light-dark(#d47628, #ffa359)",+ "t3-file-icon-epub": "light-dark(#693acf, #9d6afb)",+};+const T3_FILE_ICON_SPRITE = `<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" aria-hidden="true"><!-- Lucide Film icon, ISC license. -->@@ -41,6 +49,48 @@ const T3_FILE_ICON_SPRITE = `<symbol id="t3-file-icon-xml" viewBox="0 0 24 24"><path fill="none" style="stroke: light-dark(#d47628, #ffa359)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="m18 16 4-4-4-4M6 8l-4 4 4 4M14.5 4l-5 16" /></symbol>+ <!-- Lucide File Type, File Text, File Spreadsheet, Presentation and Book Open icons, ISC license. -->+ <symbol id="t3-file-icon-pdf" viewBox="0 0 24 24">+ <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-pdf"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />+ <path d="M14 2v5a1 1 0 0 0 1 1h5" />+ <path d="M11 18h2" />+ <path d="M12 12v6" />+ <path d="M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5" />+ </g>+ </symbol>+ <symbol id="t3-file-icon-word" viewBox="0 0 24 24">+ <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-word"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />+ <path d="M14 2v5a1 1 0 0 0 1 1h5" />+ <path d="M10 9H8" />+ <path d="M16 13H8" />+ <path d="M16 17H8" />+ </g>+ </symbol>+ <symbol id="t3-file-icon-spreadsheet" viewBox="0 0 24 24">+ <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-spreadsheet"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />+ <path d="M14 2v5a1 1 0 0 0 1 1h5" />+ <path d="M8 13h2" />+ <path d="M14 13h2" />+ <path d="M8 17h2" />+ <path d="M14 17h2" />+ </g>+ </symbol>+ <symbol id="t3-file-icon-slides" viewBox="0 0 24 24">+ <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-slides"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M2 3h20" />+ <path d="M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3" />+ <path d="m7 21 5-5 5 5" />+ </g>+ </symbol>+ <symbol id="t3-file-icon-epub" viewBox="0 0 24 24">+ <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-epub"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M12 7v14" />+ <path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />+ </g>+ </symbol><!-- Language logos from Simple Icons, CC0. --><symbol id="t3-file-icon-csharp" viewBox="0 0 24 24"><path style="fill: light-dark(#693acf, #9d6afb)" d="M1.194 7.543v8.913c0 1.103.588 2.122 1.544 2.674l7.718 4.456a3.086 3.086 0 0 0 3.088 0l7.718-4.456a3.087 3.087 0 0 0 1.544-2.674V7.543a3.084 3.084 0 0 0-1.544-2.673L13.544.414a3.086 3.086 0 0 0-3.088 0L2.738 4.87a3.085 3.085 0 0 0-1.544 2.673Zm5.403 2.914v3.087a.77.77 0 0 0 .772.772.773.773 0 0 0 .772-.772.773.773 0 0 1 1.317-.546.775.775 0 0 1 .226.546 2.314 2.314 0 1 1-4.631 0v-3.087c0-.615.244-1.203.679-1.637a2.312 2.312 0 0 1 3.274 0c.434.434.678 1.023.678 1.637a.769.769 0 0 1-.226.545.767.767 0 0 1-1.091 0 .77.77 0 0 1-.226-.545.77.77 0 0 0-.772-.772.771.771 0 0 0-.772.772Zm12.35 3.087a.77.77 0 0 1-.772.772h-.772v.772a.773.773 0 0 1-1.544 0v-.772h-1.544v.772a.773.773 0 0 1-1.317.546.775.775 0 0 1-.226-.546v-.772H12a.771.771 0 1 1 0-1.544h.772v-1.543H12a.77.77 0 1 1 0-1.544h.772v-.772a.773.773 0 0 1 1.317-.546.775.775 0 0 1 .226.546v.772h1.544v-.772a.773.773 0 0 1 1.544 0v.772h.772a.772.772 0 0 1 0 1.544h-.772v1.543h.772a.776.776 0 0 1 .772.772Zm-3.088-2.315h-1.544v1.543h1.544v-1.543Z" />@@ -95,6 +145,20 @@ export const T3_PIERRE_ICONS = {...Object.fromEntries(VIDEO_FILE_EXTENSIONS.map((extension) => [extension, "t3-file-icon-video"]),),+ pdf: "t3-file-icon-pdf",+ doc: "t3-file-icon-word",+ docx: "t3-file-icon-word",+ odt: "t3-file-icon-word",+ rtf: "t3-file-icon-word",+ xls: "t3-file-icon-spreadsheet",+ xlsx: "t3-file-icon-spreadsheet",+ ods: "t3-file-icon-spreadsheet",+ csv: "t3-file-icon-spreadsheet",+ tsv: "t3-file-icon-spreadsheet",+ ppt: "t3-file-icon-slides",+ pptx: "t3-file-icon-slides",+ odp: "t3-file-icon-slides",+ epub: "t3-file-icon-epub",cs: "t3-file-icon-csharp",csx: "t3-file-icon-csharp",dart: "t3-file-icon-dart",@@ -180,6 +244,11 @@ export function resolvePierreIconForEntry(: icon;}+export function documentIconColorForFileName(fileName: string) {+ const icon = resolvePierreIconForEntry(fileName, "file");+ return icon ? DOCUMENT_ICON_COLORS[icon.name] : undefined;+}+export function hasSpecificPierreIconForFileName(fileName: string): boolean {return resolvePierreIconForEntry(fileName, "file")?.token !== "default";}diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex a155ac5917d..67853de8063 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -11,6 +11,7 @@ import "vite-plus/test/config";import { defineConfig, type Connect, type Plugin } from "vite-plus";import * as Hash from "effect/Hash";import pkg from "./package.json" with { type: "json" };+import pdfjsPkg from "pdfjs-dist/package.json" with { type: "json" };import {DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES,@@ -112,9 +113,11 @@ const browserTestProject = {"@betteroffice/xlsx","@betteroffice/xlsx/headless","fast-xml-parser",+ "entities","dompurify","heic-to/next","jszip",+ "pdfjs-dist","sql.js","tiff",],@@ -351,9 +354,19 @@ export default defineConfig(() => {sourcemap: buildSourcemap,rolldownOptions: {output: {+ // PDF.js resolves decoder modules and ICC data relative to wasmUrl.+ assetFileNames: (asset) =>+ asset.originalFileNames.some((path) => /[/\\]pdfjs-dist[/\\]wasm[/\\]/.test(path))+ ? `assets/pdfjs-${pdfjsPkg.version}/[name][extname]`+ : "assets/[name]-[hash][extname]",codeSplitting: {// Preview imports must not fold shared file icons back into main.groups: [+ {+ name: "react",+ test: /\/node_modules\/(?:react|react-dom|scheduler)\//,+ includeDependenciesRecursively: false,+ },{name: "icons",test: /\/(?:components\/chat\/PierreEntryIcon\.tsx|pierre-icons\.ts|mediaPreview\.ts)$/,diff --git a/packages/shared/src/filePreview.test.ts b/packages/shared/src/filePreview.test.tsindex ef63070eeea..b6f4fc94087 100644--- a/packages/shared/src/filePreview.test.ts+++ b/packages/shared/src/filePreview.test.ts@@ -68,6 +68,12 @@ describe("workspace file previews", () => {"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation",],+ ["notes.odt", "odt", "application/vnd.oasis.opendocument.text"],+ ["budget.ods", "ods", "application/vnd.oasis.opendocument.spreadsheet"],+ ["deck.odp", "odp", "application/vnd.oasis.opendocument.presentation"],+ ["notes.rtf", "rtf", "application/rtf"],+ ["guide.epub", "epub", "application/epub+zip"],+ ["analysis.ipynb", "ipynb", "application/x-ipynb+json"],])("recognizes Office assets at literal path %s", (name, kind, mimeType) => {expect(officePreviewKind({ name })).toBe(kind);expect(filePreviewKind({ name, mimeType: "application/octet-stream" })).toBe(kind);@@ -85,6 +91,9 @@ describe("workspace file previews", () => {"report.xlsx?download=1","slides%2Epptx","report.docm",+ "guide.epub?download=1",+ "analysis.ipynb#notes.txt",+ "report.odt.ts","slides.ppt",])("rejects non-preview path %s", (path) => {expect(isWorkspacePreviewEntryPath(path)).toBe(false);@@ -145,8 +154,10 @@ describe("attachment preview classification", () => {["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"],+ ["notes.rtf", "application/rtf", "rtf"],+ ["notes.rtf", "", "rtf"],+ ["download", "text/rtf", "rtf"],+ ["analysis.IPYNB", "application/json", "ipynb"],["clip.weba", "", "audio"],["image.bmp", "application/octet-stream", "image"],["photo.heic", "application/octet-stream", "image"],@@ -165,7 +176,7 @@ 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", "7z", "rar"])(+ it.each(["doc", "xls", "ppt", "7z", "rar"])("retains the binary fallback for %s, which opencode does not render",(extension) => {expect(filePreviewKind({ name: `sample.${extension}` })).toBe("unsupported");diff --git a/packages/shared/src/filePreview.ts b/packages/shared/src/filePreview.tsindex e9871fb698a..4155252a12a 100644--- a/packages/shared/src/filePreview.ts+++ b/packages/shared/src/filePreview.ts@@ -25,6 +25,12 @@ export type FilePreviewKind =| "docx"| "xlsx"| "pptx"+ | "odt"+ | "ods"+ | "odp"+ | "rtf"+ | "epub"+ | "ipynb"| "text"| "unsupported";@@ -54,7 +60,6 @@ export function filePreviewKind(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";@@ -132,6 +137,12 @@ 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",+ odt: "application/vnd.oasis.opendocument.text",+ ods: "application/vnd.oasis.opendocument.spreadsheet",+ odp: "application/vnd.oasis.opendocument.presentation",+ rtf: "application/rtf",+ epub: "application/epub+zip",+ ipynb: "application/x-ipynb+json",} as const;export type OfficePreviewKind = keyof typeof OFFICE_MIME_TYPES;@@ -141,10 +152,14 @@ export function officePreviewKind(file: {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 === "text/rtf") return "rtf";+ for (const kind of Object.keys(OFFICE_MIME_TYPES) as OfficePreviewKind[]) {if (mime === OFFICE_MIME_TYPES[kind]) return kind;if (- (!mime || mime === "application/octet-stream" || mime === "text/plain") &&+ (!mime ||+ mime === "application/octet-stream" ||+ mime === "text/plain" ||+ (kind === "ipynb" && mime === "application/json")) &&file.name.toLowerCase().endsWith(`.${kind}`))return kind;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex de0c270b07b..9c7ff560c0e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1136,6 +1136,9 @@ importers:effect:specifier: 4.0.5version: 4.0.5+ entities:+ specifier: 8.1.0+ version: 8.1.0fast-xml-parser:specifier: 5.7.3version: 5.7.3@@ -1169,6 +1172,9 @@ importers:morphicons:specifier: ^1.7.1version: 1.7.1([email protected]([email protected](@babel/[email protected]([email protected]))(@react-native/[email protected](@babel/[email protected]([email protected]))([email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected]([email protected]))(@react-native/[email protected](@babel/[email protected]([email protected]))([email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ pdfjs-dist:+ specifier: 6.4.299+ version: 6.4.299pele:specifier: ^1.8.0version: 1.8.0@@ -4558,6 +4564,81 @@ packages:'@types/node':optional: true+ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==}+ engines: {node: '>= 10'}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==}+ engines: {node: '>= 10'}+'@napi-rs/[email protected]':resolution: {integrity: sha512-pl76hJvdYUBn6I24bXiOBMA9nbDapo3I5B+f3OorjDU4dUMSypXeKbOVehJe8fhgTiH24flMyTS3aAIy43xegQ==}engines: {node: '>= 10'}@@ -10375,6 +10456,10 @@ packages:resolution: {integrity: sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A==}+ resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}+ engines: {node: '>=22.13.0 || >=24'}+resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==}engines: {node: '>=12', npm: '>=6'}@@ -14793,6 +14878,54 @@ snapshots:optionalDependencies:'@types/node': 24.12.4+ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optionalDependencies:+ '@napi-rs/canvas-android-arm64': 1.0.13+ '@napi-rs/canvas-darwin-arm64': 1.0.13+ '@napi-rs/canvas-darwin-x64': 1.0.13+ '@napi-rs/canvas-linux-arm-gnueabihf': 1.0.13+ '@napi-rs/canvas-linux-arm64-gnu': 1.0.13+ '@napi-rs/canvas-linux-arm64-musl': 1.0.13+ '@napi-rs/canvas-linux-riscv64-gnu': 1.0.13+ '@napi-rs/canvas-linux-x64-gnu': 1.0.13+ '@napi-rs/canvas-linux-x64-musl': 1.0.13+ '@napi-rs/canvas-win32-arm64-msvc': 1.0.13+ '@napi-rs/canvas-win32-x64-msvc': 1.0.13+ optional: true+'@napi-rs/[email protected]':optional: true@@ -20858,6 +20991,10 @@ snapshots:dependencies:through: 2.3.8+ optionalDependencies:+ '@napi-rs/canvas': 1.0.13+diff --git a/third-party-licenses.config.json b/third-party-licenses.config.jsonindex 313d1502e3e..e6d38a17e2d 100644--- a/third-party-licenses.config.json+++ b/third-party-licenses.config.json@@ -229,6 +229,12 @@}],"packageOverrides": [+ {+ "name": "entities",+ "version": "8.1.0",+ "license": "BSD-2-Clause",+ "sourceUrl": "https://github.com/fb55/entities"+ },{"name": "@nodable/entities","version": "2.1.1",@@ -304,6 +310,12 @@]}},+ {+ "name": "pdfjs-dist",+ "version": "6.4.299",+ "license": "Apache-2.0",+ "sourceUrl": "https://github.com/mozilla/pdf.js"+ },{"name": "@betteroffice/fonts","version": "0.4.0",