Open History to see the last commit
1import { act, useEffect, 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 presentationFinished: false,
18}));
19
20vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl }));
21vi.mock("../../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() }));
22vi.mock("../../lib/attachmentDownload", () => ({
23 downloadAndShareAttachment: vi.fn(),
24 nativeViewerErrorMessage: () => "",
25 shareLocalAttachment: vi.fn(),
26}));
27vi.mock("../../lib/previewPresentation", () => ({ usePreviewPresentation: () => {} }));
28vi.mock("./Dialog", () => ({ alert: harness.alert }));
29
30import type { FilePreviewItem, FilePreviewViewerProps } from "./FilePreviewModal.types";
31import { FilePreviewSession } from "./FilePreviewSession";
32
33function Viewer(props: FilePreviewViewerProps) {
34 useState(() => harness.mounts++);
35 harness.previews.push(props.source);
36 const { onPresent } = props;
37 // Stands in for the native presentation starting.
38 useEffect(() => onPresent?.(() => harness.presentationFinished), [onPresent]);
39 return null;
40}
41
42const environmentId = EnvironmentId.make("environment");
43const image = (url: string): FilePreviewItem => ({
44 kind: "image",
45 environmentId,
46 resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
47});
48
49async function openGallery(
50 selected: FilePreviewItem,
51 gallery: readonly FilePreviewItem[],
52 progressiveGallery: boolean,
53) {
54 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
55 harness.previews.length = 0;
56 harness.mounts = 0;
57 harness.alert.mockClear();
58 const root = createRoot(document.createElement("div"));
59 const onRequestClose = vi.fn();
60 await act(async () =>
61 root.render(
62 <FilePreviewSession
63 source={{ ...selected, gallery }}
64 onRequestClose={onRequestClose}
65 progressiveGallery={progressiveGallery}
66 Viewer={Viewer}
67 />,
68 ),
69 );
70 return { onRequestClose, [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
71}
72
73it.each([true, false])(
74 "keeps the gallery stable while a sibling is still resolving (progressive: %s)",
75 async (progressiveGallery) => {
76 const slow = Promise.withResolvers<string>();
77 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) =>
78 resource.url.endsWith("slow.png") ? slow.promise : "https://signed.test/a.png",
79 );
80 const selected = image("https://github.com/a.png");
81 await using _preview = await openGallery(
82 selected,
83 [image("https://github.com/slow.png"), selected],
84 progressiveGallery,
85 );
86
87 if (progressiveGallery) {
88 expect(harness.previews.at(-1)).toMatchObject({
89 kind: "image",
90 selectedIndex: 1,
91 images: [
92 expect.not.objectContaining({ uri: expect.anything() }),
93 { uri: "https://signed.test/a.png" },
94 ],
95 });
96 } else {
97 expect(harness.previews).toEqual([]);
98 }
99 await act(async () => slow.resolve("https://signed.test/slow.png"));
100 expect(harness.previews.at(-1)).toMatchObject({
101 selectedIndex: 1,
102 images: [{ uri: "https://signed.test/slow.png" }, { uri: "https://signed.test/a.png" }],
103 });
104 expect(harness.mounts).toBe(1);
105 },
106);
107
108it.each([true, false])(
109 "handles a failed sibling without leaving a pending page (progressive: %s)",
110 async (progressiveGallery) => {
111 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
112 if (resource.url.endsWith("missing.png")) throw new Error("not found");
113 return `https://signed.test/${resource.url.split("/").pop()}`;
114 });
115 const selected = image("https://github.com/a.png");
116 await using preview = await openGallery(
117 selected,
118 [selected, image("https://github.com/missing.png"), image("https://github.com/c.png")],
119 progressiveGallery,
120 );
121
122 if (!progressiveGallery) {
123 expect(preview.onRequestClose).toHaveBeenCalledOnce();
124 expect(harness.alert).toHaveBeenCalledOnce();
125 expect(harness.previews).toEqual([]);
126 return;
127 }
128
129 expect(preview.onRequestClose).not.toHaveBeenCalled();
130 expect(harness.alert).not.toHaveBeenCalled();
131 expect(harness.previews.at(-1)).toMatchObject({
132 selectedIndex: 0,
133 images: [
134 { uri: "https://signed.test/a.png" },
135 { failed: true },
136 { uri: "https://signed.test/c.png" },
137 ],
138 });
139 },
140);
141
142it("closes the preview when the selected image cannot be resolved", async () => {
143 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
144 if (resource.url.endsWith("missing.png")) throw new Error("not found");
145 return `https://signed.test/${resource.url.split("/").pop()}`;
146 });
147 const selected = image("https://github.com/missing.png");
148 await using preview = await openGallery(
149 selected,
150 [image("https://github.com/a.png"), selected],
151 true,
152 );
153
154 expect(preview.onRequestClose).toHaveBeenCalledOnce();
155 expect(harness.alert).toHaveBeenCalledOnce();
156});
157
158it("names the checked path when the server cannot find the file", async () => {
159 const resource = {
160 _tag: "media-file" as const,
161 threadId: ThreadId.make("thread"),
162 path: "v2/extended/duo-color-3-extended-FINAL.png",
163 };
164 const checkedPath = "/repo/v2/extended/duo-color-3-extended-FINAL.png";
165 harness.refreshAssetUrl.mockRejectedValue(
166 new AssetWorkspaceAssetNotFoundError({ resource, checkedPath }),
167 );
168 const selected: FilePreviewItem = { kind: "image", environmentId, resource };
169 await using preview = await openGallery(selected, [selected], false);
170
171 expect(preview.onRequestClose).toHaveBeenCalledOnce();
172 expect(harness.alert).toHaveBeenCalledWith(
173 "Could not open preview",
174 expect.stringContaining(checkedPath),
175 );
176 expect(harness.alert.mock.calls[0]?.[1]).not.toMatch(/reconnect/i);
177});
178
179it.each([
180 // Handed to native but not yet started there, or still on screen.
181 ["image", false, 1],
182 ["image", true, 2],
183 // A PDF is still resolving here, so its viewer never presented and a re-render must not restart it.
184 ["pdf", true, 1],
185] as const)(
186 "a re-tap of the open %s restarts the preview only once its native viewer closed (closed: %s)",
187 async (kind, finished, starts) => {
188 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
189 harness.presentationFinished = finished;
190 harness.mounts = 0;
191 harness.refreshAssetUrl.mockReset();
192 if (kind === "image") harness.refreshAssetUrl.mockResolvedValue("https://signed.test/a.png");
193 else harness.refreshAssetUrl.mockReturnValue(new Promise(() => {}));
194 const selected: FilePreviewItem = { ...image("https://github.com/a.png"), kind };
195 const root = createRoot(document.createElement("div"));
196 await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
197 const render = () =>
198 act(async () =>
199 root.render(
200 <FilePreviewSession
201 source={{ ...selected, gallery: [selected] }}
202 onRequestClose={() => {}}
203 progressiveGallery
204 Viewer={Viewer}
205 />,
206 ),
207 );
208 await render();
209 await render();
210 expect(harness.refreshAssetUrl).toHaveBeenCalledTimes(starts);
211 },
212);
213
214it("does not carry a presented viewer over to a different item that is still resolving", async () => {
215 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
216 harness.presentationFinished = true;
217 harness.refreshAssetUrl.mockReset();
218 harness.refreshAssetUrl.mockImplementation((_environmentId, resource) =>
219 resource.url.endsWith("a.png")
220 ? Promise.resolve("https://signed.test/a.png")
221 : new Promise(() => {}),
222 );
223 const shown = image("https://github.com/a.png");
224 const resolving: FilePreviewItem = { ...image("https://github.com/b.pdf"), kind: "pdf" };
225 const root = createRoot(document.createElement("div"));
226 await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
227 const render = (item: FilePreviewItem) =>
228 act(async () =>
229 root.render(
230 <FilePreviewSession
231 source={{ ...item, gallery: [item] }}
232 onRequestClose={() => {}}
233 progressiveGallery
234 Viewer={Viewer}
235 />,
236 ),
237 );
238 await render(shown);
239 await render(resolving);
240 await render(resolving);
241 expect(
242 harness.refreshAssetUrl.mock.calls.filter(([, r]) => r.url.endsWith("b.pdf")),
243 ).toHaveLength(1);
244});