Skip to content

Commit 9ce2ac0

Browse files
committed
feat(web): preview ZIP attachments
1 parent 8414d16 commit 9ce2ac0

7 files changed

Lines changed: 1118 additions & 2 deletions

File tree

‎apps/web/src/components/files/AttachmentFilePreview.tsx‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,10 @@ import {
2626
FileSurfaceLoading,
2727
FileSurfaceNotice,
2828
} from "./fileSurfaceChrome";
29+
import { isZipPreviewFile } from "./filePreviewMode";
2930

3031
const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
32+
const ZipArchivePreview = lazy(() => import("./ZipArchivePreview"));
3133

3234
/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
3335
const STALE_URL_MS = 5 * 60_000;
@@ -68,8 +70,9 @@ export function AttachmentFilePreview(props: {
6870
onRemove?: () => void;
6971
onClose?: () => void;
7072
}) {
71-
const kind = filePreviewKind(props);
72-
const delimiter = filePreviewDelimiter(props);
73+
const isZip = isZipPreviewFile(props);
74+
const kind = isZip ? "unsupported" : filePreviewKind(props);
75+
const delimiter = isZip ? null : filePreviewDelimiter(props);
7376
const renderedMode =
7477
kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;
7578
const attachmentId = props.asset?.attachmentId;
@@ -277,6 +280,16 @@ export function AttachmentFilePreview(props: {
277280
onError={() => setError("Unable to load image.")}
278281
/>
279282
</div>
283+
) : isZip ? (
284+
<Suspense fallback={<FileSurfaceLoading />}>
285+
<ZipArchivePreview
286+
key={`${url}:${revision}`}
287+
name={props.name}
288+
file={props.file ?? null}
289+
url={url}
290+
onRetry={() => setRevision((value) => value + 1)}
291+
/>
292+
</Suspense>
280293
) : (
281294
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center">
282295
<p className="text-sm font-medium">No preview for this file</p>

‎apps/web/src/components/files/FilePreviewPanel.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
import {
1212
filePreviewReadErrorMessage,
1313
isMarkdownPreviewFile,
14+
isZipPreviewFile,
1415
resolveFilePreviewPath,
1516
setMarkdownTaskChecked,
1617
shouldShowFileExplorer,
@@ -120,6 +121,26 @@ describe("isMarkdownPreviewFile", () => {
120121
});
121122
});
122123

124+
describe("isZipPreviewFile", () => {
125+
it("recognizes ZIP archives by MIME type or extension", () => {
126+
expect(isZipPreviewFile({ name: "photos", mimeType: "application/zip; charset=binary" })).toBe(
127+
true,
128+
);
129+
expect(isZipPreviewFile({ name: "photos", mimeType: "application/x-zip-compressed" })).toBe(
130+
true,
131+
);
132+
expect(isZipPreviewFile({ name: "Photos.ZIP", mimeType: "application/octet-stream" })).toBe(
133+
true,
134+
);
135+
expect(isZipPreviewFile({ name: "photos.zip", mimeType: "text/plain" })).toBe(true);
136+
});
137+
138+
it("does not treat other archives or ZIP-based documents as ZIP previews", () => {
139+
expect(isZipPreviewFile({ name: "photos.tar.gz", mimeType: "application/gzip" })).toBe(false);
140+
expect(isZipPreviewFile({ name: "report.docx", mimeType: "" })).toBe(false);
141+
});
142+
});
143+
123144
describe("shouldShowFileExplorer", () => {
124145
it("hides the workspace tree for host files and attachments", () => {
125146
expect(
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// @vitest-environment jsdom
2+
import { act, type ReactNode } from "react";
3+
import { createRoot, type Root } from "react-dom/client";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5+
6+
import type { ZipPreviewEntry } from "~/lib/zipPreview";
7+
8+
import ZipArchivePreview from "./ZipArchivePreview";
9+
10+
const entries: ZipPreviewEntry[] = [
11+
{ path: "photos/", name: "photos", isDirectory: true, sizeBytes: 0, mimeType: null },
12+
{ path: "photos/a.png", name: "a.png", isDirectory: false, sizeBytes: 3, mimeType: "image/png" },
13+
];
14+
15+
vi.mock("~/lib/zipPreview", () => ({
16+
loadZipPreview: async () => ({
17+
entries,
18+
readImage: async (entry: ZipPreviewEntry) => new Blob([entry.name], { type: "image/png" }),
19+
}),
20+
readZipPreviewResponse: vi.fn(),
21+
}));
22+
vi.mock("~/hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "light" }) }));
23+
vi.mock("~/components/chat/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
24+
vi.mock("./fileSurfaceChrome", () => ({
25+
FileSurfaceFailure: ({ message }: { message: string }) => <div role="alert">{message}</div>,
26+
FileSurfaceLoading: () => <div role="status">Loading</div>,
27+
}));
28+
vi.mock("~/components/ui/scroll-area", () => ({
29+
ScrollArea: ({ children }: { children: ReactNode }) => children,
30+
}));
31+
32+
let root: Root;
33+
let container: HTMLDivElement;
34+
let intersect: (isIntersecting: boolean) => void;
35+
const revoked: string[] = [];
36+
37+
const flush = () => act(async () => {});
38+
const button = (label: string) =>
39+
[...container.querySelectorAll("button")].find(
40+
(element) =>
41+
element.getAttribute("aria-label") === label || element.textContent?.startsWith(label),
42+
)!;
43+
const press = (key: string) =>
44+
act(() => {
45+
document.activeElement!.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));
46+
});
47+
48+
beforeEach(async () => {
49+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
50+
let next = 0;
51+
vi.stubGlobal("URL", {
52+
...URL,
53+
createObjectURL: () => `blob:${next++}`,
54+
revokeObjectURL: (url: string) => revoked.push(url),
55+
});
56+
vi.stubGlobal(
57+
"IntersectionObserver",
58+
class {
59+
constructor(callback: (entries: { isIntersecting: boolean }[]) => void) {
60+
intersect = (isIntersecting) => callback([{ isIntersecting }]);
61+
}
62+
observe() {}
63+
disconnect() {}
64+
},
65+
);
66+
revoked.length = 0;
67+
container = document.createElement("div");
68+
document.body.append(container);
69+
root = createRoot(container);
70+
await act(() =>
71+
root.render(
72+
<ZipArchivePreview name="photos.zip" file={new Blob()} url="blob:zip" onRetry={() => {}} />,
73+
),
74+
);
75+
await flush();
76+
});
77+
78+
afterEach(async () => {
79+
await act(() => root.unmount());
80+
container.remove();
81+
vi.unstubAllGlobals();
82+
});
83+
84+
describe("ZipArchivePreview", () => {
85+
it("releases thumbnails that leave the viewport and reloads them on return", async () => {
86+
await act(() => button("photos").click());
87+
await act(() => intersect(true));
88+
await flush();
89+
expect(container.querySelector("img")?.getAttribute("src")).toBe("blob:0");
90+
91+
await act(() => intersect(false));
92+
expect(container.querySelector("img")).toBeNull();
93+
expect(revoked).toEqual(["blob:0"]);
94+
95+
await act(() => intersect(true));
96+
await flush();
97+
expect(container.querySelector("img")?.getAttribute("src")).toBe("blob:1");
98+
});
99+
100+
it("keeps keyboard back navigation after the clicked tile unmounts", async () => {
101+
await act(() => button("photos").click());
102+
await act(() => intersect(true));
103+
await flush();
104+
await act(() => button("Open a.png").click());
105+
await flush();
106+
expect(container.querySelector("img[alt='a.png']")).not.toBeNull();
107+
108+
await press("Escape");
109+
expect(container.querySelector("img[alt='a.png']")).toBeNull();
110+
expect(button("Open a.png")).toBeDefined();
111+
112+
await press("Backspace");
113+
expect(button("photos")).toBeDefined();
114+
expect(container.querySelector("[aria-current='page']")?.textContent).toBe("photos.zip");
115+
});
116+
});

0 commit comments

Comments
 (0)