Open History to see the last commit
1import { act, useState } from "react";
2import { createRoot } from "react-dom/client";
3import { expect, it, vi } from "vite-plus/test";
4import {
5 AssetWorkspaceAssetNotFoundError,
6 EnvironmentId,
7 SOURCE_CONTROL_MEDIA_ASSET,
8 ThreadId,
9} from "@t3tools/contracts";
10
11const harness = vi.hoisted(() => ({
12 refreshAssetUrl:
13 vi.fn<(environmentId: string, resource: { url: string }) => Promise<string | null>>(),
14 alert: vi.fn(),
15 previews: [] as unknown[],
16 mounts: 0,
17}));
18
19vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl }));
20vi.mock("../../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() }));
21vi.mock("../../lib/attachmentDownload", () => ({
22 downloadAndShareAttachment: vi.fn(),
23 nativeViewerErrorMessage: () => "",
24 shareLocalAttachment: vi.fn(),
25}));
26vi.mock("../../lib/previewPresentation", () => ({ usePreviewPresentation: () => {} }));
27vi.mock("./Dialog", () => ({ alert: harness.alert }));
28
29import type { FilePreviewItem, FilePreviewViewerProps } from "./FilePreviewModal.types";
30import { FilePreviewSession } from "./FilePreviewSession";
31
32function Viewer(props: FilePreviewViewerProps) {
33 useState(() => harness.mounts++);
34 harness.previews.push(props.source);
35 return null;
36}
37
38const environmentId = EnvironmentId.make("environment");
39const image = (url: string): FilePreviewItem => ({
40 kind: "image",
41 environmentId,
42 resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
43});
44
45async function openGallery(
46 selected: FilePreviewItem,
47 gallery: readonly FilePreviewItem[],
48 progressiveGallery: boolean,
49) {
50 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
51 harness.previews.length = 0;
52 harness.mounts = 0;
53 harness.alert.mockClear();
54 const root = createRoot(document.createElement("div"));
55 const onRequestClose = vi.fn();
56 await act(async () =>
57 root.render(
58 <FilePreviewSession
59 source={{ ...selected, gallery }}
60 onRequestClose={onRequestClose}
61 progressiveGallery={progressiveGallery}
62 Viewer={Viewer}
63 />,
64 ),
65 );
66 return { onRequestClose, [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
67}
68
69it.each([true, false])(
70 "keeps the gallery stable while a sibling is still resolving (progressive: %s)",
71 async (progressiveGallery) => {
72 const slow = Promise.withResolvers<string>();
73 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) =>
74 resource.url.endsWith("slow.png") ? slow.promise : "https://signed.test/a.png",
75 );
76 const selected = image("https://github.com/a.png");
77 await using _preview = await openGallery(
78 selected,
79 [image("https://github.com/slow.png"), selected],
80 progressiveGallery,
81 );
82
83 if (progressiveGallery) {
84 expect(harness.previews.at(-1)).toMatchObject({
85 kind: "image",
86 selectedIndex: 1,
87 images: [
88 expect.not.objectContaining({ uri: expect.anything() }),
89 { uri: "https://signed.test/a.png" },
90 ],
91 });
92 } else {
93 expect(harness.previews).toEqual([]);
94 }
95 await act(async () => slow.resolve("https://signed.test/slow.png"));
96 expect(harness.previews.at(-1)).toMatchObject({
97 selectedIndex: 1,
98 images: [{ uri: "https://signed.test/slow.png" }, { uri: "https://signed.test/a.png" }],
99 });
100 expect(harness.mounts).toBe(1);
101 },
102);
103
104it.each([true, false])(
105 "handles a failed sibling without leaving a pending page (progressive: %s)",
106 async (progressiveGallery) => {
107 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
108 if (resource.url.endsWith("missing.png")) throw new Error("not found");
109 return `https://signed.test/${resource.url.split("/").pop()}`;
110 });
111 const selected = image("https://github.com/a.png");
112 await using preview = await openGallery(
113 selected,
114 [selected, image("https://github.com/missing.png"), image("https://github.com/c.png")],
115 progressiveGallery,
116 );
117
118 if (!progressiveGallery) {
119 expect(preview.onRequestClose).toHaveBeenCalledOnce();
120 expect(harness.alert).toHaveBeenCalledOnce();
121 expect(harness.previews).toEqual([]);
122 return;
123 }
124
125 expect(preview.onRequestClose).not.toHaveBeenCalled();
126 expect(harness.alert).not.toHaveBeenCalled();
127 expect(harness.previews.at(-1)).toMatchObject({
128 selectedIndex: 0,
129 images: [
130 { uri: "https://signed.test/a.png" },
131 { failed: true },
132 { uri: "https://signed.test/c.png" },
133 ],
134 });
135 },
136);
137
138it("closes the preview when the selected image cannot be resolved", async () => {
139 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
140 if (resource.url.endsWith("missing.png")) throw new Error("not found");
141 return `https://signed.test/${resource.url.split("/").pop()}`;
142 });
143 const selected = image("https://github.com/missing.png");
144 await using preview = await openGallery(
145 selected,
146 [image("https://github.com/a.png"), selected],
147 true,
148 );
149
150 expect(preview.onRequestClose).toHaveBeenCalledOnce();
151 expect(harness.alert).toHaveBeenCalledOnce();
152});
153
154it("names the checked path when the server cannot find the file", async () => {
155 const resource = {
156 _tag: "media-file" as const,
157 threadId: ThreadId.make("thread"),
158 path: "v2/extended/duo-color-3-extended-FINAL.png",
159 };
160 const checkedPath = "/repo/v2/extended/duo-color-3-extended-FINAL.png";
161 harness.refreshAssetUrl.mockRejectedValue(
162 new AssetWorkspaceAssetNotFoundError({ resource, checkedPath }),
163 );
164 const selected: FilePreviewItem = { kind: "image", environmentId, resource };
165 await using preview = await openGallery(selected, [selected], false);
166
167 expect(preview.onRequestClose).toHaveBeenCalledOnce();
168 expect(harness.alert).toHaveBeenCalledWith(
169 "Could not open preview",
170 expect.stringContaining(checkedPath),
171 );
172 expect(harness.alert.mock.calls[0]?.[1]).not.toMatch(/reconnect/i);
173});