@devries-cameron20 / t3code Mirror · read-only / commits / 34ead566d4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 17:00 UTC

feat(web): preview opendocument, epub, rich text, and notebooks (#21469)

maria committed Oct 26, 2026 at 02:17 UTC 34ead566d44881a29e7438b949a421636742ab20
28 files changed +3093 -92
apps/server/src/assets/AssetAccess.test.ts
+32
@@ -221,6 +221,12 @@ describe("AssetAccess", () => {
221 ["recording.webm", "video/webm"],
222 ["report.html", "text/html"],
223 ["report.pdf", "application/pdf"],
224 + ["notes.odt", "application/vnd.oasis.opendocument.text"],
225 + ["budget.ods", "application/vnd.oasis.opendocument.spreadsheet"],
226 + ["slides.odp", "application/vnd.oasis.opendocument.presentation"],
227 + ["notes.rtf", "application/rtf"],
228 + ["book.epub", "application/epub+zip"],
229 + ["analysis.ipynb", "application/x-ipynb+json"],
230 ["tone.wav", "audio/wav"],
231 ["tone.webm-audio", "audio/webm"],
232 ["archive.zip", "application/zip"],
@@ -944,6 +950,20 @@ describe("AssetAccess", () => {
950 expect(yield* resolveAsset(token, ".env")).toBeNull();
951 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
952 for (const extension of [
953 + "odt",
954 + "ods",
955 + "odp",
956 + "rtf",
957 + "epub",
958 + "ipynb",
959 + "zip",
960 + "jar",
961 + "tar",
962 + "gz",
963 + "tgz",
964 + "sqlite",
965 + "sqlite3",
966 + "db",
967 "docx",
968 "xlsx",
969 "pptx",
@@ -1018,6 +1038,12 @@ describe("AssetAccess", () => {
1038 );
1039 for (const extension of [
1040 "pdf",
1041 + "odt",
1042 + "ods",
1043 + "odp",
1044 + "rtf",
1045 + "epub",
1046 + "ipynb",
1047 "png",
1048 "bmp",
1049 "heic",
@@ -1082,6 +1108,12 @@ describe("AssetAccess", () => {
1108 "report.docx",
1109 "workbook.xlsx",
1110 "slides.pptx",
1111 + "notes.odt",
1112 + "budget.ods",
1113 + "slides.odp",
1114 + "notes.rtf",
1115 + "book.epub",
1116 + "analysis.ipynb",
1117 "specimen.ttf",
1118 "specimen.otf",
1119 "specimen.woff",
apps/web/package.json
+2
@@ -61,6 +61,7 @@
61 "culori": "^4.0.2",
62 "dompurify": "^3.4.16",
63 "effect": "catalog:",
64 + "entities": "8.1.0",
65 "fast-xml-parser": "5.7.3",
66 "hast-util-to-html": "^9.0.5",
67 "hast-util-to-jsx-runtime": "^2.3.6",
@@ -72,6 +73,7 @@
73 "lucide": "^0.564.0",
74 "lucide-react": "^0.564.0",
75 "morphicons": "^1.7.1",
76 + "pdfjs-dist": "6.4.299",
77 "pele": "^1.8.0",
78 "react": "catalog:",
79 "react-dom": "catalog:",
apps/web/src/components/ComposerPromptEditorTiptap.tsx
+4
@@ -1,3 +1,4 @@
1 +import { documentIconColorForFileName } from "~/pierre-icons";
2 import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";
3 import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
4 import {
@@ -45,6 +46,7 @@ import {
46 useLayoutEffect,
47 useRef,
48 useState,
49 + type CSSProperties,
50 type KeyboardEvent as ReactKeyboardEvent,
51 type RefObject,
52 } from "react";
@@ -260,9 +262,11 @@ const ComposerMentionExtension = Node.create({
262 function ComposerMentionNodeView({ node }: NodeViewProps) {
263 const actions = use(ComposerContextActionsContext);
264 const path = (node.attrs.path as string) ?? "";
265 + const accent = documentIconColorForFileName(path);
266 const chip = (
267 <ContextChip
268 kind="mention"
269 + style={accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined}
270 dir="ltr"
271 render={<button type="button" />}
272 onClick={() => actions.openMention(path)}
apps/web/src/components/chat/MarkdownFileLink.tsx
+6 -1
@@ -5,12 +5,13 @@ import {
5 type AtomCommandResult,
6 } from "@t3tools/client-runtime/state/runtime";
7 import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
8 -import { memo, type MouseEvent as ReactMouseEvent } from "react";
8 +import { memo, type CSSProperties, type MouseEvent as ReactMouseEvent } from "react";
9
10 import { readLocalApi } from "../../localApi";
11 import { cn } from "../../lib/utils";
12 import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links";
13 import type { markdownFileCopyPaths } from "../../markdownFileHostPath";
14 +import { documentIconColorForFileName } from "../../pierre-icons";
15 import { ContextChip } from "../ContextChip";
16 import { stackedThreadToast, toastManager } from "../ui/toast";
17 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -320,6 +321,8 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
321 canOpenInBrowser,
322 canOpenInPanel,
323 });
324 + const accent = documentIconColorForFileName(iconPath);
325 + const chipStyle = accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined;
326
327 return (
328 <Tooltip>
@@ -331,6 +334,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
334 dir="ltr"
335 render={<a href={href} />}
336 className={MARKDOWN_FILE_LINK_CLASS_NAME}
337 + style={chipStyle}
338 data-markdown-copy={copyMarkdown}
339 onClick={(event) => {
340 event.preventDefault();
@@ -362,6 +366,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
366 aria-label={`File options for ${label}`}
367 aria-haspopup="menu"
368 className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")}
369 + style={chipStyle}
370 data-markdown-copy={copyMarkdown}
371 onClick={handleContextMenu}
372 onContextMenu={handleContextMenu}
apps/web/src/components/chat/UserMessageContextChips.tsx
+4 -1
@@ -1,3 +1,4 @@
1 +import { documentIconColorForFileName } from "~/pierre-icons";
2 import { isSvgAttachment } from "@t3tools/shared/image";
3 import { useRenderedAppearance } from "../../hooks/useTheme";
4 import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
@@ -5,7 +6,7 @@ import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
6 import { useRightPanelStore } from "~/rightPanelStore";
7 import { COMPOSER_CONTEXT_KINDS } from "@t3tools/contracts";
8 import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
8 -import { use, type ReactNode } from "react";
9 +import { use, type CSSProperties, type ReactNode } from "react";
10 import { FileDiff } from "@pierre/diffs/react";
11 import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
12 import {
@@ -61,12 +62,14 @@ function UserMessageMentionChip(props: {
62 copyMarkdown: string;
63 }) {
64 const ctx = use(TimelineRowCtx);
65 + const accent = documentIconColorForFileName(props.record.path);
66 return (
67 <Tooltip>
68 <TooltipTrigger
69 render={
70 <ContextChip
71 kind="mention"
72 + style={accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined}
73 render={<button type="button" />}
74 aria-label={`Preview ${props.record.path}`}
75 data-markdown-copy={props.copyMarkdown}
apps/web/src/components/contextChipParts.tsx
+3
@@ -9,6 +9,7 @@ import {
9 type ReactNode,
10 } from "react";
11 import { useAssetUrlState } from "~/assets/assetUrls";
12 +import { documentIconColorForFileName } from "~/pierre-icons";
13
14 import { PULL_REQUEST_STATE_PRESENTATION } from "~/components/pullRequest/pullRequestIcons";
15 import type { PullRequestContextDisplayState } from "~/lib/composerContextRecords";
@@ -242,6 +243,7 @@ export function FileChip(props: {
243 }) {
244 if (props.svgPreview && !props.unresolved) return <SvgFileChip {...props} />;
245 const content = <FileChipContent {...props} />;
246 + const accent = props.isVideo ? undefined : documentIconColorForFileName(props.name);
247 const state = props.unresolved
248 ? ("unresolved" as const)
249 : props.error
@@ -249,6 +251,7 @@ export function FileChip(props: {
251 : null;
252 const attributes = {
253 kind: props.isVideo ? "video" : "file",
254 + style: accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined,
255 ...(state ? { state } : {}),
256 "aria-label": [props.accessibleLabel, props.suffix].filter(Boolean).join(", "),
257 "data-markdown-copy": props.copyMarkdown,
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+464
@@ -1,3 +1,4 @@
1 +import DocumentPages, { sanitizeDocumentHtml } from "./DocumentPages";
2 import { act, render, stubGlobal, type Screen } from "../../../test/render";
3 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4 import { describe, expect, it, vi } from "vite-plus/test";
@@ -2057,6 +2058,40 @@ describe("attachment HTML preview recovery", () => {
2058 });
2059 });
2060
2061 +describe("document output sanitization", () => {
2062 + it("fits saved HTML outputs to their content and resizes when the content changes", async () => {
2063 + await using screen = await render(
2064 + <DocumentPages html="<table><tr><td>42</td></tr></table>" name="Output" output />,
2065 + );
2066 + const frame = screen.container.querySelector("iframe")!;
2067 + await vi.waitFor(() => {
2068 + expect(frame.contentDocument?.querySelector("td")?.textContent).toBe("42");
2069 + expect(frame.clientHeight).toBeGreaterThan(32);
2070 + expect(frame.clientHeight).toBeLessThan(120);
2071 + });
2072 + const initialHeight = frame.clientHeight;
2073 + await screen.rerender(
2074 + <DocumentPages html={"<p>More saved output</p>".repeat(10)} name="Output" output />,
2075 + );
2076 + await vi.waitFor(() => {
2077 + expect(frame.contentDocument?.querySelectorAll("p")).toHaveLength(10);
2078 + expect(frame.clientHeight).toBeGreaterThan(initialHeight);
2079 + expect(frame.contentDocument!.body.scrollHeight).toBeLessThanOrEqual(frame.clientHeight);
2080 + });
2081 + });
2082 +
2083 + it("preserves table content and raster data while removing scripts and network resources", () => {
2084 + const html = sanitizeDocumentHtml(
2085 + '<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>',
2086 + );
2087 + const doc = new DOMParser().parseFromString(html, "text/html");
2088 + expect(doc.querySelector("td")?.textContent).toBe("Research");
2089 + expect(doc.images).toHaveLength(1);
2090 + expect(doc.images[0]!.getAttribute("src")).toBe("data:image/png;base64,iVBORw0KGgo=");
2091 + expect(doc.querySelector("script,style,iframe,a,[onerror]")).toBeNull();
2092 + expect(html).not.toContain("https://");
2093 + });
2094 +});
2095 it("opens a known empty attachment even when its range response is inaccessible", async () => {
2096 refresh.mockResolvedValue("https://unreachable.invalid/empty.txt");
2097 await using screen = await render(
@@ -2295,3 +2330,432 @@ it("toggles a Mermaid attachment between diagram and source through the lazy pre
2330 );
2331 expect(screen.container.querySelector('[role="alert"]')).toBeNull();
2332 });
2333 +
2334 +it("navigates, searches, zooms, and selects mixed-height PDF pages", async () => {
2335 + const objects = [
2336 + "<< /Type /Catalog /Pages 2 0 R >>",
2337 + "<< /Type /Pages /Count 3 /Kids [3 0 R 5 0 R 7 0 R] >>",
2338 + ];
2339 + for (const [index, title] of [
2340 + "Quarterly outlook",
2341 + "Delivery milestones",
2342 + "Budget and risks",
2343 + ].entries()) {
2344 + 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`;
2345 + objects.push(
2346 + `<< /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 >>`,
2347 + `<< /Length ${text.length} >>\nstream\n${text}\nendstream`,
2348 + );
2349 + }
2350 + objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
2351 + objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>");
2352 + let source = "%PDF-1.4\n";
2353 + const offsets = [0];
2354 + for (const [index, object] of objects.entries()) {
2355 + offsets.push(source.length);
2356 + source += `${index + 1} 0 obj\n${object}\nendobj\n`;
2357 + }
2358 + const xref = source.length;
2359 + source += `xref\n0 11\n0000000000 65535 f \n${offsets
2360 + .slice(1)
2361 + .map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)
2362 + .join("")}trailer\n<< /Size 11 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
2363 + const file = new Blob([source], { type: "application/pdf" });
2364 + const { default: PdfViewer } = await import("./PdfViewer");
2365 + const url = URL.createObjectURL(file);
2366 + try {
2367 + await using screen = await render(
2368 + <div style={{ display: "flex", height: 600, width: 320 }}>
2369 + <PdfViewer src={url} title="Planning PDF" />
2370 + </div>,
2371 + );
2372 + await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"), {
2373 + timeout: 15_000,
2374 + });
2375 + const region = screen.container.querySelector<HTMLElement>('[role="region"]')!;
2376 + await vi.waitFor(() => {
2377 + expect(region.scrollWidth).toBe(region.clientWidth);
2378 + expect(region.querySelector("canvas")!.getBoundingClientRect().width).toBeLessThan(
2379 + region.clientWidth,
2380 + );
2381 + expect(screen.container.textContent).toContain("Fit width");
2382 + });
2383 + await act(() => {
2384 + (screen.container.firstElementChild as HTMLElement).style.width = "500px";
2385 + });
2386 + await vi.waitFor(() =>
2387 + expect(region.querySelector("canvas")!.getBoundingClientRect().width).toBe(468),
2388 + );
2389 + await screen.getByRole("button", { name: "Next page", exact: true }).click();
2390 + await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
2391 + await screen.getByRole("button", { name: "Previous page", exact: true }).click();
2392 + await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"));
2393 + await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
2394 + await vi.waitFor(() => expect(region.scrollWidth).toBeGreaterThan(region.clientWidth));
2395 + await screen.getByRole("button", { name: "Fit width", exact: true }).click();
2396 + await vi.waitFor(() => expect(region.scrollWidth).toBe(region.clientWidth));
2397 + await screen.getByRole("searchbox", { name: "Find in PDF" }).fill("Quarterly outlook");
2398 + await vi.waitFor(() => {
2399 + expect(screen.container.querySelector('[role="status"]')?.textContent).toBe("1/1");
2400 + expect(
2401 + Array.from(region.querySelectorAll(".pdf-find-match")).map((span) => span.textContent),
2402 + ).toEqual(["Quarter", "ly outlook"]);
2403 + });
2404 + await screen.getByRole("searchbox", { name: "Find in PDF" }).fill("Budget");
2405 + await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
2406 + await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
2407 + await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
2408 + await vi.waitFor(() => {
2409 + const span = Array.from(screen.container.querySelectorAll("[data-pdf-text-layer] span")).find(
2410 + (node) => node.textContent === "Budget and risks",
2411 + );
2412 + expect(span).toBeDefined();
2413 + const textBounds = span!.getBoundingClientRect();
2414 + const pageBounds = span!.parentElement!.getBoundingClientRect();
2415 + expect(textBounds.width).toBeGreaterThan(0);
2416 + expect(textBounds.height).toBeGreaterThan(0);
2417 + expect(textBounds.left).toBeGreaterThanOrEqual(pageBounds.left - 1);
2418 + expect(textBounds.top).toBeGreaterThanOrEqual(pageBounds.top - 1);
2419 + expect(textBounds.right).toBeLessThanOrEqual(pageBounds.right + 1);
2420 + expect(textBounds.bottom).toBeLessThanOrEqual(pageBounds.bottom + 1);
2421 + const range = document.createRange();
2422 + range.selectNodeContents(span!);
2423 + const selection = window.getSelection()!;
2424 + selection.removeAllRanges();
2425 + selection.addRange(range);
2426 + expect(selection.toString()).toBe("Budget and risks");
2427 + expect(getComputedStyle(span!).userSelect).toBe("text");
2428 + selection.removeAllRanges();
2429 + });
2430 + await screen.getByRole("button", { name: "Fit width", exact: true }).click();
2431 + await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
2432 + await screen.getByRole("searchbox", { name: "Find in PDF" }).fill(" ");
2433 + await vi.waitFor(() =>
2434 + expect(screen.container.querySelector('[role="status"]')?.textContent).toBe("0/0"),
2435 + );
2436 + } finally {
2437 + URL.revokeObjectURL(url);
2438 + }
2439 +});
2440 +it("mounts a bounded set of saved notebook outputs as the reader scrolls", async () => {
2441 + const notebook = {
2442 + nbformat: 4,
2443 + metadata: {},
2444 + cells: Array.from({ length: 20 }, (_, cell) => ({
2445 + cell_type: "code",
2446 + source: [],
2447 + metadata: {},
2448 + outputs: Array.from({ length: 100 }, (_, output) => ({
2449 + output_type: "display_data",
2450 + data: { "text/html": `<p>saved ${cell}-${output}</p>` },
2451 + })),
2452 + })),
2453 + };
2454 + const file = new Blob([JSON.stringify(notebook)]);
2455 + await using screen = await render(
2456 + <div style={{ display: "flex", height: 400, width: 600 }}>
2457 + <AttachmentFilePreview
2458 + name="observations.ipynb"
2459 + mimeType="application/json"
2460 + sizeBytes={file.size}
2461 + file={file}
2462 + />
2463 + </div>,
2464 + );
2465 + await vi.waitFor(() =>
2466 + expect(screen.container.querySelectorAll("iframe").length).toBeGreaterThan(0),
2467 + );
2468 + expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16);
2469 + const first = screen.container.querySelector("iframe")!;
2470 + expect(first.srcdoc).toContain("saved 0-0");
2471 + const viewport = screen.container.querySelector<HTMLElement>(".scrollbar-gutter-both")!;
2472 + await act(() => {
2473 + viewport.scrollTop = viewport.scrollHeight;
2474 + });
2475 + await vi.waitFor(() => {
2476 + expect(
2477 + [...screen.container.querySelectorAll("iframe")].some((frame) =>
2478 + frame.srcdoc.includes("saved 19-99"),
2479 + ),
2480 + ).toBe(true);
2481 + expect(first.isConnected).toBe(false);
2482 + });
2483 + expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16);
2484 + await act(() => {
2485 + viewport.scrollTop = 0;
2486 + });
2487 + await vi.waitFor(() =>
2488 + expect(screen.container.querySelector("iframe")?.srcdoc).toContain("saved 0-0"),
2489 + );
2490 +});
2491 +
2492 +it.each([
2493 + [String.raw`{\rtf1\uc1\u945{\b bold}Hello}`, "αboldHello"],
2494 + [String.raw`{\rtf1\uc1{\u945}Hello}`, "αHello"],
2495 + [
2496 + String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset204 Cyrillic;}{\f1\fcharset0 Latin;}}\f0\'c0{\f1\'c0}\'c1}`,
2497 + "АÀБ",
2498 + ],
2499 + [String.raw`{\rtf1\ansi\deff1{\fonttbl{\f1\fcharset204 Cyrillic;}}\'c0\plain\'c1}`, "АБ"],
2500 +])("retains RTF grouped Unicode and font text in %s", async (source, expected) => {
2501 + const { openRtf } = await import("./extendedDocumentPreview");
2502 + const result = openRtf(new TextEncoder().encode(source).buffer);
2503 + if (result.type !== "document") throw new Error("Expected rich text document");
2504 + const html = result.pages.map((page) => page.html).join("");
2505 + expect(new DOMParser().parseFromString(html, "text/html").body.textContent).toBe(expected);
2506 +});
2507 +
2508 +it.each(["odt", "odp"] as const)("preserves rendered %s spaces and tabs", async (kind) => {
2509 + const archive = new JSZip().file(
2510 + "content.xml",
2511 + `<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>`,
2512 + );
2513 + const bytes = await archive.generateAsync({ type: "arraybuffer" });
2514 + const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
2515 + type: "module",
2516 + });
2517 + try {
2518 + const result = await new Promise<OfficeWorkerResult>((resolve) => {
2519 + worker.addEventListener(
2520 + "message",
2521 + (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
2522 + { once: true },
2523 + );
2524 + worker.postMessage({ type: "open", kind, bytes }, [bytes]);
2525 + });
2526 + if (result.type !== "document") throw new Error("Expected document");
2527 + await using screen = await render(
2528 + <DocumentPages html={result.pages[0]!.html} name="spacing" output />,
2529 + );
2530 + await vi.waitFor(() => {
2531 + const doc = screen.container.querySelector("iframe")?.contentDocument;
2532 + const spans = doc?.querySelectorAll<HTMLElement>("span[data-odf-whitespace]");
2533 + expect(doc?.querySelector("p")?.textContent).toBe("A B\tC");
2534 + expect(spans).toHaveLength(2);
2535 + for (const span of spans!) {
2536 + expect(doc!.defaultView!.getComputedStyle(span).whiteSpace).toBe("pre-wrap");
2537 + expect(span.getBoundingClientRect().width).toBeGreaterThan(0);
2538 + }
2539 + expect(spans![0]!.getBoundingClientRect().width).toBeGreaterThan(10);
2540 + });
2541 + } finally {
2542 + worker.terminate();
2543 + }
2544 +});
2545 +
2546 +it.each(["rtf", "epub", "ods"] as const)(
2547 + "preserves %s document text through the worker and attachment viewer",
2548 + async (kind) => {
2549 + const archive = new JSZip();
2550 + if (kind === "epub") {
2551 + archive.file(
2552 + "META-INF/container.xml",
2553 + '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',
2554 + );
2555 + archive.file(
2556 + "book.opf",
2557 + '<package><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>',
2558 + );
2559 + archive.file(
2560 + "chapter.xhtml",
2561 + "<html><head><title>Handbook</title></head><body><p>first<br/>second<br/>third</p><hr/></body></html>",
2562 + );
2563 + } else if (kind === "ods") {
2564 + archive.file(
2565 + "content.xml",
2566 + '<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>',
2567 + );
2568 + }
2569 + const file =
2570 + kind === "rtf"
2571 + ? new Blob([
2572 + 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}`,
2573 + ])
2574 + : await archive.generateAsync({ type: "blob" });
2575 + const bytes = await file.arrayBuffer();
2576 + const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
2577 + type: "module",
2578 + });
2579 + try {
2580 + const result = await new Promise<OfficeWorkerResult>((resolve) => {
2581 + worker.addEventListener(
2582 + "message",
2583 + (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
2584 + { once: true },
2585 + );
2586 + worker.postMessage({ type: "open", kind, bytes }, [bytes]);
2587 + });
2588 + if (kind === "ods") {
2589 + expect(result.type).toBe("ods");
2590 + if (result.type !== "ods") throw new Error("Expected spreadsheet");
2591 + expect(result.sheets[0]!.rows).toEqual([["North", "150"]]);
2592 + } else {
2593 + expect(result.type).toBe("document");
2594 + if (result.type !== "document") throw new Error("Expected document");
2595 + const body = new DOMParser().parseFromString(result.pages[0]!.html, "text/html").body;
2596 + if (kind === "epub") {
2597 + expect(body.querySelectorAll("br")).toHaveLength(2);
2598 + expect(body.querySelectorAll("hr")).toHaveLength(1);
2599 + } else {
2600 + expect(body.textContent).toContain("10–20 —•‘a’“b”");
2601 + expect(body.textContent).toContain("Name\tValue\t12\t34\t");
2602 + expect(body.textContent).toContain("Unicode:–end");
2603 + expect(body.textContent).not.toContain("hidden");
2604 + expect(body.querySelectorAll("br")).toHaveLength(3);
2605 + }
2606 + }
2607 + } finally {
2608 + worker.terminate();
2609 + }
2610 + await using screen = await render(
2611 + <div style={{ display: "flex", height: 400, width: 600 }}>
2612 + <AttachmentFilePreview
2613 + name={`report.${kind}`}
2614 + mimeType="application/octet-stream"
2615 + sizeBytes={file.size}
2616 + file={file}
2617 + />
2618 + </div>,
2619 + );
2620 + await vi.waitFor(() => {
2621 + if (kind === "ods") {
2622 + expect(screen.container.textContent).toContain("North");
2623 + expect(screen.container.textContent).toContain("150");
2624 + expect(screen.container.textContent).not.toContain("private note");
2625 + expect(screen.container.textContent).toContain("1 rows · 2 columns");
2626 + expect(screen.container.textContent).not.toContain("Limited to 500");
2627 + } else {
2628 + const frame = screen.container.querySelector("iframe");
2629 + expect(frame?.srcdoc).toContain(kind === "rtf" ? "10–20" : "first<br>second<br>third");
2630 + }
2631 + });
2632 + expect(screen.container.querySelector('[role="alert"]')).toBeNull();
2633 + },
2634 +);
2635 +
2636 +it.each(["epub", "odt", "ipynb", "html", "encoded-html"] as const)(
2637 + "bounds %s image pixels before returning browser markup",
2638 + async (kind) => {
2639 + const canvas = new OffscreenCanvas(2, 3);
2640 + canvas.getContext("2d");
2641 + const blob = await canvas.convertToBlob({ type: "image/png" });
2642 + for (const width of [2, 12000]) {
2643 + const image = await blob.arrayBuffer();
2644 + new DataView(image).setUint32(16, width);
2645 + new DataView(image).setUint32(20, width === 2 ? 3 : 12000);
2646 + const archive = new JSZip();
2647 + archive.file("cover.png", image);
2648 + if (kind === "epub") {
2649 + archive.file(
2650 + "META-INF/container.xml",
2651 + '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',
2652 + );
2653 + archive.file(
2654 + "book.opf",
2655 + '<package><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>',
2656 + );
2657 + archive.file(
2658 + "chapter.xhtml",
2659 + '<html><body><p>retained caption</p><img src="cover.png"/></body></html>',
2660 + );
2661 + } else
2662 + archive.file(
2663 + "content.xml",
2664 + '<office:document><office:text><text:p>retained caption</text:p><draw:image xlink:href="cover.png"/></office:text></office:document>',
2665 + );
2666 + const base64 = btoa(String.fromCharCode(...new Uint8Array(image)));
2667 + const bytes =
2668 + kind === "ipynb" || kind === "html" || kind === "encoded-html"
2669 + ? new TextEncoder().encode(
2670 + JSON.stringify({
2671 + nbformat: 4,
2672 + cells: [
2673 + {
2674 + cell_type: "code",
2675 + source: "plot()",
2676 + outputs: [
2677 + {
2678 + data: {
2679 + ...(kind === "html" || kind === "encoded-html"
2680 + ? {
2681 + "text/html": `<table><tr><td>retained caption</td></tr></table><img src="${kind === "encoded-html" ? "&#100ata" : "data"}:image/png;base64,${base64}">`,
2682 + }
2683 + : { "image/png": base64 }),
2684 + "text/plain": "retained caption",
2685 + },
2686 + },
2687 + ],
2688 + },
2689 + ],
2690 + }),
2691 + ).buffer
2692 + : await archive.generateAsync({ type: "arraybuffer" });
2693 + const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
2694 + type: "module",
2695 + });
2696 + try {
2697 + const result = await new Promise<OfficeWorkerResult>((resolve) => {
2698 + worker.addEventListener(
2699 + "message",
2700 + (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
2701 + { once: true },
2702 + );
2703 + worker.postMessage(
2704 + {
2705 + type: "open",
2706 + kind: kind === "html" || kind === "encoded-html" ? "ipynb" : kind,
2707 + bytes,
2708 + },
2709 + [bytes],
2710 + );
2711 + });
2712 + if (result.type === "notebook") {
2713 + const output = result.cells[0]!.outputs[0]!;
2714 + expect(output.kind).toBe(
2715 + width === 2 ? (kind === "html" || kind === "encoded-html" ? "html" : "image") : "text",
2716 + );
2717 + if (output.kind === "html") {
2718 + const rendered = new DOMParser().parseFromString(
2719 + sanitizeDocumentHtml(output.text),
2720 + "text/html",
2721 + );
2722 + expect(rendered.images).toHaveLength(1);
2723 + expect(rendered.querySelector("td")!.textContent).toBe("retained caption");
2724 + }
2725 + if (width !== 2) expect(result.cells[0]!.outputs[0]!.text).toBe("retained caption");
2726 + } else {
2727 + expect(result.type).toBe("document");
2728 + if (result.type !== "document") throw new Error("Expected document");
2729 + expect(result.pages[0]!.html.includes("<img")).toBe(width === 2);
2730 + expect(result.pages[0]!.html).toContain("retained caption");
2731 + }
2732 + } finally {
2733 + worker.terminate();
2734 + }
2735 + }
2736 + },
2737 +);
2738 +
2739 +it.each([
2740 + ["standardFontDataUrl", "FoxitSerif.pfb", "standard_fonts"],
2741 + ["cMapUrl", "78-EUC-H.bcmap", "cmaps"],
2742 + ["wasmUrl", "openjpeg.wasm", "wasm"],
2743 +])("validates PDF %s assets before decoding", async (kind, filename, directory) => {
2744 + const { BinaryDataFactory } = await import("./pdfDocument");
2745 + const factory = new BinaryDataFactory();
2746 + const fetchAsset = vi.fn(
2747 + async () =>
2748 + new Response("<html>app</html>", {
2749 + headers: { "content-type": "text/html; charset=utf-8" },
2750 + }),
2751 + );
2752 + using _fetch = stubGlobal("fetch", fetchAsset);
2753 + await expect(factory.fetch({ kind, filename })).rejects.toThrow(
2754 + `PDF ${directory} asset unavailable.`,
2755 + );
2756 + fetchAsset.mockImplementation(async () => new Response(new Uint8Array([1, 2, 3])));
2757 + await expect(factory.fetch({ kind, filename })).resolves.toEqual(new Uint8Array([1, 2, 3]));
2758 + await expect(factory.fetch({ kind, filename: "missing" })).rejects.toThrow(
2759 + `Unsupported PDF ${directory} asset.`,
2760 + );
2761 +});
apps/web/src/components/files/BrowserDocumentFrame.tsx
+38 -9
@@ -22,7 +22,17 @@ import {
22 matchesKeybindingShortcut,
23 normalizeEventKey,
24 } from "@t3tools/shared/keybindings";
25 -import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
25 +import {
26 + lazy,
27 + Suspense,
28 + useEffect,
29 + useEffectEvent,
30 + useLayoutEffect,
31 + useRef,
32 + useState,
33 +} from "react";
34 +import { isElectron } from "~/env";
35 +import { FileSurfaceLoading } from "./fileSurfaceChrome";
36
37 import { useOpenLink } from "~/browser/useOpenLink";
38 import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
@@ -61,9 +71,34 @@ const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
71 export const isPdfPreviewFile = (path: string): boolean =>
72 /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
73
74 +const PdfViewer = lazy(() => import("./PdfViewer"));
75 +
76 +function PdfDocument(props: { src: string; title: string }) {
77 + const [src] = useState(props.src);
78 + // The Electron shell does not enable PDF plugins. WebKit embeds on iOS
79 + // expose only the first page, even when pdfViewerEnabled reports support.
80 + const native =
81 + !isElectron &&
82 + navigator.pdfViewerEnabled &&
83 + !/iPad|iPhone|iPod/.test(navigator.userAgent) &&
84 + !(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
85 + return native ? (
86 + // oxlint-disable-next-line react/iframe-missing-sandbox -- Chromium's PDF plugin requires an unsandboxed frame; src is an exact-file asset grant.
87 + <iframe
88 + src={`${src.split("#", 1)[0]}#navpanes=0&view=FitH`}
89 + title={props.title}
90 + className="block h-full min-h-0 w-full flex-1 border-0 bg-white"
91 + />
92 + ) : (
93 + <Suspense fallback={<FileSurfaceLoading />}>
94 + <PdfViewer src={src} title={props.title} />
95 + </Suspense>
96 + );
97 +}
98 +
99 /**
100 * HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach
66 - * the app's session or storage. PDFs use the browser's native viewer.
101 + * the app's session or storage. PDFs use a native viewer or the lazy PDF.js fallback.
102 */
103 export function BrowserDocumentFrame(props: {
104 readonly src: string;
@@ -76,13 +111,7 @@ export function BrowserDocumentFrame(props: {
111 }) {
112 const key = props.documentKey ?? props.src;
113 return props.pdf ? (
79 - <embed
80 - key={props.src}
81 - src={props.src}
82 - type="application/pdf"
83 - title={props.title}
84 - className="min-h-0 w-full flex-1 border-0"
85 - />
114 + <PdfDocument key={key} src={props.src} title={props.title} />
115 ) : props.htmlRender ? (
116 <HtmlRenderDocument
117 key={key}
apps/web/src/components/files/DocumentPages.tsx new
+145
@@ -0,0 +1,145 @@
1 +import DOMPurify from "dompurify";
2 +import { MinusIcon, PlusIcon, RotateCcwIcon } from "lucide-react";
3 +import { FileSurfaceAction } from "./fileSurfaceChrome";
4 +import { useEffect, useRef, useState } from "react";
5 +import { useTheme } from "~/hooks/useTheme";
6 +import { observeResize } from "~/lib/observeResize";
7 +
8 +export function sanitizeDocumentHtml(source: string): string {
9 + const fragment = DOMPurify.sanitize(source, {
10 + RETURN_DOM_FRAGMENT: true,
11 + ALLOWED_TAGS: [
12 + "p",
13 + "h1",
14 + "h2",
15 + "h3",
16 + "h4",
17 + "h5",
18 + "h6",
19 + "div",
20 + "span",
21 + "strong",
22 + "b",
23 + "em",
24 + "i",
25 + "u",
26 + "s",
27 + "ul",
28 + "ol",
29 + "li",
30 + "blockquote",
31 + "pre",
32 + "code",
33 + "table",
34 + "thead",
35 + "tbody",
36 + "tr",
37 + "th",
38 + "td",
39 + "caption",
40 + "figure",
41 + "figcaption",
42 + "br",
43 + "hr",
44 + "sub",
45 + "sup",
46 + "dl",
47 + "dt",
48 + "dd",
49 + "img",
50 + ],
51 + ALLOWED_ATTR: ["src", "alt", "colspan", "rowspan", "data-odf-whitespace"],
52 + });
53 + for (const image of fragment.querySelectorAll("img")) {
54 + if (
55 + !/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/]*={0,2}$/i.test(
56 + image.getAttribute("src") ?? "",
57 + )
58 + )
59 + image.remove();
60 + }
61 + const container = document.createElement("div");
62 + container.append(fragment);
63 + return container.innerHTML;
64 +}
65 +
66 +function documentColors() {
67 + const style = getComputedStyle(document.documentElement);
68 + return ["background", "foreground", "card", "border"].map((token) =>
69 + style.getPropertyValue(`--${token}`),
70 + );
71 +}
72 +
73 +export default function DocumentPages(props: {
74 + readonly html: string;
75 + readonly name: string;
76 + readonly output?: boolean;
77 + readonly details?: string;
78 +}) {
79 + const { theme, resolvedTheme, themeHalves } = useTheme();
80 + const [colors, setColors] = useState(documentColors);
81 + // oxlint-disable-next-line t3code/react-effect-budget -- Read the host DOM's applied theme tokens so the sandboxed document receives the current palette.
82 + useEffect(() => {
83 + // The iframe cannot inherit the host palette across its sandbox boundary.
84 + // oxlint-disable-next-line react/set-state-in-effect -- Read tokens after useTheme applies the selected palette.
85 + setColors(documentColors());
86 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Theme values invalidate the palette read from the host DOM.
87 + }, [theme, resolvedTheme, themeHalves]);
88 + const [zoom, setZoom] = useState(1);
89 + const [outputHeight, setOutputHeight] = useState(0);
90 + const stopObserving = useRef<(() => void) | null>(null);
91 + // oxlint-disable-next-line t3code/react-effect-budget -- Disconnect the iframe body's resize observer when the document unmounts.
92 + useEffect(() => () => stopObserving.current?.(), []);
93 + const html = sanitizeDocumentHtml(props.html);
94 + 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>`;
95 + return (
96 + <>
97 + {!props.output ? (
98 + <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">
99 + <span className="min-w-0 flex-1 text-muted-foreground tabular-nums" role="status">
100 + {props.details}
101 + </span>
102 + <FileSurfaceAction
103 + label="Decrease reading size"
104 + disabled={zoom <= 0.5}
105 + onPress={() => setZoom((value) => Math.max(0.5, value - 0.25))}
106 + >
107 + <MinusIcon className="size-3.5" />
108 + </FileSurfaceAction>
109 + <span className="min-w-10 text-center tabular-nums">{Math.round(zoom * 100)}%</span>
110 + <FileSurfaceAction
111 + label="Increase reading size"
112 + disabled={zoom >= 2}
113 + onPress={() => setZoom((value) => Math.min(2, value + 0.25))}
114 + >
115 + <PlusIcon className="size-3.5" />
116 + </FileSurfaceAction>
117 + <FileSurfaceAction
118 + label="Reset reading size"
119 + disabled={zoom === 1}
120 + onPress={() => setZoom(1)}
121 + >
122 + <RotateCcwIcon className="size-3.5" />
123 + </FileSurfaceAction>
124 + </div>
125 + ) : null}
126 + <iframe
127 + title={props.name}
128 + srcDoc={srcDoc}
129 + // Same-origin access lets the parent measure saved output; scripts remain blocked.
130 + sandbox={props.output ? "allow-same-origin" : ""}
131 + onLoad={(event) => {
132 + if (!props.output) return;
133 + stopObserving.current?.();
134 + const body = event.currentTarget.contentDocument?.body;
135 + if (!body) return;
136 + const measure = () => setOutputHeight(Math.ceil(body.getBoundingClientRect().height));
137 + stopObserving.current = observeResize(body, measure);
138 + measure();
139 + }}
140 + style={props.output ? { height: outputHeight } : undefined}
141 + className={props.output ? "block w-full border-0" : "min-h-0 flex-1 border-0"}
142 + />
143 + </>
144 + );
145 +}
apps/web/src/components/files/FilePreviewPanel.test.ts
+255 -1
@@ -1,7 +1,9 @@
1 +import JSZip from "jszip";
2 +import { openRtf, openNotebook, openDocument, openEpub } from "./extendedDocumentPreview";
3 import type { ScopedThreadRef } from "@t3tools/contracts";
4 import { ProjectReadFileError } from "@t3tools/contracts";
5 import * as Schema from "effect/Schema";
4 -import { describe, expect, it } from "vite-plus/test";
6 +import { describe, expect, it, vi } from "vite-plus/test";
7
8 import { remapFileCommentAnnotations } from "./fileCommentAnnotations";
9 import {
@@ -144,3 +146,255 @@ describe("workspaceAssetResource", () => {
146 ).toEqual({ _tag: "draft-workspace-file", cwd: "/repo", path: "/tmp/screenshots/shot.png" });
147 });
148 });
149 +
150 +describe("document preview contents", () => {
151 + const bytes = (text: string) => new TextEncoder().encode(text).buffer;
152 +
153 + it.each(["?", String.raw`\'3f`, String.raw`\\`])(
154 + "consumes skipped rich text Unicode fallback %s",
155 + (fallback) => {
156 + const result = openRtf(bytes(String.raw`{\rtf1{\*\unknown\u945` + fallback + "}Hello}"));
157 + if (result.type !== "document") throw new Error("Expected document");
158 + expect(result.pages[0]!.html).toBe("<p>Hello</p>");
159 + },
160 + );
161 +
162 + it("bounds EPUB markup made entirely of empty allowed elements", async () => {
163 + const archive = new JSZip()
164 + .file(
165 + "META-INF/container.xml",
166 + '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',
167 + )
168 + .file(
169 + "book.opf",
170 + '<package><manifest><item id="a" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine>' +
171 + '<itemref idref="a"/>'.repeat(30) +
172 + "</spine></package>",
173 + )
174 + .file("chapter.xhtml", "<html><body>" + "<figcaption/>".repeat(30_000) + "</body></html>");
175 + await expect(openEpub(archive)).rejects.toThrow("too large");
176 + });
177 +
178 + it("decodes rich text formatting and Unicode without showing hidden destinations", () => {
179 + const result = openRtf(
180 + bytes(
181 + 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}}}`,
182 + ),
183 + );
184 + expect(result.type).toBe("document");
185 + if (result.type !== "document") throw new Error("Expected document");
186 + const html = result.pages[0]!.html;
187 + expect(html.replaceAll(/<[^>]*>/g, "")).toBe("Hello boldUnicode: αvisible");
188 + expect(html).toContain("<strong>");
189 + expect(html).not.toContain("https:");
190 + });
191 +
192 + it("preserves rich text page breaks and formatting without splitting hidden destinations", () => {
193 + const result = openRtf(
194 + bytes(String.raw`{\rtf1\b First\page Second\b0{\*\unknown \page hidden}\page Third\page}`),
195 + );
196 + if (result.type !== "document") throw new Error("Expected document");
197 + expect(result.navigation).toBe("page");
198 + expect(result.pages.map((page) => page.html)).toEqual([
199 + "<p><strong>First</strong></p>",
200 + "<p><strong>Second</strong></p>",
201 + "<p>Third</p>",
202 + ]);
203 + expect(() => openRtf(bytes(String.raw`{\rtf1 ` + String.raw`\page`.repeat(501) + "}"))).toThrow(
204 + "500 pages",
205 + );
206 + });
207 +
208 + it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => {
209 + const input = new TextEncoder().encode(
210 + String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`,
211 + );
212 + input[input.indexOf(65)] = 0xc0;
213 + const result = openRtf(input.buffer);
214 + if (result.type !== "document") throw new Error("Expected document");
215 + expect(result.pages[0]!.html).toBe("<p>А А<br>あ</p>");
216 + expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow("code page");
217 + });
218 +
219 + it("resolves scoped ODF namespaces and explicit spreadsheet whitespace", async () => {
220 + const archive = new JSZip().file(
221 + "content.xml",
222 + '<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 &amp; 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>',
223 + );
224 + const result = await openDocument(archive, "ods");
225 + if (result.type !== "ods") throw new Error("Expected workbook");
226 + expect(result.sheets[0]!.name).toBe("Accounts & names");
227 + expect(result.sheets[0]!.rows[0]).toEqual(["Account Name A\tB\nC"]);
228 + });
229 +
230 + it("stops repeated slide images before encoding beyond the output budget", async () => {
231 + const pixels = new Uint8Array(4 * 1024 * 1024);
232 + pixels.set(
233 + Buffer.from(
234 + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
235 + "base64",
236 + ),
237 + );
238 + const archive = new JSZip()
239 + .file(
240 + "content.xml",
241 + '<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>' +
242 + '<d:page><d:image l:href="picture.png"/></d:page>'.repeat(500) +
243 + "</o:body></o:document-content>",
244 + )
245 + .file("picture.png", pixels);
246 + const image = archive.file("picture.png")!;
247 + const read = vi.spyOn(image, "async");
248 + await expect(openDocument(archive, "odp")).rejects.toThrow("too large");
249 + expect(read.mock.calls.filter(([type]) => type === "base64")).toHaveLength(2);
250 + expect(read).toHaveBeenCalledTimes(5);
251 + });
252 +
253 + it("reads saved notebook cells and preferred outputs without executing code", () => {
254 + const result = openNotebook(
255 + bytes(
256 + JSON.stringify({
257 + nbformat: 4,
258 + metadata: { language_info: { name: "python" } },
259 + cells: [
260 + { cell_type: "markdown", source: ["# Results"] },
261 + {
262 + cell_type: "code",
263 + source: ["print(42)"],
264 + outputs: [
265 + { output_type: "stream", text: ["\n "] },
266 + { output_type: "display_data", data: {} },
267 + { data: { "text/html": [""] } },
268 + { data: { "text/html": [], "text/plain": "array fallback" } },
269 + { data: { "text/html": "", "text/plain": "string fallback" } },
270 + { data: { "text/html": " ", "text/plain": "space fallback" } },
271 + { output_type: "stream", text: ["42\n"] },
272 + { data: { "text/html": ["<b>Results</b>"], "text/plain": ["Results"] } },
273 + ],
274 + },
275 + ],
276 + }),
277 + ),
278 + );
279 + expect(result).toEqual({
280 + type: "notebook",
281 + language: "python",
282 + cells: [
283 + { kind: "markdown", source: "# Results", outputs: [] },
284 + {
285 + kind: "code",
286 + source: "print(42)",
287 + outputs: [
288 + { kind: "text", text: "array fallback" },
289 + { kind: "text", text: "string fallback" },
290 + { kind: "text", text: "space fallback" },
291 + { kind: "text", text: "42\n" },
292 + { kind: "html", text: "<b>Results</b>" },
293 + ],
294 + },
295 + ],
296 + });
297 + expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow("version 4");
298 + expect(() =>
299 + openNotebook(
300 + bytes(JSON.stringify({ nbformat: 4, cells: Array.from({ length: 501 }, () => ({})) })),
301 + ),
302 + ).toThrow("500 cells");
303 + });
304 +
305 + it("bounds repeated OpenDocument spreadsheet cells and keeps sheet names and values", async () => {
306 + const archive = new JSZip().file(
307 + "content.xml",
308 + '<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 &amp; design</text:p></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>',
309 + );
310 + const result = await openDocument(archive, "ods");
311 + expect(result.type).toBe("ods");
312 + if (result.type !== "ods") throw new Error("Expected workbook");
313 + expect(result.sheets[0]!.name).toBe("Budget");
314 + expect(result.sheets[0]!.truncated).toBe(true);
315 + expect(result.sheets[0]!.rows).toHaveLength(500);
316 + expect(result.sheets[0]!.rows[0]).toHaveLength(50);
317 + expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design");
318 + });
319 +
320 + it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {
321 + const archive = new JSZip().file(
322 + "content.xml",
323 + `<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>`,
324 + );
325 + const result = await openDocument(archive, "ods");
326 + if (result.type !== "ods") throw new Error("Expected workbook");
327 + expect(result.sheets[0]).toMatchObject({ rowCount: count, columns: 1, truncated: false });
328 + expect(result.sheets[0]!.rows).toEqual(Array.from({ length: count }, () => ["North"]));
329 + });
330 +
331 + it.each([2, 999999])(
332 + "preserves internal ODS gaps of %s rows and reports real overflow",
333 + async (gap) => {
334 + const archive = new JSZip().file(
335 + "content.xml",
336 + `<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>`,
337 + );
338 + const result = await openDocument(archive, "ods");
339 + if (result.type !== "ods") throw new Error("Expected workbook");
340 + expect(result.sheets[0]).toMatchObject({
341 + rowCount: Math.min(gap + 2, 500),
342 + columns: gap === 2 ? 3 : 1,
343 + truncated: gap !== 2,
344 + });
345 + expect(result.sheets[0]!.rows[1]).toEqual([]);
346 + if (gap === 2) expect(result.sheets[0]!.rows[3]).toEqual(["", "", "Last"]);
347 + },
348 + );
349 +
350 + it.each(["odt", "odp"] as const)("reads %s text and rejects XML entities", async (kind) => {
351 + const archive = new JSZip().file(
352 + "content.xml",
353 + `<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>`,
354 + );
355 + const result = await openDocument(archive, kind);
356 + expect(result.type).toBe("document");
357 + if (result.type !== "document") throw new Error("Expected document");
358 + expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan");
359 + archive.file(
360 + "content.xml",
361 + '<!DOCTYPE x [<!ENTITY external SYSTEM "file:///etc/passwd">]><x>&external;</x>',
362 + );
363 + await expect(openDocument(archive, kind)).rejects.toThrow("unsupported XML");
364 + });
365 +
366 + it("reads EPUB chapters in spine order and removes active and remote content", async () => {
367 + const archive = new JSZip()
368 + .file(
369 + "META-INF/container.xml",
370 + '<container><rootfiles><rootfile full-path="Book/book.opf"/></rootfiles></container>',
371 + )
372 + .file(
373 + "Book/book.opf",
374 + '<package><manifest><item id="a" href="one.xhtml" media-type="application/xhtml+xml"/><item id="b" href="two&amp;&#x26;&#38;.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
375 + )
376 + .file(
377 + "Book/one.xhtml",
378 + '<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>',
379 + )
380 + .file(
381 + "Book/two&&&.xhtml",
382 + '<!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&nbsp;B &copy; &mdash; &NotEqualTilde; &amp;lt;</p><img src="cover.png" alt="&copy; &NotEqualTilde;"/></body></html>',
383 + )
384 + .file(
385 + "Book/cover.png",
386 + Buffer.from(
387 + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
388 + "base64",
389 + ),
390 + );
391 + const result = await openEpub(archive);
392 + expect(result.type).toBe("document");
393 + if (result.type !== "document") throw new Error("Expected document");
394 + expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]);
395 + expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &amp;lt;");
396 + expect(result.pages[0]!.html).toContain('alt="© ≂̸"');
397 + expect(result.pages[1]!.html).toContain('src="data:image/png;base64,');
398 + expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/);
399 + });
400 +});
apps/web/src/components/files/NotebookPreview.tsx new
+182
@@ -0,0 +1,182 @@
1 +/* oxlint-disable react/no-array-index-key -- Notebook cells and outputs retain their saved source order. */
2 +import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
3 +import { useEffect, useRef, useState } from "react";
4 +import type { Root, RootContent } from "mdast";
5 +import ChatMarkdown from "~/components/ChatMarkdown";
6 +import { Button } from "~/components/ui/button";
7 +import ReadOnlySourcePreview from "./ReadOnlySourcePreview";
8 +import DocumentPages from "./DocumentPages";
9 +import { FileSurfaceNotice } from "./fileSurfaceChrome";
10 +import type { OfficeWorkerResult } from "./officePreviewProtocol";
11 +
12 +// Saved notebooks must not load URLs or turn authored links into app actions.
13 +function inertNotebookMarkdown() {
14 + function clean(nodes: RootContent[]): RootContent[] {
15 + return nodes.flatMap((node): RootContent[] => {
16 + if (node.type === "html" || node.type === "definition") return [];
17 + if (node.type === "image" || node.type === "imageReference")
18 + return [{ type: "text", value: node.alt ?? "" }];
19 + if (node.type === "link" || node.type === "linkReference") return clean(node.children);
20 + if (node.type === "inlineCode") return [{ type: "text", value: node.value }];
21 + if (node.type === "code" && node.lang === "mermaid") return [{ ...node, lang: "text" }];
22 + if ("children" in node) node.children = clean(node.children) as typeof node.children;
23 + return [node];
24 + });
25 + }
26 + return (tree: Root) => {
27 + tree.children = clean(tree.children) as Root["children"];
28 + };
29 +}
30 +const NOTEBOOK_PLUGINS = [inertNotebookMarkdown];
31 +
32 +function NotebookSource(props: { readonly name: string; readonly text: string }) {
33 + const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16));
34 + const measure = (node: HTMLElement) => {
35 + setHeight(Math.min(360, Math.ceil(node.getBoundingClientRect().height)));
36 + };
37 + return (
38 + <div className="flex min-h-0 flex-col" style={{ height }}>
39 + <ReadOnlySourcePreview {...props} onPostRender={measure} />
40 + </div>
41 + );
42 +}
43 +
44 +export default function NotebookPreview(props: {
45 + readonly notebook: Extract<OfficeWorkerResult, { type: "notebook" }>;
46 + readonly sizeBytes?: number | undefined;
47 +}) {
48 + const [visible, setVisible] = useState(20);
49 + const scroll = useRef<HTMLDivElement>(null);
50 + const [outputView, setOutputView] = useState(() => ({
51 + mounted: new Set<string>(),
52 + heights: new Map<string, number>(),
53 + }));
54 + const outputCount = props.notebook.cells
55 + .slice(0, visible)
56 + .reduce(
57 + (count, cell) => count + cell.outputs.filter((output) => output.kind === "html").length,
58 + 0,
59 + );
60 + // oxlint-disable-next-line t3code/react-effect-budget -- Observe output visibility and measure departing outputs to bound iframe lifetimes while preserving scroll height.
61 + useEffect(() => {
62 + const root = scroll.current;
63 + if (!root || !outputCount) return;
64 + const candidates = new Map<Element, string>();
65 + let active: Element[] = [];
66 + const observer = new IntersectionObserver(
67 + (entries) => {
68 + for (const entry of entries) {
69 + if (entry.isIntersecting)
70 + candidates.set(entry.target, (entry.target as HTMLElement).dataset.notebookOutput!);
71 + else candidates.delete(entry.target);
72 + }
73 + // Bound browsing contexts even when a cell contains hundreds of tiny HTML outputs.
74 + const next = [...candidates.keys()].slice(0, 16);
75 + const measured = active
76 + .filter((node) => !next.includes(node))
77 + .map(
78 + (node) =>
79 + [
80 + (node as HTMLElement).dataset.notebookOutput!,
81 + node.getBoundingClientRect().height,
82 + ] as const,
83 + );
84 + active = next;
85 + setOutputView((old) => ({
86 + mounted: new Set(next.map((node) => candidates.get(node)!)),
87 + heights: new Map([...old.heights, ...measured]),
88 + }));
89 + },
90 + { root, rootMargin: "160px" },
91 + );
92 + for (const node of root.querySelectorAll("[data-notebook-output]")) observer.observe(node);
93 + return () => observer.disconnect();
94 + }, [outputCount]);
95 + return (
96 + <>
97 + <div
98 + className="border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"
99 + role="status"
100 + >
101 + {props.notebook.cells.length.toLocaleString()} cells · {props.notebook.language}
102 + {props.sizeBytes !== undefined
103 + ? ` · ${props.sizeBytes === 0 ? "0 bytes" : formatAttachmentSize(props.sizeBytes)}`
104 + : ""}
105 + </div>
106 + <FileSurfaceNotice>Saved outputs only. Code is never executed.</FileSurfaceNotice>
107 + <div ref={scroll} className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto">
108 + <div className="mx-auto max-w-4xl space-y-5 px-5 py-6">
109 + {props.notebook.cells.slice(0, visible).map((cell, index) => (
110 + <section
111 + key={index}
112 + aria-label={`Cell ${index + 1}`}
113 + className="min-w-0 overflow-hidden rounded-md border border-border/60"
114 + >
115 + <div className="border-b border-border/60 bg-muted/30 px-3 py-1.5 text-xs text-muted-foreground">
116 + {cell.kind === "code" ? props.notebook.language : cell.kind} · {index + 1}
117 + </div>
118 + {cell.kind === "markdown" ? (
119 + <ChatMarkdown
120 + text={cell.source}
121 + cwd={undefined}
122 + parseRawHtml={false}
123 + extraRemarkPlugins={NOTEBOOK_PLUGINS}
124 + className="px-4 py-3"
125 + />
126 + ) : cell.source.trim() ? (
127 + <NotebookSource
128 + name={`cell.${cell.kind === "code" ? (({ python: "py", javascript: "js", typescript: "ts", julia: "jl" } as Record<string, string>)[props.notebook.language] ?? props.notebook.language) : "txt"}`}
129 + text={cell.source}
130 + />
131 + ) : null}
132 + {cell.outputs.map((output, outputIndex) => (
133 + <div
134 + key={outputIndex}
135 + data-notebook-output={
136 + output.kind === "html" ? `${index}-${outputIndex}` : undefined
137 + }
138 + className="border-t border-border/60"
139 + style={{
140 + minHeight:
141 + output.kind !== "html" || outputView.mounted.has(`${index}-${outputIndex}`)
142 + ? undefined
143 + : (outputView.heights.get(`${index}-${outputIndex}`) ?? 80),
144 + }}
145 + >
146 + {output.kind === "html" ? (
147 + !outputView.mounted.has(`${index}-${outputIndex}`) ? null : (
148 + <DocumentPages
149 + html={output.text}
150 + name={`Cell ${index + 1} HTML output`}
151 + output
152 + />
153 + )
154 + ) : output.kind === "image" ? (
155 + <img
156 + src={output.text}
157 + alt={`Cell ${index + 1} output`}
158 + loading="lazy"
159 + className="max-h-96 max-w-full p-4 object-contain"
160 + />
161 + ) : (
162 + <pre className="overflow-x-auto p-4 text-xs whitespace-pre-wrap break-words">
163 + {output.text}
164 + </pre>
165 + )}
166 + </div>
167 + ))}
168 + </section>
169 + ))}
170 + {props.notebook.cells.length === 0 ? (
171 + <p className="text-sm text-muted-foreground">This notebook is empty.</p>
172 + ) : null}
173 + {visible < props.notebook.cells.length ? (
174 + <Button variant="outline" size="sm" onClick={() => setVisible((count) => count + 20)}>
175 + Show more cells ({props.notebook.cells.length - visible} remaining)
176 + </Button>
177 + ) : null}
178 + </div>
179 + </div>
180 + </>
181 + );
182 +}
apps/web/src/components/files/OfficeViewer.tsx
+229 -50
@@ -1,15 +1,29 @@
1 -import { useStableCallback } from "~/hooks/useStableCallback";
1 +/* oxlint-disable react/no-array-index-key -- Spreadsheet rows and columns retain their source positions. */
2 +import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
3 import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
3 -import { lazy, Suspense, useEffect, useState } from "react";
4 +import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
5 +import { lazy, Suspense, useEffect, useRef, useState } from "react";
6 +
7 +import VirtualTablePreview from "./VirtualTablePreview";
8 +
9 import {
5 - FileSurfaceLoading,
6 - FileSurfaceNotice,
7 - FILE_SURFACE_SUBHEADER_CLASS,
8 -} from "./fileSurfaceChrome";
10 + Select,
11 + SelectItem,
12 + SelectPopup,
13 + SelectTrigger,
14 + SelectValue,
15 +} from "~/components/ui/select";
16 +
17 +import { FileSurfaceAction, FileSurfaceLoading, FileSurfaceNotice } from "./fileSurfaceChrome";
18 import { OFFICE_PREVIEW_MAX_BYTES, type OfficeWorkerResult } from "./officePreviewProtocol";
10 -const WordDocument = lazy(() => import("./office/WordDocument"));
11 -const Spreadsheet = lazy(() => import("./office/Spreadsheet"));
12 -const Presentation = lazy(() => import("./office/Presentation"));
19 +
20 +const DocumentPages = lazy(() => import("./DocumentPages"));
21 +const NotebookPreview = lazy(() => import("./NotebookPreview"));
22 +
23 +type Workbook = Extract<OfficeWorkerResult, { type: "ods" }>;
24 +
25 +const OpenXmlOfficeViewer = lazy(() => import("./OpenXmlOfficeViewer"));
26 +
27 async function readOfficeFile(src: string, signal: AbortSignal) {
28 const response = await fetch(src, { signal });
29 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: {
52 readonly name: string;
53 readonly kind: OfficePreviewKind;
54 readonly sizeBytes?: number;
55 +}) {
56 + if (props.kind === "docx" || props.kind === "xlsx" || props.kind === "pptx")
57 + return (
58 + <Suspense fallback={<FileSurfaceLoading />}>
59 + <OpenXmlOfficeViewer {...props} kind={props.kind} />
60 + </Suspense>
61 + );
62 + return <ExtendedOfficeViewer {...props} />;
63 +}
64 +
65 +function ExtendedOfficeViewer(props: {
66 + readonly src: string;
67 + readonly name: string;
68 + readonly kind: OfficePreviewKind;
69 + readonly sizeBytes?: number;
70 }) {
71 const [error, setError] = useState<string | null>(null);
43 - const [prepared, setPrepared] = useState<Exclude<OfficeWorkerResult, { type: "error" }>>();
44 - const [details, setDetails] = useState("");
45 - const fail = useStableCallback((cause: unknown) =>
46 - setError(cause instanceof Error ? cause.message : "Could not render this Office document."),
47 - );
72 + const [sheetPages, setSheetPages] = useState(new Map<string, string[][]>());
73 + const pendingPages = useRef(new Set<string>());
74 + const [previewDocument, setDocument] = useState<Extract<
75 + OfficeWorkerResult,
76 + { type: "document" }
77 + > | null>(null);
78 + const [notebook, setNotebook] = useState<Extract<
79 + OfficeWorkerResult,
80 + { type: "notebook" }
81 + > | null>(null);
82 + const [workbook, setWorkbook] = useState<Workbook | null>(null);
83 + const [count, setCount] = useState(0);
84 + const [fileSize, setFileSize] = useState(props.sizeBytes);
85 + const [page, setPage] = useState(0);
86 + const workerRef = useRef<Worker | null>(null);
87 + const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
88 // oxlint-disable-next-line t3code/react-effect-budget -- Own the Office fetch, preparation worker, and timeout for this source and release them on cleanup.
89 useEffect(() => {
90 + const controller = new AbortController();
91 if ((props.sizeBytes ?? 0) > OFFICE_PREVIEW_MAX_BYTES) {
51 - // Metadata bounds are checked before fetching or starting an engine.
52 - // oxlint-disable-next-line react/set-state-in-effect
92 + // oxlint-disable-next-line react/set-state-in-effect -- The file metadata can reject the preview before loading bytes or engines.
93 setError("Preview limited to files under 50 MB.");
94 return;
95 }
56 - const controller = new AbortController();
96 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
97 type: "module",
98 });
60 - const failure = (cause: unknown) => {
61 - if (!controller.signal.aborted) fail(cause);
99 + workerRef.current = worker;
100 + const fail = (message: string) => {
101 + if (!controller.signal.aborted) setError(message);
102 controller.abort();
103 worker.terminate();
104 + if (timerRef.current) clearTimeout(timerRef.current);
105 };
65 - const timer = setTimeout(
66 - () => failure(new Error("This document took too long to preview. Open it in another app.")),
67 - 30000,
106 + timerRef.current = setTimeout(
107 + () => fail("This document took too long to preview. Open it in another app."),
108 + 30_000,
109 );
69 - worker.addEventListener("error", () => failure(new Error("Could not load the Office viewer.")));
70 - worker.addEventListener("messageerror", () =>
71 - failure(new Error("Could not read the Office viewer response.")),
110 + worker.addEventListener("error", () =>
111 + fail("Could not load the Office viewer. Close the file and try again."),
112 );
113 worker.addEventListener("message", (event: MessageEvent<OfficeWorkerResult>) => {
114 if (controller.signal.aborted) return;
75 - clearTimeout(timer);
76 - if (event.data.type === "error") failure(new Error(event.data.message));
77 - else {
78 - setPrepared(event.data);
79 - worker.terminate();
115 + const result = event.data;
116 + if (result.type === "error") fail(result.message);
117 + else if (result.type === "document") {
118 + if (timerRef.current) clearTimeout(timerRef.current);
119 + setDocument(result);
120 + setCount(result.pages.length > 1 ? result.pages.length : 0);
121 + } else if (result.type === "notebook") {
122 + if (timerRef.current) clearTimeout(timerRef.current);
123 + setNotebook(result);
124 + } else if (result.type === "ods") {
125 + if (timerRef.current) clearTimeout(timerRef.current);
126 + setWorkbook(result);
127 + setCount(result.sheets.length);
128 + } else if (result.type === "sheet-page") {
129 + const key = `${result.sheet}:${result.index}`;
130 + pendingPages.current.delete(key);
131 + setSheetPages((old) => {
132 + const next = new Map(old);
133 + next.set(key, result.rows);
134 + if (next.size > 12) next.delete(next.keys().next().value!);
135 + return next;
136 + });
137 }
138 });
139 void readOfficeFile(props.src, controller.signal)
140 .then((bytes) => {
84 - if (!controller.signal.aborted)
141 + if (!controller.signal.aborted) {
142 + setFileSize(bytes.byteLength);
143 worker.postMessage({ type: "open", kind: props.kind, bytes }, [bytes]);
144 + }
145 })
87 - .catch(failure);
146 + .catch((cause: unknown) =>
147 + fail(cause instanceof Error ? cause.message : "Could not read this file."),
148 + );
149 return () => {
150 controller.abort();
151 worker.terminate();
91 - clearTimeout(timer);
152 + workerRef.current = null;
153 + if (timerRef.current) clearTimeout(timerRef.current);
154 };
93 - }, [props.src, props.kind, props.sizeBytes, fail]);
155 + }, [props.src, props.kind, props.sizeBytes]);
156 + const selectPage = setPage;
157 if (error)
158 return (
159 <div
@@ -103,27 +166,143 @@ export default function OfficeViewer(props: {
166 </p>
167 </div>
168 );
106 - if (!prepared) return <FileSurfaceLoading />;
107 - const Viewer =
108 - props.kind === "docx" ? WordDocument : props.kind === "xlsx" ? Spreadsheet : Presentation;
169 + if (notebook)
170 + return (
171 + <Suspense fallback={<FileSurfaceLoading />}>
172 + <NotebookPreview notebook={notebook} sizeBytes={fileSize} />
173 + </Suspense>
174 + );
175 + const sheet = workbook?.sheets[page];
176 + const documentPage = previewDocument?.pages[page];
177 + const navigation = workbook ? "sheet" : (previewDocument?.navigation ?? "slide");
178 + const documentCount = previewDocument?.pages.length ?? 0;
179 + const documentDetails =
180 + navigation === "chapter"
181 + ? `Chapter ${page + 1} of ${documentCount}`
182 + : `${documentCount} ${navigation}${documentCount === 1 ? "" : "s"}`;
183 return (
184 <div className="flex min-h-0 flex-1 flex-col">
111 - {details ? (
112 - <div className={FILE_SURFACE_SUBHEADER_CLASS}>
113 - <span className="text-xs text-muted-foreground" aria-live="polite">
114 - {details}
115 - {props.kind !== "xlsx" ? " · Fit to width" : ""}
116 - </span>
185 + {count > 0 ? (
186 + <div className="flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3 text-xs">
187 + <FileSurfaceAction
188 + label={`Previous ${navigation}`}
189 + disabled={page === 0}
190 + onPress={() => selectPage(page - 1)}
191 + >
192 + <ChevronLeftIcon className="size-3.5" />
193 + </FileSurfaceAction>
194 + {workbook ? (
195 + <div className="min-w-0 flex-1">
196 + <Select
197 + value={page}
198 + onValueChange={(value) => {
199 + if (value !== null) selectPage(value);
200 + }}
201 + >
202 + <SelectTrigger aria-label="Sheet" size="xs">
203 + <SelectValue>{sheet?.name}</SelectValue>
204 + </SelectTrigger>
205 + <SelectPopup>
206 + {workbook.sheets.map((item, index) => (
207 + <SelectItem key={index} value={index}>
208 + {item.name}
209 + </SelectItem>
210 + ))}
211 + </SelectPopup>
212 + </Select>
213 + </div>
214 + ) : previewDocument?.navigation === "chapter" ? (
215 + <div className="min-w-0 flex-1">
216 + <Select
217 + value={page}
218 + onValueChange={(value) => {
219 + if (value !== null) selectPage(value);
220 + }}
221 + >
222 + <SelectTrigger aria-label="Chapter" size="xs">
223 + <SelectValue>{documentPage?.title}</SelectValue>
224 + </SelectTrigger>
225 + <SelectPopup>
226 + {previewDocument.pages.map((item, index) => (
227 + <SelectItem key={index} value={index}>
228 + {item.title}
229 + </SelectItem>
230 + ))}
231 + </SelectPopup>
232 + </Select>
233 + </div>
234 + ) : (
235 + <span className="flex-1 text-center tabular-nums" aria-live="polite">
236 + {navigation === "slide" ? "Slide" : "Page"} {page + 1} of {count}
237 + </span>
238 + )}
239 + <FileSurfaceAction
240 + label={`Next ${navigation}`}
241 + disabled={page + 1 === count}
242 + onPress={() => selectPage(page + 1)}
243 + >
244 + <ChevronRightIcon className="size-3.5" />
245 + </FileSurfaceAction>
246 </div>
247 ) : null}
119 - {prepared.truncated ? (
120 - <FileSurfaceNotice>
121 - Preview limited. Save it or open it in another app to read the full document.
122 - </FileSurfaceNotice>
248 + {props.kind === "ods" && sheet ? (
249 + <div
250 + 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"
251 + role="status"
252 + >
253 + Sheet {page + 1} of {count} · {sheet.rowCount.toLocaleString()} rows ·{" "}
254 + {sheet.columns.toLocaleString()} columns
255 + {fileSize !== undefined
256 + ? ` · ${fileSize === 0 ? "0 bytes" : formatAttachmentSize(fileSize)}`
257 + : ""}
258 + </div>
259 ) : null}
124 - <Suspense fallback={<FileSurfaceLoading />}>
125 - <Viewer bytes={prepared.bytes} onDetails={setDetails} onError={fail} />
126 - </Suspense>
260 + {documentPage ? (
261 + <>
262 + {props.kind !== "epub" ? (
263 + <FileSurfaceNotice>
264 + Text and images. Layout and embedded objects may differ from the original.
265 + </FileSurfaceNotice>
266 + ) : null}
267 + <Suspense fallback={<FileSurfaceLoading />}>
268 + <DocumentPages
269 + html={documentPage.html}
270 + name={`${props.name}: ${documentPage.title}`}
271 + details={`${documentDetails}${fileSize !== undefined ? ` · ${fileSize === 0 ? "0 bytes" : formatAttachmentSize(fileSize)}` : ""}`}
272 + />
273 + </Suspense>
274 + </>
275 + ) : sheet ? (
276 + <>
277 + <FileSurfaceNotice>
278 + Cell values only. Charts, images, and formatting are not shown.
279 + {sheet.truncated
280 + ? props.kind === "ods"
281 + ? " Limited to 500 rows and 50 columns."
282 + : " Preview limited to 250,000 rows, 1,024 columns, and bounded cell text."
283 + : ""}
284 + </FileSurfaceNotice>
285 + {sheet.rowCount === 0 ? (
286 + <p className="p-6 text-xs text-muted-foreground">This sheet is empty.</p>
287 + ) : (
288 + <VirtualTablePreview
289 + key={page}
290 + name={`${props.name}: ${sheet.name}`}
291 + count={sheet.rowCount}
292 + columns={sheet.columns}
293 + getRows={(index) => (index === 0 ? sheet.rows : sheetPages.get(`${page}:${index}`))}
294 + loadPage={(index) => {
295 + const key = `${page}:${index}`;
296 + if (pendingPages.current.has(key)) return;
297 + pendingPages.current.add(key);
298 + workerRef.current?.postMessage({ type: "sheet-page", sheet: page, index });
299 + }}
300 + />
301 + )}
302 + </>
303 + ) : (
304 + <FileSurfaceLoading />
305 + )}
306 </div>
307 );
308 }
apps/web/src/components/files/OpenXmlOfficeViewer.tsx new
+129
@@ -0,0 +1,129 @@
1 +import { useStableCallback } from "~/hooks/useStableCallback";
2 +import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
3 +import { lazy, Suspense, useEffect, useState } from "react";
4 +import {
5 + FileSurfaceLoading,
6 + FileSurfaceNotice,
7 + FILE_SURFACE_SUBHEADER_CLASS,
8 +} from "./fileSurfaceChrome";
9 +import { OFFICE_PREVIEW_MAX_BYTES, type OfficeWorkerResult } from "./officePreviewProtocol";
10 +const WordDocument = lazy(() => import("./office/WordDocument"));
11 +const Spreadsheet = lazy(() => import("./office/Spreadsheet"));
12 +const Presentation = lazy(() => import("./office/Presentation"));
13 +async function readOfficeFile(src: string, signal: AbortSignal) {
14 + const response = await fetch(src, { signal });
15 + if (!response.ok) throw new Error("The file could not be loaded. Close it and try again.");
16 + if (Number(response.headers.get("content-length")) > OFFICE_PREVIEW_MAX_BYTES)
17 + throw new Error("Preview limited to files under 50 MB.");
18 + const reader = response.body?.getReader();
19 + if (!reader) throw new Error("The file is unavailable.");
20 + const chunks: Uint8Array<ArrayBuffer>[] = [];
21 + let size = 0;
22 + try {
23 + while (true) {
24 + const { value, done } = await reader.read();
25 + if (done) break;
26 + size += value.length;
27 + if (size > OFFICE_PREVIEW_MAX_BYTES) throw new Error("Preview limited to files under 50 MB.");
28 + chunks.push(value);
29 + }
30 + } finally {
31 + await reader.cancel();
32 + }
33 + return new Blob(chunks).arrayBuffer();
34 +}
35 +
36 +export default function OfficeViewer(props: {
37 + readonly src: string;
38 + readonly name: string;
39 + readonly kind: Extract<OfficePreviewKind, "docx" | "xlsx" | "pptx">;
40 + readonly sizeBytes?: number;
41 +}) {
42 + const [error, setError] = useState<string | null>(null);
43 + const [prepared, setPrepared] = useState<Extract<OfficeWorkerResult, { bytes: ArrayBuffer }>>();
44 + const [details, setDetails] = useState("");
45 + const fail = useStableCallback((cause: unknown) =>
46 + setError(cause instanceof Error ? cause.message : "Could not render this Office document."),
47 + );
48 + // oxlint-disable-next-line t3code/react-effect-budget -- Own the Open XML fetch, preparation worker, and timeout for this source and release them on cleanup.
49 + useEffect(() => {
50 + if ((props.sizeBytes ?? 0) > OFFICE_PREVIEW_MAX_BYTES) {
51 + // Metadata bounds are checked before fetching or starting an engine.
52 + // oxlint-disable-next-line react/set-state-in-effect
53 + setError("Preview limited to files under 50 MB.");
54 + return;
55 + }
56 + const controller = new AbortController();
57 + const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
58 + type: "module",
59 + });
60 + const failure = (cause: unknown) => {
61 + if (!controller.signal.aborted) fail(cause);
62 + controller.abort();
63 + worker.terminate();
64 + };
65 + const timer = setTimeout(
66 + () => failure(new Error("This document took too long to preview. Open it in another app.")),
67 + 30000,
68 + );
69 + worker.addEventListener("error", () => failure(new Error("Could not load the Office viewer.")));
70 + worker.addEventListener("messageerror", () =>
71 + failure(new Error("Could not read the Office viewer response.")),
72 + );
73 + worker.addEventListener("message", (event: MessageEvent<OfficeWorkerResult>) => {
74 + if (controller.signal.aborted) return;
75 + clearTimeout(timer);
76 + if (event.data.type === "error") failure(new Error(event.data.message));
77 + else if ("bytes" in event.data) {
78 + setPrepared(event.data);
79 + worker.terminate();
80 + }
81 + });
82 + void readOfficeFile(props.src, controller.signal)
83 + .then((bytes) => {
84 + if (!controller.signal.aborted)
85 + worker.postMessage({ type: "open", kind: props.kind, bytes }, [bytes]);
86 + })
87 + .catch(failure);
88 + return () => {
89 + controller.abort();
90 + worker.terminate();
91 + clearTimeout(timer);
92 + };
93 + }, [props.src, props.kind, props.sizeBytes, fail]);
94 + if (error)
95 + return (
96 + <div
97 + role="alert"
98 + className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
99 + >
100 + <p className="text-sm font-medium">No preview for this file</p>
101 + <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
102 + {error} Save it or open it in another app.
103 + </p>
104 + </div>
105 + );
106 + if (!prepared) return <FileSurfaceLoading />;
107 + const Viewer =
108 + props.kind === "docx" ? WordDocument : props.kind === "xlsx" ? Spreadsheet : Presentation;
109 + return (
110 + <div className="flex min-h-0 flex-1 flex-col">
111 + {details ? (
112 + <div className={FILE_SURFACE_SUBHEADER_CLASS}>
113 + <span className="text-xs text-muted-foreground" aria-live="polite">
114 + {details}
115 + {props.kind !== "xlsx" ? " · Fit to width" : ""}
116 + </span>
117 + </div>
118 + ) : null}
119 + {prepared.truncated ? (
120 + <FileSurfaceNotice>
121 + Preview limited. Save it or open it in another app to read the full document.
122 + </FileSurfaceNotice>
123 + ) : null}
124 + <Suspense fallback={<FileSurfaceLoading />}>
125 + <Viewer bytes={prepared.bytes} onDetails={setDetails} onError={fail} />
126 + </Suspense>
127 + </div>
128 + );
129 +}
apps/web/src/components/files/PdfViewer.tsx new
+431
@@ -0,0 +1,431 @@
1 +import {
2 + useEffect,
3 + useEffectEvent,
4 + useLayoutEffect,
5 + useRef,
6 + useState,
7 + type CSSProperties,
8 +} from "react";
9 +import { TextLayer, type PDFDocumentProxy } from "pdfjs-dist";
10 +import { ChevronDownIcon, ChevronUpIcon, MinusIcon, PlusIcon, ScanIcon } from "lucide-react";
11 +import { Input } from "~/components/ui/input";
12 +import { observeResize } from "~/lib/observeResize";
13 +import { FileSurfaceAction, FileSurfaceFailure, FileSurfaceLoading } from "./fileSurfaceChrome";
14 +import { readBoundedDocument } from "./readBoundedDocument";
15 +import { openPdf } from "./pdfDocument";
16 +import "./pdfViewer.css";
17 +
18 +const MAX_PAGES = 2000;
19 +const MAX_FIND_TEXT = 4 * 1024 * 1024;
20 +
21 +function PdfPage(props: {
22 + document: PDFDocumentProxy;
23 + index: number;
24 + width: number;
25 + query: string;
26 + onSize: (index: number, ratio: number) => void;
27 + onError: (error: string) => void;
28 +}) {
29 + const canvas = useRef<HTMLCanvasElement>(null);
30 + const text = useRef<HTMLDivElement>(null);
31 + const { document: pdf, index, width, onSize, onError } = props;
32 + // 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.
33 + useEffect(() => {
34 + let cancelled = false;
35 + let paint: ReturnType<Awaited<ReturnType<PDFDocumentProxy["getPage"]>>["render"]> | undefined;
36 + let layer: TextLayer | undefined;
37 + let loadedPage: Awaited<ReturnType<PDFDocumentProxy["getPage"]>> | undefined;
38 + void (async () => {
39 + const page = await pdf.getPage(index + 1);
40 + loadedPage = page;
41 + if (cancelled || !canvas.current || !text.current) {
42 + page.cleanup();
43 + return;
44 + }
45 + const natural = page.getViewport({ scale: 1 });
46 + onSize(index, natural.height / natural.width);
47 + const viewport = page.getViewport({ scale: width / natural.width });
48 + const ratio = Math.min(
49 + 2,
50 + window.devicePixelRatio || 1,
51 + Math.sqrt((8 * 1024 * 1024) / (viewport.width * viewport.height)),
52 + );
53 + canvas.current.width = Math.ceil(viewport.width * ratio);
54 + canvas.current.height = Math.ceil(viewport.height * ratio);
55 + paint = page.render({
56 + canvas: canvas.current,
57 + viewport,
58 + transform: [ratio, 0, 0, ratio, 0, 0],
59 + background: "white",
60 + });
61 + text.current.replaceChildren();
62 + text.current.style.setProperty("--total-scale-factor", String(viewport.scale));
63 + layer = new TextLayer({
64 + container: text.current,
65 + viewport,
66 + textContentSource: page.streamTextContent(),
67 + });
68 + await Promise.all([paint.promise, layer.render()]);
69 + })().catch((cause: unknown) => {
70 + if (!cancelled)
71 + onError(cause instanceof Error ? cause.message : "This PDF page could not render.");
72 + });
73 + return () => {
74 + cancelled = true;
75 + paint?.cancel();
76 + layer?.cancel();
77 + // Release operator lists when virtual pages leave the viewport.
78 + void Promise.allSettled([paint?.promise]).then(() => loadedPage?.cleanup());
79 + };
80 + }, [pdf, index, width, onSize, onError]);
81 + // 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.
82 + useEffect(() => {
83 + const node = text.current;
84 + if (!node) return;
85 + const mark = () => {
86 + const runs = Array.from(node.querySelectorAll('span[role="presentation"], br')).map(
87 + (element) => ({
88 + element,
89 + text: element.tagName === "BR" ? "\n" : (element.textContent ?? "").toLowerCase(),
90 + }),
91 + );
92 + const text = runs.map((run) => run.text).join("");
93 + const query = props.query.toLowerCase();
94 + let match = query.trim() ? text.indexOf(query) : -1;
95 + let offset = 0;
96 + for (const run of runs) {
97 + while (match !== -1 && match + query.length <= offset)
98 + match = text.indexOf(query, match + query.length);
99 + run.element.classList.toggle(
100 + "pdf-find-match",
101 + match !== -1 && match < offset + run.text.length,
102 + );
103 + offset += run.text.length;
104 + }
105 + };
106 + mark();
107 + const observer = new MutationObserver(mark);
108 + observer.observe(node, { childList: true, subtree: true });
109 + return () => observer.disconnect();
110 + }, [props.query]);
111 + return (
112 + <>
113 + <canvas ref={canvas} aria-label={`Page ${index + 1}`} className="block h-full w-full" />
114 + <div ref={text} data-pdf-text-layer />
115 + </>
116 + );
117 +}
118 +
119 +export default function PdfViewer(props: { src: string; title: string }) {
120 + const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);
121 + const [error, setError] = useState<string | null>(null);
122 + const [revision, setRevision] = useState(0);
123 + const [ratios, setRatios] = useState<number[]>([]);
124 + const [zoom, setZoom] = useState<number | null>(null);
125 + const [pageWidth, setPageWidth] = useState(612);
126 + const [viewport, setViewport] = useState({ width: 600, height: 800 });
127 + const [scrollTop, setScrollTop] = useState(0);
128 + const [query, setQuery] = useState("");
129 + const [matches, setMatches] = useState<number[]>([]);
130 + const [finding, setFinding] = useState(false);
131 + const [findError, setFindError] = useState<string | null>(null);
132 + const [match, setMatch] = useState(0);
133 + const scroll = useRef<HTMLDivElement>(null);
134 + const find = useRef<HTMLInputElement>(null);
135 + const zoomAnchor = useRef<{ page: number; offset: number; width: number } | null>(null);
136 + // 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.
137 + useEffect(() => {
138 + const controller = new AbortController();
139 + let disposed = false;
140 + let task: ReturnType<typeof openPdf> | undefined;
141 + const timeout = setTimeout(() => {
142 + setError("This PDF took too long to load. Try again.");
143 + controller.abort();
144 + void task?.destroy();
145 + }, 30_000);
146 + void readBoundedDocument(
147 + props.src,
148 + controller.signal,
149 + 50 * 1024 * 1024,
150 + revision > 0 ? "reload" : "default",
151 + )
152 + .then(async (bytes) => {
153 + controller.signal.throwIfAborted();
154 + task = openPdf(bytes);
155 + const document = await task.promise;
156 + if (document.numPages > MAX_PAGES)
157 + throw new Error("Preview limited to 2,000 pages. Save this PDF to read it in full.");
158 + const first = (await document.getPage(1)).getViewport({ scale: 1 });
159 + if (controller.signal.aborted) return;
160 + setPageWidth(first.width);
161 + setRatios(Array.from({ length: document.numPages }, () => first.height / first.width));
162 + setPdf(document);
163 + })
164 + .catch((cause: unknown) => {
165 + if (!disposed && !controller.signal.aborted)
166 + setError(cause instanceof Error ? cause.message : "Unable to open PDF.");
167 + })
168 + .finally(() => clearTimeout(timeout));
169 + return () => {
170 + disposed = true;
171 + controller.abort();
172 + clearTimeout(timeout);
173 + void task?.destroy();
174 + };
175 + }, [props.src, revision]);
176 + // 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.
177 + useLayoutEffect(() => {
178 + const node = scroll.current;
179 + if (!node) return;
180 + const update = () => setViewport({ width: node.clientWidth, height: node.clientHeight });
181 + update();
182 + return observeResize(node, update);
183 + }, []);
184 + const fitWidth = Math.max(1, viewport.width - 32);
185 + const scale = zoom ?? fitWidth / pageWidth;
186 + const width = zoom === null ? fitWidth : pageWidth * zoom;
187 + const offsets = (() => {
188 + const result = [16];
189 + for (const ratio of ratios) result.push(result[result.length - 1]! + width * ratio + 16);
190 + return result;
191 + })();
192 + const current = Math.max(
193 + 0,
194 + ratios.findIndex((_, index) => offsets[index + 1]! > scrollTop + 17),
195 + );
196 + const visible = ratios.flatMap((ratio, index) =>
197 + offsets[index + 1]! >= scrollTop - viewport.height &&
198 + offsets[index]! <= scrollTop + viewport.height * 2
199 + ? [{ index, ratio }]
200 + : [],
201 + );
202 + // Stable callbacks let page canvases survive scroll and find updates.
203 + const [onSize] = useState(
204 + () => (index: number, ratio: number) =>
205 + setRatios((old) =>
206 + old[index] === ratio ? old : old.map((value, i) => (i === index ? ratio : value)),
207 + ),
208 + );
209 + const jumpToPage = useEffectEvent((index: number) => {
210 + scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
211 + });
212 + const showPage = (index: number) => {
213 + scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
214 + };
215 + const changeZoom = (value: number | null) => {
216 + zoomAnchor.current = {
217 + page: current,
218 + offset: (scroll.current?.scrollTop ?? 0) - (offsets[current]! - 16),
219 + width,
220 + };
221 + setZoom(value);
222 + };
223 + // oxlint-disable-next-line t3code/react-effect-budget -- Restore the DOM scroll anchor after the new zoom width has committed to page layout.
224 + useLayoutEffect(() => {
225 + const anchor = zoomAnchor.current;
226 + zoomAnchor.current = null;
227 + if (!anchor || anchor.width === width) return;
228 + scroll.current?.scrollTo({
229 + top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
230 + });
231 + });
232 + // oxlint-disable-next-line t3code/react-effect-budget -- Scroll to the first asynchronous search result after its measured page offsets have committed.
233 + useLayoutEffect(() => {
234 + if (matches.length) jumpToPage(matches[0]!);
235 + }, [matches]);
236 + // oxlint-disable-next-line t3code/react-effect-budget -- Debounce pdf.js text extraction and cancel obsolete searches when the query or document changes.
237 + useEffect(() => {
238 + if (!pdf || !query.trim()) {
239 + // oxlint-disable-next-line react/set-state-in-effect -- A blank query cancels the previous search.
240 + setFinding(false);
241 + return;
242 + }
243 + let cancelled = false;
244 + const timer = setTimeout(() => {
245 + setFinding(true);
246 + setFindError(null);
247 + setMatches([]);
248 + setMatch(0);
249 + void (async () => {
250 + const found: number[] = [];
251 + const sizes: number[] = [];
252 + let size = 0;
253 + for (let index = 0; index < pdf.numPages; index++) {
254 + if (cancelled) return;
255 + const page = await pdf.getPage(index + 1);
256 + const pageSize = page.getViewport({ scale: 1 });
257 + sizes.push(pageSize.height / pageSize.width);
258 + const content = await page.getTextContent();
259 + const text = content.items
260 + .map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : ""))
261 + .join("");
262 + size += text.length;
263 + if (size > MAX_FIND_TEXT)
264 + throw new Error(
265 + "This PDF has too much text to search. Save it to search in another app.",
266 + );
267 + if (text.toLowerCase().includes(query.toLowerCase())) found.push(index);
268 + }
269 + if (cancelled) return;
270 + setRatios(sizes);
271 + setMatches(found);
272 + })()
273 + .catch((cause: unknown) => {
274 + if (!cancelled)
275 + setFindError(cause instanceof Error ? cause.message : "Could not search this PDF.");
276 + })
277 + .finally(() => {
278 + if (!cancelled) setFinding(false);
279 + });
280 + }, 250);
281 + return () => {
282 + cancelled = true;
283 + clearTimeout(timer);
284 + };
285 + }, [pdf, query]);
286 + return (
287 + <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
288 + <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">
289 + <span className="mr-auto px-1 tabular-nums" aria-live="polite">
290 + {pdf ? `${current + 1} / ${pdf.numPages} pages` : "PDF"}
291 + </span>
292 + <FileSurfaceAction
293 + label="Previous page"
294 + disabled={!pdf || current === 0}
295 + onPress={() => showPage(current - 1)}
296 + >
297 + <ChevronUpIcon className="size-3.5" />
298 + </FileSurfaceAction>
299 + <FileSurfaceAction
300 + label="Next page"
301 + disabled={!pdf || current + 1 >= pdf.numPages}
302 + onPress={() => showPage(current + 1)}
303 + >
304 + <ChevronDownIcon className="size-3.5" />
305 + </FileSurfaceAction>
306 + <FileSurfaceAction
307 + label="Zoom out"
308 + disabled={scale <= 0.25}
309 + onPress={() => changeZoom(Math.max(0.25, scale - 0.25))}
310 + >
311 + <MinusIcon className="size-3.5" />
312 + </FileSurfaceAction>
313 + <span className="min-w-14 text-center tabular-nums">
314 + {zoom === null ? "Fit width" : `${Math.round(scale * 100)}%`}
315 + </span>
316 + <FileSurfaceAction
317 + label="Zoom in"
318 + disabled={scale >= 3}
319 + onPress={() => changeZoom(Math.min(3, scale + 0.25))}
320 + >
321 + <PlusIcon className="size-3.5" />
322 + </FileSurfaceAction>
323 + <FileSurfaceAction
324 + label="Fit width"
325 + onPress={() => {
326 + changeZoom(null);
327 + scroll.current?.scrollTo({ left: 0 });
328 + }}
329 + >
330 + <ScanIcon className="size-3.5" />
331 + </FileSurfaceAction>
332 + <div className="w-28">
333 + <Input
334 + ref={find}
335 + size="compact"
336 + type="search"
337 + aria-label="Find in PDF"
338 + placeholder="Find in PDF"
339 + value={query}
340 + onChange={(event) => {
341 + setQuery(event.target.value);
342 + setMatches([]);
343 + setFindError(null);
344 + }}
345 + />
346 + </div>
347 + {query ? (
348 + <>
349 + <span role="status">
350 + {finding
351 + ? "Searching…"
352 + : (findError ?? `${matches.length ? match + 1 : 0}/${matches.length}`)}
353 + </span>
354 + <FileSurfaceAction
355 + label="Next matching page"
356 + disabled={!matches.length}
357 + onPress={() => {
358 + const next = (match + 1) % matches.length;
359 + setMatch(next);
360 + showPage(matches[next]!);
361 + }}
362 + >
363 + <ChevronDownIcon className="size-3.5" />
364 + </FileSurfaceAction>
365 + </>
366 + ) : null}
367 + </div>
368 + <div
369 + ref={scroll}
370 + role="region"
371 + aria-label={props.title}
372 + tabIndex={0}
373 + className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto bg-muted/40"
374 + onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
375 + onKeyDown={(event) => {
376 + if ((event.ctrlKey || event.metaKey) && event.key === "f") {
377 + event.preventDefault();
378 + event.stopPropagation();
379 + find.current?.focus();
380 + }
381 + }}
382 + >
383 + {error ? (
384 + <FileSurfaceFailure
385 + message={error}
386 + onRetry={() => {
387 + setError(null);
388 + setPdf(null);
389 + setRevision((value) => value + 1);
390 + }}
391 + />
392 + ) : !pdf ? (
393 + <FileSurfaceLoading />
394 + ) : (
395 + <div
396 + className="relative"
397 + style={{
398 + height: `max(${offsets.at(-1) ?? 0}px, calc(100% + ${(offsets.at(-2) ?? 16) - 16}px))`,
399 + minWidth: width + 32,
400 + }}
401 + >
402 + {visible.map(({ index, ratio }) => (
403 + <div
404 + key={index}
405 + className="absolute bg-white shadow-sm"
406 + style={
407 + {
408 + top: offsets[index],
409 + left: Math.max(16, (viewport.width - width) / 2),
410 + width,
411 + height: width * ratio,
412 + "--total-scale-factor": 1,
413 + } as CSSProperties
414 + }
415 + >
416 + <PdfPage
417 + document={pdf}
418 + index={index}
419 + width={width}
420 + query={query}
421 + onSize={onSize}
422 + onError={setError}
423 + />
424 + </div>
425 + ))}
426 + </div>
427 + )}
428 + </div>
429 + </div>
430 + );
431 +}
apps/web/src/components/files/extendedDocumentPreview.ts new
+672
@@ -0,0 +1,672 @@
1 +import {
2 + IMAGE_DIMENSIONS_HEADER_BYTES,
3 + readImageDimensions,
4 +} from "@t3tools/shared/imageDimensions";
5 +import { XMLParser, XMLValidator } from "fast-xml-parser";
6 +import { decodeHTMLAttribute, decodeHTMLStrict as decodeEntities } from "entities";
7 +import type JSZip from "jszip";
8 +
9 +import { type OfficeWorkerResult, type NotebookCell } from "./officePreviewProtocol";
10 +
11 +const ODS_PREVIEW_MAX_ROWS = 500;
12 +const ODS_PREVIEW_MAX_COLUMNS = 50;
13 +
14 +type XmlNode = { name: string; attrs: Record<string, string>; children: XmlNode[]; text: string };
15 +type OrderedXml = { [key: string]: OrderedXml[] | Record<string, string> | string };
16 +const escape = (value: string) =>
17 + value
18 + .replaceAll("&", "&amp;")
19 + .replaceAll("<", "&lt;")
20 + .replaceAll(">", "&gt;")
21 + .replaceAll('"', "&quot;");
22 +
23 +const namespacePrefixes: Record<string, string> = {
24 + "urn:oasis:names:tc:opendocument:xmlns:office:1.0": "office",
25 + "urn:oasis:names:tc:opendocument:xmlns:table:1.0": "table",
26 + "urn:oasis:names:tc:opendocument:xmlns:text:1.0": "text",
27 + "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0": "draw",
28 + "http://www.w3.org/1999/xlink": "xlink",
29 + "http://www.w3.org/1999/xhtml": "",
30 + "http://www.idpf.org/2007/opf": "",
31 + "urn:oasis:names:tc:opendocument:xmlns:container": "",
32 +};
33 +function parseXml(source: string): XmlNode {
34 + // EPUB XHTML commonly declares an external DTD. Discard it without resolving it.
35 + source = source.replaceAll(/<!DOCTYPE\s+[^<>[\]]*>/gi, "");
36 + if (
37 + source.length > 8 * 1024 * 1024 ||
38 + /<!\s*(DOCTYPE|ENTITY)/i.test(source) ||
39 + XMLValidator.validate(source) !== true
40 + )
41 + throw new Error("This document contains invalid or unsupported XML.");
42 + const parser = new XMLParser({
43 + preserveOrder: true,
44 + ignoreAttributes: false,
45 + attributeNamePrefix: "",
46 + processEntities: false,
47 + trimValues: false,
48 + parseTagValue: false,
49 + });
50 + const ordered = parser.parse(source) as OrderedXml[];
51 + let count = 0;
52 + function convert(
53 + items: OrderedXml[],
54 + depth: number,
55 + inherited: Record<string, string>,
56 + ): XmlNode[] {
57 + if (depth > 100) throw new Error("This document is nested too deeply to preview.");
58 + return items.map((item) => {
59 + if (++count > 100_000) throw new Error("This document has too much content to preview.");
60 + const name = Object.keys(item).find((key) => key !== ":@") ?? "#text";
61 + const value = item[name];
62 + const attrs = Object.fromEntries(
63 + Object.entries((item[":@"] ?? {}) as Record<string, string>).map(([key, value]) => [
64 + key,
65 + decodeEntities(value),
66 + ]),
67 + );
68 + const namespaces = Object.create(inherited) as Record<string, string>;
69 + for (const [key, value] of Object.entries(attrs)) {
70 + if (key === "xmlns") namespaces[""] = value;
71 + else if (key.startsWith("xmlns:")) namespaces[key.slice(6)] = value;
72 + }
73 + const expanded = (name: string, attribute = false) => {
74 + if (name.startsWith("#")) return name;
75 + const colon = name.indexOf(":");
76 + if (colon < 0 && attribute) return name;
77 + const uri = namespaces[colon < 0 ? "" : name.slice(0, colon)];
78 + if (!uri) return name;
79 + const prefix = Object.hasOwn(namespacePrefixes, uri) ? namespacePrefixes[uri] : undefined;
80 + const local = name.slice(colon + 1);
81 + return prefix === undefined
82 + ? "{" + uri + "}" + local
83 + : prefix
84 + ? prefix + ":" + local
85 + : local;
86 + };
87 + return {
88 + name: expanded(name),
89 + attrs: Object.fromEntries(
90 + Object.entries(attrs).map(([key, value]) => [expanded(key, true), value]),
91 + ),
92 + children: Array.isArray(value) ? convert(value, depth + 1, namespaces) : [],
93 + text: typeof value === "string" ? value : "",
94 + };
95 + });
96 + }
97 + return {
98 + name: "root",
99 + attrs: {},
100 + children: convert(ordered, 0, Object.create(null) as Record<string, string>),
101 + text: "",
102 + };
103 +}
104 +function find(node: XmlNode, name: string, skip?: string): XmlNode[] {
105 + return node.children.flatMap((child) =>
106 + child.name === skip
107 + ? []
108 + : child.name === name || (!name.includes(":") && child.name.endsWith(`:${name}`))
109 + ? [child]
110 + : find(child, name, skip),
111 + );
112 +}
113 +function text(node: XmlNode): string {
114 + if (node.name === "office:annotation") return "";
115 + if (node.name === "text:s") return " ".repeat(repeat(node.attrs["text:c"], 100));
116 + if (node.name === "text:tab") return "\t";
117 + if (node.name === "text:line-break") return "\n";
118 + return node.name === "#text" ? decodeEntities(node.text) : node.children.map(text).join("");
119 +}
120 +function archivePath(base: string, href: string): string | null {
121 + if (/^(?:[a-z][a-z\d+.-]*:|\/|\\)/i.test(href)) return null;
122 + const parts = base.split("/").slice(0, -1);
123 + let decoded: string;
124 + try {
125 + decoded = decodeURIComponent(href.split(/[?#]/, 1)[0] ?? "");
126 + } catch {
127 + return null;
128 + }
129 + for (const part of decoded.split("/")) {
130 + if (part === "..") {
131 + if (!parts.length) return null;
132 + parts.pop();
133 + } else if (part && part !== ".") parts.push(part);
134 + }
135 + return parts.join("/");
136 +}
137 +function imageFits(bytes: Uint8Array) {
138 + const size = readImageDimensions(bytes.subarray(0, IMAGE_DIMENSIONS_HEADER_BYTES));
139 + return size !== null && size.width <= 16_777_216 / size.height;
140 +}
141 +function base64ImageFits(base64: string) {
142 + return (
143 + /^[a-z\d+/]*={0,2}$/i.test(base64) &&
144 + base64.length % 4 !== 1 &&
145 + (!base64.endsWith("=") || base64.length % 4 === 0) &&
146 + imageFits(
147 + Uint8Array.from(
148 + atob(base64.slice(0, 4 * Math.ceil(IMAGE_DIMENSIONS_HEADER_BYTES / 3))),
149 + (char) => char.charCodeAt(0),
150 + ),
151 + )
152 + );
153 +}
154 +function htmlImagesFit(html: string) {
155 + // HTML attribute entities can obscure a data URL until the client parses it.
156 + for (const match of decodeHTMLAttribute(html).matchAll(
157 + /data:image\/(?:png|jpeg|gif|webp);base64,([a-z\d+/]*={0,2})/gi,
158 + ))
159 + if (!base64ImageFits(match[1]!)) return false;
160 + return true;
161 +}
162 +async function imageData(archive: JSZip, path: string | null): Promise<string> {
163 + if (!path) return "";
164 + const mime = (
165 + { png: "png", jpg: "jpeg", jpeg: "jpeg", gif: "gif", webp: "webp" } as Record<string, string>
166 + )[path.split(".").at(-1)?.toLowerCase() ?? ""];
167 + const entry = archive.file(path);
168 + if (!mime || !entry) return "";
169 + const bytes = await entry.async("uint8array");
170 + if (bytes.length > 4 * 1024 * 1024 || !imageFits(bytes)) return "";
171 + reserveMarkup(4 * Math.ceil(bytes.length / 3) + 100);
172 + return `data:image/${mime};base64,${await entry.async("base64")}`;
173 +}
174 +let markupBytes = 0;
175 +function reserveMarkup(size: number) {
176 + markupBytes += size;
177 + if (markupBytes > 16 * 1024 * 1024)
178 + throw new Error("The rendered document is too large to preview.");
179 +}
180 +function boundedMarkup(value: string): string {
181 + reserveMarkup(value.length);
182 + return value;
183 +}
184 +const HTML_TAGS = new Set([
185 + "p",
186 + "h1",
187 + "h2",
188 + "h3",
189 + "h4",
190 + "h5",
191 + "h6",
192 + "div",
193 + "span",
194 + "strong",
195 + "b",
196 + "em",
197 + "i",
198 + "u",
199 + "s",
200 + "ul",
201 + "ol",
202 + "li",
203 + "blockquote",
204 + "pre",
205 + "code",
206 + "table",
207 + "thead",
208 + "tbody",
209 + "tr",
210 + "th",
211 + "td",
212 + "caption",
213 + "figure",
214 + "figcaption",
215 + "br",
216 + "hr",
217 + "sub",
218 + "sup",
219 + "dl",
220 + "dt",
221 + "dd",
222 +]);
223 +async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise<string> {
224 + if (node.name === "#text") return boundedMarkup(escape(text(node)));
225 + const tag =
226 + node.name
227 + .replace(/^\{[^}]*\}/, "")
228 + .split(":")
229 + .at(-1) ?? "";
230 + if (["head", "script", "style", "iframe", "object", "embed", "svg", "math", "form"].includes(tag))
231 + return "";
232 + if (tag === "br" || tag === "hr") return boundedMarkup(`<${tag}>`);
233 + if (tag === "img") {
234 + const src = await imageData(archive, archivePath(base, node.attrs.src ?? ""));
235 + return src ? `<img src="${src}" alt="${boundedMarkup(escape(node.attrs.alt ?? ""))}">` : "";
236 + }
237 + let children = "";
238 + for (const child of node.children) children += await epubHtml(child, archive, base);
239 + if (!HTML_TAGS.has(tag)) return children;
240 + const spans =
241 + tag === "td" || tag === "th"
242 + ? ["colspan", "rowspan"]
243 + .map((name) =>
244 + /^\d{1,4}$/.test(node.attrs[name] ?? "") ? ` ${name}="${node.attrs[name]}"` : "",
245 + )
246 + .join("")
247 + : "";
248 + reserveMarkup(tag.length * 2 + spans.length + 5);
249 + return `<${tag}${spans}>${children}</${tag}>`;
250 +}
251 +async function odfHtml(node: XmlNode, archive: JSZip): Promise<string> {
252 + if (node.name === "#text") return boundedMarkup(escape(text(node)));
253 + if (node.name === "text:s" || node.name === "text:tab")
254 + return boundedMarkup(
255 + `<span data-odf-whitespace>${node.name === "text:tab" ? "&#9;" : " ".repeat(repeat(node.attrs["text:c"], 100))}</span>`,
256 + );
257 + if (node.name === "text:line-break") return boundedMarkup("<br>");
258 + if (node.name === "draw:image") {
259 + const src = await imageData(
260 + archive,
261 + archivePath("content.xml", node.attrs["xlink:href"] ?? ""),
262 + );
263 + return src ? `<img src="${src}" alt="">` : "";
264 + }
265 + if (
266 + [
267 + "office:annotation",
268 + "text:tracked-changes",
269 + "office:scripts",
270 + "draw:object",
271 + "draw:object-ole",
272 + ].includes(node.name)
273 + )
274 + return "";
275 + let children = "";
276 + for (const child of node.children) children += await odfHtml(child, archive);
277 + const tags: Record<string, string> = {
278 + "text:p": "p",
279 + "text:h": "h2",
280 + "text:span": "span",
281 + "text:list": "ul",
282 + "text:list-item": "li",
283 + "table:table": "table",
284 + "table:table-row": "tr",
285 + "table:table-cell": "td",
286 + };
287 + const tag = tags[node.name];
288 + if (!tag) return children;
289 + reserveMarkup(tag.length * 2 + 5);
290 + return `<${tag}>${children}</${tag}>`;
291 +}
292 +function repeat(value: string | undefined, max: number) {
293 + const count = Number(value ?? 1);
294 + if (!Number.isSafeInteger(count) || count < 1)
295 + throw new Error("This spreadsheet contains invalid repeated cells.");
296 + return Math.min(count, max);
297 +}
298 +export async function openDocument(
299 + archive: JSZip,
300 + kind: "odt" | "ods" | "odp",
301 +): Promise<OfficeWorkerResult> {
302 + markupBytes = 0;
303 + const source = await archive.file("content.xml")?.async("string");
304 + if (!source) throw new Error("This OpenDocument file has no readable content.");
305 + const root = parseXml(source);
306 + if (kind === "ods") {
307 + const tables = find(root, "table:table");
308 + if (!tables.length || tables.length > 100)
309 + throw new Error("This workbook has no sheets or too many sheets to preview.");
310 + let cellBytes = 0;
311 + return {
312 + type: "ods",
313 + sheets: tables.map((table, index) => {
314 + const rows: string[][] = [];
315 + let truncated = false;
316 + let pendingEmptyRows = 0;
317 + for (const row of find(table, "table:table-row")) {
318 + const cells: string[] = [];
319 + for (const cell of row.children.filter((child) =>
320 + ["table:table-cell", "table:covered-table-cell"].includes(child.name),
321 + )) {
322 + const value =
323 + find(cell, "text:p", "office:annotation").map(text).join("\n") ||
324 + cell.attrs["office:value"] ||
325 + cell.attrs["office:date-value"] ||
326 + cell.attrs["office:boolean-value"] ||
327 + cell.attrs["office:string-value"] ||
328 + "";
329 + const count = repeat(
330 + cell.attrs["table:number-columns-repeated"],
331 + ODS_PREVIEW_MAX_COLUMNS + 1,
332 + );
333 + if (value && cells.length + count > ODS_PREVIEW_MAX_COLUMNS) truncated = true;
334 + for (let i = 0; i < count && cells.length < ODS_PREVIEW_MAX_COLUMNS; i++) {
335 + if (value.length > 10_000)
336 + throw new Error("A spreadsheet cell is too large to preview.");
337 + cells.push(value);
338 + }
339 + }
340 + while (cells.at(-1) === "") cells.pop();
341 + const count = repeat(row.attrs["table:number-rows-repeated"], ODS_PREVIEW_MAX_ROWS + 1);
342 + if (!cells.length) {
343 + pendingEmptyRows = Math.min(ODS_PREVIEW_MAX_ROWS + 1, pendingEmptyRows + count);
344 + continue;
345 + }
346 + while (pendingEmptyRows > 0 && rows.length < ODS_PREVIEW_MAX_ROWS) {
347 + rows.push([]);
348 + pendingEmptyRows--;
349 + }
350 + pendingEmptyRows = 0;
351 + if (rows.length + count > ODS_PREVIEW_MAX_ROWS) truncated = true;
352 + if (rows.length >= ODS_PREVIEW_MAX_ROWS) break;
353 + for (let i = 0; i < count && rows.length < ODS_PREVIEW_MAX_ROWS; i++) {
354 + cellBytes += cells.reduce((size, cell) => size + cell.length, 0);
355 + if (cellBytes > 8 * 1024 * 1024)
356 + throw new Error("This spreadsheet has too much text to preview.");
357 + rows.push(cells);
358 + }
359 + }
360 + return {
361 + name: table.attrs["table:name"] || `Sheet ${index + 1}`,
362 + rows,
363 + rowCount: rows.length,
364 + columns: rows.reduce((columns, row) => Math.max(columns, row.length), 1),
365 + truncated,
366 + };
367 + }),
368 + };
369 + }
370 + const pages = kind === "odp" ? find(root, "draw:page") : find(root, "office:text");
371 + if (!pages.length || pages.length > 500)
372 + throw new Error("This document has no pages or too many pages to preview.");
373 + const rendered = [];
374 + for (const [index, page] of pages.entries()) {
375 + rendered.push({
376 + title: page.attrs["draw:name"] || `Page ${index + 1}`,
377 + html: await odfHtml(page, archive),
378 + });
379 + }
380 + return { type: "document", navigation: kind === "odp" ? "slide" : "page", pages: rendered };
381 +}
382 +export async function openEpub(archive: JSZip): Promise<OfficeWorkerResult> {
383 + markupBytes = 0;
384 + const container = parseXml((await archive.file("META-INF/container.xml")?.async("string")) ?? "");
385 + const rootfile = find(container, "rootfile")[0]?.attrs["full-path"];
386 + if (!rootfile || !archive.file(rootfile)) throw new Error("This EPUB has no readable package.");
387 + const packageRoot = parseXml(await archive.file(rootfile)!.async("string"));
388 + const manifest = new Map(find(packageRoot, "item").map((item) => [item.attrs.id, item]));
389 + const spine = find(packageRoot, "itemref");
390 + if (!spine.length || spine.length > 500)
391 + throw new Error("This EPUB has no chapters or too many chapters to preview.");
392 + const pages = [];
393 + for (const itemref of spine) {
394 + const item = manifest.get(itemref.attrs.idref);
395 + if (!item || item.attrs["media-type"] !== "application/xhtml+xml") continue;
396 + const path = archivePath(rootfile, item.attrs.href ?? "");
397 + const entry = path ? archive.file(path) : null;
398 + if (!entry || !path) continue;
399 + const chapter = parseXml(await entry.async("string"));
400 + pages.push({
401 + title:
402 + text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter).slice(0, 120) ||
403 + `Chapter ${pages.length + 1}`,
404 + html: await epubHtml(chapter, archive, path),
405 + });
406 + }
407 + if (!pages.length) throw new Error("This EPUB has no readable XHTML chapters.");
408 + return { type: "document", navigation: "chapter", pages };
409 +}
410 +function record(value: unknown): Record<string, unknown> {
411 + return value !== null && typeof value === "object" && !Array.isArray(value)
412 + ? (value as Record<string, unknown>)
413 + : {};
414 +}
415 +function notebookText(value: unknown, limit = 256_000): string {
416 + const result =
417 + typeof value === "string"
418 + ? value
419 + : Array.isArray(value)
420 + ? value.filter((part) => typeof part === "string").join("")
421 + : "";
422 + if (result.length > limit) throw new Error("A notebook cell is too large to preview.");
423 + return result;
424 +}
425 +export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult {
426 + if (bytes.byteLength > 8 * 1024 * 1024)
427 + throw new Error("Notebook preview limited to files under 8 MB.");
428 + const notebook = record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
429 + if (notebook.nbformat !== 4 || !Array.isArray(notebook.cells) || notebook.cells.length > 500)
430 + throw new Error("Preview supports version 4 notebooks with up to 500 cells.");
431 + const language = String(record(record(notebook.metadata).language_info).name ?? "text")
432 + .replaceAll(/[^a-z\d+#-]/gi, "")
433 + .slice(0, 40);
434 + const cells: NotebookCell[] = notebook.cells.map((value) => {
435 + const cell = record(value);
436 + const outputs = Array.isArray(cell.outputs) ? cell.outputs : [];
437 + if (outputs.length > 100) throw new Error("A notebook cell has too many outputs to preview.");
438 + return {
439 + kind: cell.cell_type === "markdown" ? "markdown" : cell.cell_type === "code" ? "code" : "raw",
440 + source: notebookText(cell.source),
441 + outputs: outputs
442 + .map((value) => {
443 + const output = record(value);
444 + const data = record(output.data);
445 + for (const mime of ["image/png", "image/jpeg", "image/gif", "image/webp"]) {
446 + if (data[mime]) {
447 + const base64 = notebookText(data[mime], 4 * 1024 * 1024).replaceAll(/\s/g, "");
448 + if (base64ImageFits(base64))
449 + return { kind: "image" as const, text: `data:${mime};base64,${base64}` };
450 + }
451 + }
452 + const html = notebookText(data["text/html"]);
453 + if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html };
454 + return {
455 + kind: "text" as const,
456 + text: notebookText(output.text ?? data["text/plain"] ?? output.traceback),
457 + };
458 + })
459 + .filter((output) => output.text.trim().length > 0),
460 + };
461 + });
462 + return { type: "notebook", language, cells };
463 +}
464 +
465 +export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult {
466 + if (bytes.byteLength > 8 * 1024 * 1024)
467 + throw new Error("Rich text preview limited to files under 8 MB.");
468 + // Keep byte offsets intact for binary destinations and multibyte code pages.
469 + const input = new Uint8Array(bytes);
470 + let source = "";
471 + for (let offset = 0; offset < input.length; offset += 8192)
472 + source += String.fromCharCode(...input.subarray(offset, offset + 8192));
473 + if (!source.startsWith("{\\rtf")) throw new Error("This is not a valid rich text document.");
474 + let state = {
475 + skip: false,
476 + bold: false,
477 + italic: false,
478 + underline: false,
479 + uc: 1,
480 + font: 0,
481 + fontTable: false,
482 + decoder: new TextDecoder("windows-1252"),
483 + };
484 + const fonts = new Map<number, TextDecoder>();
485 + let defaultFont = 0;
486 + const stack: (typeof state)[] = [];
487 + let html = "";
488 + const pages: { title: string; html: string }[] = [];
489 + let completedLength = 0;
490 + const finishPage = () => {
491 + if (pages.length >= 500) throw new Error("Rich text preview limited to 500 pages.");
492 + pages.push({ title: `Page ${pages.length + 1}`, html: `<p>${html}</p>` });
493 + completedLength += html.length;
494 + html = "";
495 + };
496 + let run = "";
497 + let fallback = 0;
498 + const encoded = new Uint8Array(bytes.byteLength);
499 + let encodedLength = 0;
500 + const flush = () => {
501 + if (encodedLength) {
502 + run += escape(
503 + (fonts.get(state.font) ?? state.decoder).decode(encoded.subarray(0, encodedLength)),
504 + );
505 + encodedLength = 0;
506 + }
507 + if (completedLength + html.length + run.length > 8 * 1024 * 1024)
508 + throw new Error("This rich text document has too much content to preview.");
509 + if (!run) return;
510 + let span = run;
511 + if (state.bold) span = `<strong>${span}</strong>`;
512 + if (state.italic) span = `<em>${span}</em>`;
513 + if (state.underline) span = `<u>${span}</u>`;
514 + html += span;
515 + run = "";
516 + };
517 + const emit = (value: string) => {
518 + if (fallback > 0) {
519 + fallback--;
520 + return;
521 + }
522 + if (state.skip) return;
523 + run += escape(value);
524 + if (completedLength + html.length + run.length > 8 * 1024 * 1024)
525 + throw new Error("This rich text document has too much content to preview.");
526 + };
527 + const emitByte = (value: number) => {
528 + if (fallback > 0) fallback--;
529 + else if (!state.skip) encoded[encodedLength++] = value;
530 + };
531 + for (let i = 0; i < source.length;) {
532 + const char = source[i++];
533 + if (char === "{") {
534 + flush();
535 + fallback = 0;
536 + if (stack.length > 100) throw new Error("This rich text document is nested too deeply.");
537 + stack.push({ ...state });
538 + } else if (char === "}") {
539 + flush();
540 + fallback = 0;
541 + const parent = stack.pop();
542 + if (!parent) throw new Error("This rich text document is damaged.");
543 + state = parent;
544 + } else if (char === "\\") {
545 + const next = source[i];
546 + if (next === "'") {
547 + const hex = source.slice(i + 1, i + 3);
548 + if (!/^[\da-f]{2}$/i.test(hex)) throw new Error("Invalid rich text byte escape.");
549 + i += 3;
550 + emitByte(Number.parseInt(hex, 16));
551 + continue;
552 + }
553 + flush();
554 + if (next === "\\" || next === "{" || next === "}") {
555 + i++;
556 + emit(next);
557 + continue;
558 + }
559 + if (next === "*") {
560 + state.skip = true;
561 + i++;
562 + continue;
563 + }
564 + const match = /^([a-z]+)(-?\d+)? ?/i.exec(source.slice(i));
565 + if (!match) {
566 + if (next === "~") emit("\u00a0");
567 + i++;
568 + continue;
569 + }
570 + i += match[0].length;
571 + const word = match[1];
572 + const arg = match[2] === undefined ? 1 : Number(match[2]);
573 + if (word === "fonttbl") {
574 + state.fontTable = true;
575 + state.skip = true;
576 + } else if (word === "deff") state.font = defaultFont = arg;
577 + else if (word === "f") state.font = arg;
578 + else if (word === "fcharset" && state.fontTable) {
579 + const label = (
580 + {
581 + 0: state.decoder.encoding,
582 + 1: state.decoder.encoding,
583 + 77: "macintosh",
584 + 128: "shift_jis",
585 + 129: "euc-kr",
586 + 134: "gbk",
587 + 136: "big5",
588 + 161: "windows-1253",
589 + 162: "windows-1254",
590 + 163: "windows-1258",
591 + 177: "windows-1255",
592 + 178: "windows-1256",
593 + 186: "windows-1257",
594 + 204: "windows-1251",
595 + 222: "windows-874",
596 + 238: "windows-1250",
597 + 255: "ibm866",
598 + } as Record<number, string>
599 + )[arg];
600 + if (label) fonts.set(state.font, new TextDecoder(label));
601 + } else if (
602 + [
603 + "colortbl",
604 + "stylesheet",
605 + "info",
606 + "pict",
607 + "object",
608 + "fldinst",
609 + "header",
610 + "headerl",
611 + "headerr",
612 + "headerf",
613 + "footer",
614 + "footerl",
615 + "footerr",
616 + "footerf",
617 + "filetbl",
618 + "datastore",
619 + "themedata",
620 + ].includes(word!)
621 + )
622 + state.skip = true;
623 + else if (word === "bin") {
624 + if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i)
625 + throw new Error("Invalid rich text binary data.");
626 + i += arg;
627 + } else if (word === "ansicpg") {
628 + const label =
629 + (
630 + {
631 + 65001: "utf-8",
632 + 932: "shift_jis",
633 + 936: "gbk",
634 + 949: "euc-kr",
635 + 950: "big5",
636 + 874: "windows-874",
637 + } as Record<number, string>
638 + )[arg] ?? `windows-${arg}`;
639 + try {
640 + state.decoder = new TextDecoder(label);
641 + } catch {
642 + throw new Error("This rich text code page is not supported.");
643 + }
644 + } else if (word === "b") state.bold = arg !== 0;
645 + else if (word === "i") state.italic = arg !== 0;
646 + else if (word === "ul") state.underline = arg !== 0;
647 + else if (word === "ulnone") state.underline = false;
648 + else if (word === "plain")
649 + state = { ...state, bold: false, italic: false, underline: false, font: defaultFont };
650 + else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg));
651 + else if (word === "u") {
652 + fallback = 0;
653 + emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg));
654 + fallback = state.uc;
655 + } else if (!state.skip && word === "page") finishPage();
656 + else if (!state.skip && (word === "par" || word === "line" || word === "row")) html += "<br>";
657 + else if (word === "tab" || word === "cell") emit("\t");
658 + else if (word === "endash") emit("–");
659 + // oxlint-disable-next-line t3code/no-em-dash-copy -- Preserve the RTF document's punctuation.
660 + else if (word === "emdash") emit("—");
661 + else if (word === "bullet") emit("•");
662 + else if (word === "lquote") emit("‘");
663 + else if (word === "rquote") emit("’");
664 + else if (word === "ldblquote") emit("“");
665 + else if (word === "rdblquote") emit("”");
666 + } else if (char !== "\r" && char !== "\n" && char) emitByte(char.charCodeAt(0));
667 + }
668 + if (stack.length) throw new Error("This rich text document is damaged.");
669 + flush();
670 + if (html || !pages.length) finishPage();
671 + return { type: "document", navigation: "page", pages };
672 +}
apps/web/src/components/files/officeArchive.ts
+6 -2
@@ -225,6 +225,8 @@ function boundedWorksheet(
225 let explicitRow = false;
226 let rowTag = "";
227 let column = 0;
228 + let maxRow = 0;
229 + let maxColumn = 0;
230 let cells = new Map<number, string>();
231 let cell: {
232 start: number;
@@ -299,7 +301,9 @@ function boundedWorksheet(
301 truncated = true;
302 return;
303 }
302 - if (++budget.cells > 2_000_000 || row * column > 8_000_000)
304 + maxRow = Math.max(maxRow, row);
305 + maxColumn = Math.max(maxColumn, column);
306 + if (++budget.cells > 2_000_000 || maxRow * maxColumn > 8_000_000)
307 throw new Error(
308 "This workbook exceeds the preview limit: 2 million cells or 8 million grid positions.",
309 );
@@ -934,7 +938,7 @@ async function wordExpansion(
938
939 // Stream each entry before handing it to an engine. A tiny compressed archive
940 // must not turn into an unbounded allocation on the UI thread.
937 -async function boundedArchive(input: Extract<OfficeWorkerRequest, { type: "open" }>) {
941 +export async function boundedArchive(input: Extract<OfficeWorkerRequest, { type: "open" }>) {
942 const { bytes } = input;
943 const spreadsheet = input.kind === "xlsx";
944 if (bytes.byteLength > OFFICE_PREVIEW_MAX_BYTES)
apps/web/src/components/files/officePreview.worker.ts
+49 -17
@@ -1,20 +1,52 @@
1 -import { prepareOffice } from "./officeArchive";
1 +import { boundedArchive, prepareOffice } from "./officeArchive";
2 +import { PREVIEW_PAGE_ROWS } from "./largeTextProtocol";
3 import type { OfficeWorkerRequest, OfficeWorkerResult } from "./officePreviewProtocol";
3 -self.addEventListener("message", (event: MessageEvent<OfficeWorkerRequest>) => {
4 - if (event.data.type !== "open") return;
5 - const input = event.data;
6 - void prepareOffice(input.bytes, input.kind)
7 - .then((result) => {
8 - const reply: OfficeWorkerResult = { type: input.kind, ...result };
9 - self.postMessage(reply, { transfer: [result.bytes] });
10 - })
11 - .catch((cause: unknown) => {
12 - self.postMessage(
13 - {
14 - type: "error",
15 - message: cause instanceof Error ? cause.message : "Could not parse this file.",
16 - } satisfies OfficeWorkerResult,
17 - { transfer: [] },
18 - );
4 +
5 +let workbook: string[][][] = [];
6 +function reply(result: OfficeWorkerResult) {
7 + self.postMessage(result, { transfer: "bytes" in result ? [result.bytes] : [] });
8 +}
9 +async function handle(input: OfficeWorkerRequest) {
10 + if (input.type === "sheet-page") {
11 + const rows = workbook[input.sheet];
12 + if (!rows) throw new Error("This sheet is unavailable.");
13 + reply({
14 + type: "sheet-page",
15 + sheet: input.sheet,
16 + index: input.index,
17 + rows: rows.slice(input.index * PREVIEW_PAGE_ROWS, (input.index + 1) * PREVIEW_PAGE_ROWS),
18 + });
19 + return;
20 + }
21 + if (input.kind === "docx" || input.kind === "xlsx" || input.kind === "pptx") {
22 + reply({ type: input.kind, ...(await prepareOffice(input.bytes, input.kind)) });
23 + return;
24 + }
25 + const { openDocument, openEpub, openNotebook, openRtf } =
26 + await import("./extendedDocumentPreview");
27 + if (input.kind === "ipynb" || input.kind === "rtf") {
28 + reply(input.kind === "ipynb" ? openNotebook(input.bytes) : openRtf(input.bytes));
29 + return;
30 + }
31 + const { archive } = await boundedArchive(input);
32 + const result =
33 + input.kind === "epub" ? await openEpub(archive) : await openDocument(archive, input.kind);
34 + if (result.type === "ods") {
35 + workbook = result.sheets.map((sheet) => sheet.rows);
36 + reply({
37 + ...result,
38 + sheets: result.sheets.map((sheet) => ({
39 + ...sheet,
40 + rows: sheet.rows.slice(0, PREVIEW_PAGE_ROWS),
41 + })),
42 });
43 + } else reply(result);
44 +}
45 +self.addEventListener("message", (event: MessageEvent<OfficeWorkerRequest>) => {
46 + void handle(event.data).catch((cause: unknown) =>
47 + reply({
48 + type: "error",
49 + message: cause instanceof Error ? cause.message : "Could not parse this file.",
50 + }),
51 + );
52 });
apps/web/src/components/files/officePreviewProtocol.ts
+34 -5
@@ -1,16 +1,45 @@
1 import type { OfficePreviewKind } from "@t3tools/shared/filePreview";
2 +
3 export const OFFICE_PREVIEW_MAX_BYTES = 50 * 1024 * 1024;
4 export const OFFICE_PREVIEW_MAX_ROWS = 250_000;
5 export const OFFICE_PREVIEW_MAX_COLUMNS = 1024;
5 -export type OfficeWorkerRequest = {
6 - readonly type: "open";
7 - readonly kind: OfficePreviewKind;
8 - readonly bytes: ArrayBuffer;
6 +
7 +export type OfficeWorkerRequest =
8 + | { readonly type: "open"; readonly kind: OfficePreviewKind; readonly bytes: ArrayBuffer }
9 + | { readonly type: "sheet-page"; readonly sheet: number; readonly index: number };
10 +
11 +export type NotebookCell = {
12 + readonly kind: "markdown" | "code" | "raw";
13 + readonly source: string;
14 + readonly outputs: { readonly kind: "text" | "image" | "html"; readonly text: string }[];
15 };
16 +
17 export type OfficeWorkerResult =
18 + | {
19 + readonly type: "document";
20 + readonly navigation: "page" | "slide" | "chapter";
21 + readonly pages: { title: string; html: string }[];
22 + }
23 + | { readonly type: "notebook"; readonly language: string; readonly cells: NotebookCell[] }
24 | { readonly type: "error"; readonly message: string }
25 | {
13 - readonly type: OfficePreviewKind;
26 + readonly type: "docx" | "xlsx" | "pptx";
27 readonly bytes: ArrayBuffer;
28 readonly truncated: boolean;
29 + }
30 + | {
31 + readonly type: "ods";
32 + readonly sheets: {
33 + name: string;
34 + rows: string[][];
35 + truncated: boolean;
36 + rowCount: number;
37 + columns: number;
38 + }[];
39 + }
40 + | {
41 + readonly type: "sheet-page";
42 + readonly sheet: number;
43 + readonly index: number;
44 + readonly rows: string[][];
45 };
apps/web/src/components/files/pdfDocument.ts new
+45
@@ -0,0 +1,45 @@
1 +import { getDocument, GlobalWorkerOptions } from "pdfjs-dist";
2 +import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
3 +import fallbackUrl from "pdfjs-dist/wasm/openjpeg_nowasm_fallback.js?url";
4 +
5 +GlobalWorkerOptions.workerSrc = workerUrl;
6 +
7 +const standardFonts = import.meta.glob<string>(
8 + "../../../node_modules/pdfjs-dist/standard_fonts/*",
9 + { query: "?url", import: "default", eager: true },
10 +);
11 +const cMaps = import.meta.glob<string>("../../../node_modules/pdfjs-dist/cmaps/*.bcmap", {
12 + query: "?url",
13 + import: "default",
14 + eager: true,
15 +});
16 +const wasm = import.meta.glob<string>("../../../node_modules/pdfjs-dist/wasm/*.{wasm,js}", {
17 + query: "?url",
18 + import: "default",
19 + eager: true,
20 +});
21 +export class BinaryDataFactory {
22 + async fetch({ kind, filename }: { kind: string; filename: string }) {
23 + const assets = kind === "cMapUrl" ? cMaps : kind === "wasmUrl" ? wasm : standardFonts;
24 + const directory = kind === "cMapUrl" ? "cmaps" : kind === "wasmUrl" ? "wasm" : "standard_fonts";
25 + const url = assets[`../../../node_modules/pdfjs-dist/${directory}/${filename}`];
26 + if (!url) throw new Error(`Unsupported PDF ${directory} asset.`);
27 + const response = await fetch(url);
28 + if (!response.ok || response.headers.get("content-type")?.startsWith("text/html"))
29 + throw new Error(`PDF ${directory} asset unavailable.`);
30 + return new Uint8Array(await response.arrayBuffer());
31 + }
32 +}
33 +
34 +export function openPdf(bytes: ArrayBuffer) {
35 + return getDocument({
36 + data: new Uint8Array(bytes),
37 + useSystemFonts: true,
38 + useWorkerFetch: false,
39 + BinaryDataFactory,
40 + // PDF.js imports JavaScript decoders directly, bypassing BinaryDataFactory.
41 + wasmUrl: new URL(".", new URL(fallbackUrl, window.location.href)).href,
42 + canvasMaxAreaInBytes: 32 * 1024 * 1024,
43 + useWasm: true,
44 + });
45 +}
apps/web/src/components/files/pdfViewer.css new
+52
@@ -0,0 +1,52 @@
1 +/* TextLayer geometry follows PDF.js' text layer contract (Apache-2.0). */
2 +[data-pdf-text-layer] {
3 + position: absolute;
4 + inset: 0;
5 + overflow: clip;
6 + line-height: 1;
7 + text-align: initial;
8 + letter-spacing: normal;
9 + word-spacing: normal;
10 + text-size-adjust: none;
11 + forced-color-adjust: none;
12 + transform-origin: 0 0;
13 + --min-font-size: 1;
14 + --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));
15 + --min-font-size-inv: calc(1 / var(--min-font-size));
16 + --scale-round-x: 1px;
17 + --scale-round-y: 1px;
18 +}
19 +[data-pdf-text-layer][data-main-rotation="90"] {
20 + transform: rotate(90deg) translateY(-100%);
21 +}
22 +[data-pdf-text-layer][data-main-rotation="180"] {
23 + transform: rotate(180deg) translate(-100%, -100%);
24 +}
25 +[data-pdf-text-layer][data-main-rotation="270"] {
26 + transform: rotate(270deg) translateX(-100%);
27 +}
28 +[data-pdf-text-layer] :is(span, br) {
29 + color: transparent;
30 + position: absolute;
31 + white-space: pre;
32 + cursor: text;
33 + transform-origin: 0 0;
34 + user-select: text;
35 +}
36 +[data-pdf-text-layer] > :not(.markedContent),
37 +[data-pdf-text-layer] .markedContent span:not(.markedContent) {
38 + --font-height: 0;
39 + --scale-x: 1;
40 + --rotate: 0deg;
41 + font-size: calc(var(--text-scale-factor) * var(--font-height));
42 + transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv));
43 +}
44 +[data-pdf-text-layer] .markedContent {
45 + display: contents;
46 +}
47 +[data-pdf-text-layer] ::selection {
48 + background: #4a90e266;
49 +}
50 +[data-pdf-text-layer] .pdf-find-match {
51 + background: #ffc80066;
52 +}
apps/web/src/components/files/readBoundedDocument.ts new
+26
@@ -0,0 +1,26 @@
1 +export async function readBoundedDocument(
2 + src: string,
3 + signal: AbortSignal,
4 + limit: number,
5 + cache: RequestCache = "default",
6 +) {
7 + const response = await fetch(src, { signal, cache });
8 + if (!response.ok || Number(response.headers.get("content-length")) > limit)
9 + throw new Error("This file is unavailable or too large to preview.");
10 + const reader = response.body?.getReader();
11 + if (!reader) throw new Error("This file is unavailable.");
12 + const chunks: Uint8Array<ArrayBuffer>[] = [];
13 + let size = 0;
14 + try {
15 + while (true) {
16 + const { done, value } = await reader.read();
17 + if (done) break;
18 + size += value.length;
19 + if (size > limit) throw new Error("This file is too large to preview.");
20 + chunks.push(value);
21 + }
22 + } finally {
23 + await reader.cancel();
24 + }
25 + return new Blob(chunks).arrayBuffer();
26 +}
apps/web/src/pierre-icons.test.ts
+22
@@ -31,6 +31,28 @@ describe("Pierre file icons", () => {
31 );
32 });
33
34 + it.each([
35 + ["pdf", "pdf"],
36 + ["doc", "word"],
37 + ["docx", "word"],
38 + ["odt", "word"],
39 + ["rtf", "word"],
40 + ["xls", "spreadsheet"],
41 + ["xlsx", "spreadsheet"],
42 + ["ods", "spreadsheet"],
43 + ["csv", "spreadsheet"],
44 + ["tsv", "spreadsheet"],
45 + ["ppt", "slides"],
46 + ["pptx", "slides"],
47 + ["odp", "slides"],
48 + ["epub", "epub"],
49 + ])("uses the document family icon for %s", (extension, family) => {
50 + for (const path of [`report.${extension}`, `folder/REPORT.${extension.toUpperCase()}`]) {
51 + assert.equal(resolvePierreIconForEntry(path, "file")?.name, `t3-file-icon-${family}`);
52 + assert.isTrue(hasSpecificPierreIconForFileName(path));
53 + }
54 + });
55 +
56 it("ships every custom icon referenced by the extended resolver", () => {
57 const customIconNames = new Set(
58 [
apps/web/src/pierre-icons.ts
+69
@@ -13,6 +13,14 @@ export interface PierreIconResolution {
13
14 const PIERRE_ICON_SPRITE_ID = "t3code-pierre-file-icon-sprite";
15
16 +const DOCUMENT_ICON_COLORS: Readonly<Record<string, string>> = {
17 + "t3-file-icon-pdf": "light-dark(#d52c36, #ff6762)",
18 + "t3-file-icon-word": "light-dark(#1a85d4, #69b1ff)",
19 + "t3-file-icon-spreadsheet": "light-dark(#199f43, #5ecc71)",
20 + "t3-file-icon-slides": "light-dark(#d47628, #ffa359)",
21 + "t3-file-icon-epub": "light-dark(#693acf, #9d6afb)",
22 +};
23 +
24 const T3_FILE_ICON_SPRITE = `
25 <svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" aria-hidden="true">
26 <!-- Lucide Film icon, ISC license. -->
@@ -41,6 +49,48 @@ const T3_FILE_ICON_SPRITE = `
49 <symbol id="t3-file-icon-xml" viewBox="0 0 24 24">
50 <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" />
51 </symbol>
52 + <!-- Lucide File Type, File Text, File Spreadsheet, Presentation and Book Open icons, ISC license. -->
53 + <symbol id="t3-file-icon-pdf" viewBox="0 0 24 24">
54 + <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-pdf"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
55 + <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" />
56 + <path d="M14 2v5a1 1 0 0 0 1 1h5" />
57 + <path d="M11 18h2" />
58 + <path d="M12 12v6" />
59 + <path d="M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5" />
60 + </g>
61 + </symbol>
62 + <symbol id="t3-file-icon-word" viewBox="0 0 24 24">
63 + <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-word"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
64 + <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" />
65 + <path d="M14 2v5a1 1 0 0 0 1 1h5" />
66 + <path d="M10 9H8" />
67 + <path d="M16 13H8" />
68 + <path d="M16 17H8" />
69 + </g>
70 + </symbol>
71 + <symbol id="t3-file-icon-spreadsheet" viewBox="0 0 24 24">
72 + <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-spreadsheet"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
73 + <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" />
74 + <path d="M14 2v5a1 1 0 0 0 1 1h5" />
75 + <path d="M8 13h2" />
76 + <path d="M14 13h2" />
77 + <path d="M8 17h2" />
78 + <path d="M14 17h2" />
79 + </g>
80 + </symbol>
81 + <symbol id="t3-file-icon-slides" viewBox="0 0 24 24">
82 + <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-slides"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
83 + <path d="M2 3h20" />
84 + <path d="M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3" />
85 + <path d="m7 21 5-5 5 5" />
86 + </g>
87 + </symbol>
88 + <symbol id="t3-file-icon-epub" viewBox="0 0 24 24">
89 + <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-epub"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
90 + <path d="M12 7v14" />
91 + <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" />
92 + </g>
93 + </symbol>
94 <!-- Language logos from Simple Icons, CC0. -->
95 <symbol id="t3-file-icon-csharp" viewBox="0 0 24 24">
96 <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 = {
145 ...Object.fromEntries(
146 VIDEO_FILE_EXTENSIONS.map((extension) => [extension, "t3-file-icon-video"]),
147 ),
148 + pdf: "t3-file-icon-pdf",
149 + doc: "t3-file-icon-word",
150 + docx: "t3-file-icon-word",
151 + odt: "t3-file-icon-word",
152 + rtf: "t3-file-icon-word",
153 + xls: "t3-file-icon-spreadsheet",
154 + xlsx: "t3-file-icon-spreadsheet",
155 + ods: "t3-file-icon-spreadsheet",
156 + csv: "t3-file-icon-spreadsheet",
157 + tsv: "t3-file-icon-spreadsheet",
158 + ppt: "t3-file-icon-slides",
159 + pptx: "t3-file-icon-slides",
160 + odp: "t3-file-icon-slides",
161 + epub: "t3-file-icon-epub",
162 cs: "t3-file-icon-csharp",
163 csx: "t3-file-icon-csharp",
164 dart: "t3-file-icon-dart",
@@ -180,6 +244,11 @@ export function resolvePierreIconForEntry(
244 : icon;
245 }
246
247 +export function documentIconColorForFileName(fileName: string) {
248 + const icon = resolvePierreIconForEntry(fileName, "file");
249 + return icon ? DOCUMENT_ICON_COLORS[icon.name] : undefined;
250 +}
251 +
252 export function hasSpecificPierreIconForFileName(fileName: string): boolean {
253 return resolvePierreIconForEntry(fileName, "file")?.token !== "default";
254 }
apps/web/vite.config.ts
+13
@@ -11,6 +11,7 @@ import "vite-plus/test/config";
11 import { defineConfig, type Connect, type Plugin } from "vite-plus";
12 import * as Hash from "effect/Hash";
13 import pkg from "./package.json" with { type: "json" };
14 +import pdfjsPkg from "pdfjs-dist/package.json" with { type: "json" };
15
16 import {
17 DEV_PROXIED_ORIGIN_PRESERVING_PREFIXES,
@@ -112,9 +113,11 @@ const browserTestProject = {
113 "@betteroffice/xlsx",
114 "@betteroffice/xlsx/headless",
115 "fast-xml-parser",
116 + "entities",
117 "dompurify",
118 "heic-to/next",
119 "jszip",
120 + "pdfjs-dist",
121 "sql.js",
122 "tiff",
123 ],
@@ -351,9 +354,19 @@ export default defineConfig(() => {
354 sourcemap: buildSourcemap,
355 rolldownOptions: {
356 output: {
357 + // PDF.js resolves decoder modules and ICC data relative to wasmUrl.
358 + assetFileNames: (asset) =>
359 + asset.originalFileNames.some((path) => /[/\\]pdfjs-dist[/\\]wasm[/\\]/.test(path))
360 + ? `assets/pdfjs-${pdfjsPkg.version}/[name][extname]`
361 + : "assets/[name]-[hash][extname]",
362 codeSplitting: {
363 // Preview imports must not fold shared file icons back into main.
364 groups: [
365 + {
366 + name: "react",
367 + test: /\/node_modules\/(?:react|react-dom|scheduler)\//,
368 + includeDependenciesRecursively: false,
369 + },
370 {
371 name: "icons",
372 test: /\/(?:components\/chat\/PierreEntryIcon\.tsx|pierre-icons\.ts|mediaPreview\.ts)$/,
packages/shared/src/filePreview.test.ts
+14 -3
@@ -68,6 +68,12 @@ describe("workspace file previews", () => {
68 "pptx",
69 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
70 ],
71 + ["notes.odt", "odt", "application/vnd.oasis.opendocument.text"],
72 + ["budget.ods", "ods", "application/vnd.oasis.opendocument.spreadsheet"],
73 + ["deck.odp", "odp", "application/vnd.oasis.opendocument.presentation"],
74 + ["notes.rtf", "rtf", "application/rtf"],
75 + ["guide.epub", "epub", "application/epub+zip"],
76 + ["analysis.ipynb", "ipynb", "application/x-ipynb+json"],
77 ])("recognizes Office assets at literal path %s", (name, kind, mimeType) => {
78 expect(officePreviewKind({ name })).toBe(kind);
79 expect(filePreviewKind({ name, mimeType: "application/octet-stream" })).toBe(kind);
@@ -85,6 +91,9 @@ describe("workspace file previews", () => {
91 "report.xlsx?download=1",
92 "slides%2Epptx",
93 "report.docm",
94 + "guide.epub?download=1",
95 + "analysis.ipynb#notes.txt",
96 + "report.odt.ts",
97 "slides.ppt",
98 ])("rejects non-preview path %s", (path) => {
99 expect(isWorkspacePreviewEntryPath(path)).toBe(false);
@@ -145,8 +154,10 @@ describe("attachment preview classification", () => {
154 ["diagram.MERMAID", "text/plain", "mermaid"],
155 ["download", "text/vnd.mermaid", "mermaid"],
156 ["source-code.otf", "application/vnd.oasis.opendocument.formula-template", "font"],
148 - ["notes.rtf", "application/rtf", "text"],
149 - ["notes.rtf", "", "text"],
157 + ["notes.rtf", "application/rtf", "rtf"],
158 + ["notes.rtf", "", "rtf"],
159 + ["download", "text/rtf", "rtf"],
160 + ["analysis.IPYNB", "application/json", "ipynb"],
161 ["clip.weba", "", "audio"],
162 ["image.bmp", "application/octet-stream", "image"],
163 ["photo.heic", "application/octet-stream", "image"],
@@ -165,7 +176,7 @@ describe("attachment preview classification", () => {
176 expect(() => decodeFilePreviewText(new Uint8Array([65, 0, 66]))).toThrow("binary");
177 expect(() => decodeFilePreviewText(new Uint8Array([255]))).toThrow("UTF-8");
178 });
168 - it.each(["doc", "xls", "ppt", "odt", "ods", "odp", "epub", "7z", "rar"])(
179 + it.each(["doc", "xls", "ppt", "7z", "rar"])(
180 "retains the binary fallback for %s, which opencode does not render",
181 (extension) => {
182 expect(filePreviewKind({ name: `sample.${extension}` })).toBe("unsupported");
packages/shared/src/filePreview.ts
+18 -3
@@ -25,6 +25,12 @@ export type FilePreviewKind =
25 | "docx"
26 | "xlsx"
27 | "pptx"
28 + | "odt"
29 + | "ods"
30 + | "odp"
31 + | "rtf"
32 + | "epub"
33 + | "ipynb"
34 | "text"
35 | "unsupported";
36
@@ -54,7 +60,6 @@ export function filePreviewKind(
60 mime === "application/vnd.oasis.opendocument.formula-template"
61 )
62 return "font";
57 - if (richDocuments && mime === "application/rtf") return "text";
63 if (mime.startsWith("image/")) return "image";
64 if (mime.startsWith("video/")) return "video";
65 if (mime.startsWith("audio/")) return "audio";
@@ -132,6 +137,12 @@ const OFFICE_MIME_TYPES = {
137 docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
138 xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
139 pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
140 + odt: "application/vnd.oasis.opendocument.text",
141 + ods: "application/vnd.oasis.opendocument.spreadsheet",
142 + odp: "application/vnd.oasis.opendocument.presentation",
143 + rtf: "application/rtf",
144 + epub: "application/epub+zip",
145 + ipynb: "application/x-ipynb+json",
146 } as const;
147
148 export type OfficePreviewKind = keyof typeof OFFICE_MIME_TYPES;
@@ -141,10 +152,14 @@ export function officePreviewKind(file: {
152 readonly mimeType?: string;
153 }): OfficePreviewKind | null {
154 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
144 - for (const kind of ["docx", "xlsx", "pptx"] as const) {
155 + if (mime === "text/rtf") return "rtf";
156 + for (const kind of Object.keys(OFFICE_MIME_TYPES) as OfficePreviewKind[]) {
157 if (mime === OFFICE_MIME_TYPES[kind]) return kind;
158 if (
147 - (!mime || mime === "application/octet-stream" || mime === "text/plain") &&
159 + (!mime ||
160 + mime === "application/octet-stream" ||
161 + mime === "text/plain" ||
162 + (kind === "ipynb" && mime === "application/json")) &&
163 file.name.toLowerCase().endsWith(`.${kind}`)
164 )
165 return kind;
pnpm-lock.yaml
+137
@@ -1136,6 +1136,9 @@ importers:
1136 effect:
1137 specifier: 4.0.5
1138 version: 4.0.5
1139 + entities:
1140 + specifier: 8.1.0
1141 + version: 8.1.0
1142 fast-xml-parser:
1143 specifier: 5.7.3
1144 version: 5.7.3
@@ -1169,6 +1172,9 @@ importers:
1172 morphicons:
1173 specifier: ^1.7.1
1174 version: 1.7.1(react-native-svg@15.16.0(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
1175 + pdfjs-dist:
1176 + specifier: 6.4.299
1177 + version: 6.4.299
1178 pele:
1179 specifier: ^1.8.0
1180 version: 1.8.0
@@ -4558,6 +4564,81 @@ packages:
4564 '@types/node':
4565 optional: true
4566
4567 + '@napi-rs/canvas-android-arm64@1.0.13':
4568 + resolution: {integrity: sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==}
4569 + engines: {node: '>= 10'}
4570 + cpu: [arm64]
4571 + os: [android]
4572 +
4573 + '@napi-rs/canvas-darwin-arm64@1.0.13':
4574 + resolution: {integrity: sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==}
4575 + engines: {node: '>= 10'}
4576 + cpu: [arm64]
4577 + os: [darwin]
4578 +
4579 + '@napi-rs/canvas-darwin-x64@1.0.13':
4580 + resolution: {integrity: sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==}
4581 + engines: {node: '>= 10'}
4582 + cpu: [x64]
4583 + os: [darwin]
4584 +
4585 + '@napi-rs/canvas-linux-arm-gnueabihf@1.0.13':
4586 + resolution: {integrity: sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==}
4587 + engines: {node: '>= 10'}
4588 + cpu: [arm]
4589 + os: [linux]
4590 +
4591 + '@napi-rs/canvas-linux-arm64-gnu@1.0.13':
4592 + resolution: {integrity: sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==}
4593 + engines: {node: '>= 10'}
4594 + cpu: [arm64]
4595 + os: [linux]
4596 + libc: [glibc]
4597 +
4598 + '@napi-rs/canvas-linux-arm64-musl@1.0.13':
4599 + resolution: {integrity: sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==}
4600 + engines: {node: '>= 10'}
4601 + cpu: [arm64]
4602 + os: [linux]
4603 + libc: [musl]
4604 +
4605 + '@napi-rs/canvas-linux-riscv64-gnu@1.0.13':
4606 + resolution: {integrity: sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==}
4607 + engines: {node: '>= 10'}
4608 + cpu: [riscv64]
4609 + os: [linux]
4610 + libc: [glibc]
4611 +
4612 + '@napi-rs/canvas-linux-x64-gnu@1.0.13':
4613 + resolution: {integrity: sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==}
4614 + engines: {node: '>= 10'}
4615 + cpu: [x64]
4616 + os: [linux]
4617 + libc: [glibc]
4618 +
4619 + '@napi-rs/canvas-linux-x64-musl@1.0.13':
4620 + resolution: {integrity: sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==}
4621 + engines: {node: '>= 10'}
4622 + cpu: [x64]
4623 + os: [linux]
4624 + libc: [musl]
4625 +
4626 + '@napi-rs/canvas-win32-arm64-msvc@1.0.13':
4627 + resolution: {integrity: sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==}
4628 + engines: {node: '>= 10'}
4629 + cpu: [arm64]
4630 + os: [win32]
4631 +
4632 + '@napi-rs/canvas-win32-x64-msvc@1.0.13':
4633 + resolution: {integrity: sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==}
4634 + engines: {node: '>= 10'}
4635 + cpu: [x64]
4636 + os: [win32]
4637 +
4638 + '@napi-rs/canvas@1.0.13':
4639 + resolution: {integrity: sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==}
4640 + engines: {node: '>= 10'}
4641 +
4642 '@napi-rs/keyring-darwin-arm64@1.3.0':
4643 resolution: {integrity: sha512-pl76hJvdYUBn6I24bXiOBMA9nbDapo3I5B+f3OorjDU4dUMSypXeKbOVehJe8fhgTiH24flMyTS3aAIy43xegQ==}
4644 engines: {node: '>= 10'}
@@ -10375,6 +10456,10 @@ packages:
10456 pause-stream@0.0.11:
10457 resolution: {integrity: sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A==}
10458
10459 + pdfjs-dist@6.4.299:
10460 + resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}
10461 + engines: {node: '>=22.13.0 || >=24'}
10462 +
10463 pe-library@0.4.1:
10464 resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==}
10465 engines: {node: '>=12', npm: '>=6'}
@@ -14793,6 +14878,54 @@ snapshots:
14878 optionalDependencies:
14879 '@types/node': 24.12.4
14880
14881 + '@napi-rs/canvas-android-arm64@1.0.13':
14882 + optional: true
14883 +
14884 + '@napi-rs/canvas-darwin-arm64@1.0.13':
14885 + optional: true
14886 +
14887 + '@napi-rs/canvas-darwin-x64@1.0.13':
14888 + optional: true
14889 +
14890 + '@napi-rs/canvas-linux-arm-gnueabihf@1.0.13':
14891 + optional: true
14892 +
14893 + '@napi-rs/canvas-linux-arm64-gnu@1.0.13':
14894 + optional: true
14895 +
14896 + '@napi-rs/canvas-linux-arm64-musl@1.0.13':
14897 + optional: true
14898 +
14899 + '@napi-rs/canvas-linux-riscv64-gnu@1.0.13':
14900 + optional: true
14901 +
14902 + '@napi-rs/canvas-linux-x64-gnu@1.0.13':
14903 + optional: true
14904 +
14905 + '@napi-rs/canvas-linux-x64-musl@1.0.13':
14906 + optional: true
14907 +
14908 + '@napi-rs/canvas-win32-arm64-msvc@1.0.13':
14909 + optional: true
14910 +
14911 + '@napi-rs/canvas-win32-x64-msvc@1.0.13':
14912 + optional: true
14913 +
14914 + '@napi-rs/canvas@1.0.13':
14915 + optionalDependencies:
14916 + '@napi-rs/canvas-android-arm64': 1.0.13
14917 + '@napi-rs/canvas-darwin-arm64': 1.0.13
14918 + '@napi-rs/canvas-darwin-x64': 1.0.13
14919 + '@napi-rs/canvas-linux-arm-gnueabihf': 1.0.13
14920 + '@napi-rs/canvas-linux-arm64-gnu': 1.0.13
14921 + '@napi-rs/canvas-linux-arm64-musl': 1.0.13
14922 + '@napi-rs/canvas-linux-riscv64-gnu': 1.0.13
14923 + '@napi-rs/canvas-linux-x64-gnu': 1.0.13
14924 + '@napi-rs/canvas-linux-x64-musl': 1.0.13
14925 + '@napi-rs/canvas-win32-arm64-msvc': 1.0.13
14926 + '@napi-rs/canvas-win32-x64-msvc': 1.0.13
14927 + optional: true
14928 +
14929 '@napi-rs/keyring-darwin-arm64@1.3.0':
14930 optional: true
14931
@@ -20858,6 +20991,10 @@ snapshots:
20991 dependencies:
20992 through: 2.3.8
20993
20994 + pdfjs-dist@6.4.299:
20995 + optionalDependencies:
20996 + '@napi-rs/canvas': 1.0.13
20997 +
20998 pe-library@0.4.1: {}
20999
21000 pele@1.8.0: {}
third-party-licenses.config.json
+12
@@ -229,6 +229,12 @@
229 }
230 ],
231 "packageOverrides": [
232 + {
233 + "name": "entities",
234 + "version": "8.1.0",
235 + "license": "BSD-2-Clause",
236 + "sourceUrl": "https://github.com/fb55/entities"
237 + },
238 {
239 "name": "@nodable/entities",
240 "version": "2.1.1",
@@ -304,6 +310,12 @@
310 ]
311 }
312 },
313 + {
314 + "name": "pdfjs-dist",
315 + "version": "6.4.299",
316 + "license": "Apache-2.0",
317 + "sourceUrl": "https://github.com/mozilla/pdf.js"
318 + },
319 {
320 "name": "@betteroffice/fonts",
321 "version": "0.4.0",