Open History to see the last commit
1import type { ReactNode } from "react";
2import { act } from "react";
3import { createRoot } from "react-dom/client";
4import { expect, it, vi } from "vite-plus/test";
5
6type HandlerProps = Record<string, ((event: unknown) => void) | undefined>;
7type GestureHandlers = Record<string, (event: unknown, manager?: unknown) => void>;
8type Transform = [{ translateX: number }, { translateY: number }, { scale: number }];
9
10const harness = vi.hoisted(() => ({
11 failImage: () => {},
12 loadImage: (_event: { source: { width: number; height: number } }) => {},
13 Passthrough: ({ children }: { children?: unknown }) => children,
14 pressable: {} as HandlerProps,
15 gestures: {} as Record<string, GestureHandlers>,
16 contentStyle: () => ({}) as { transform?: Transform },
17}));
18
19vi.mock("react-native", () => {
20 const View = ({ children, style }: { children?: ReactNode; style?: unknown }) => (
21 <div data-style={JSON.stringify(style)}>{children}</div>
22 );
23 return {
24 Platform: { OS: "ios" },
25 Pressable: (props: HandlerProps & { children?: ReactNode; style?: unknown }) => {
26 harness.pressable = props;
27 return <View style={props.style}>{props.children}</View>;
28 },
29 StyleSheet: { absoluteFill: {} },
30 View,
31 };
32});
33vi.mock("react-native-gesture-handler", () => {
34 // Records each gesture's callbacks so a test can drive the worklets with native-shaped events.
35 const builder = (kind: string) => () => {
36 const handlers: GestureHandlers = {};
37 harness.gestures[kind] = handlers;
38 const gesture: object = new Proxy(
39 {},
40 {
41 get: (_target, name) => (callback: GestureHandlers[string]) => {
42 if (typeof name === "string" && name.startsWith("on")) handlers[name] = callback;
43 return gesture;
44 },
45 },
46 );
47 return gesture;
48 };
49 return {
50 Gesture: { Pinch: builder("pinch"), Pan: builder("pan"), Simultaneous: () => ({}) },
51 GestureDetector: ({ children }: { children?: ReactNode }) => children,
52 };
53});
54vi.mock("react-native-reanimated", async () => {
55 const { useState } = await import("react");
56 return {
57 default: { View: ({ children }: { children?: ReactNode }) => <div>{children}</div> },
58 runOnJS: (callback: () => void) => callback,
59 // Reads the UI-thread style on demand, as Reanimated would after a gesture frame.
60 useAnimatedStyle: (updater: () => { transform?: Transform }) => {
61 harness.contentStyle = updater;
62 return {};
63 },
64 useSharedValue: <T,>(initial: T) =>
65 useState(() => {
66 let value = initial;
67 return { get: () => value, set: (next: T) => void (value = next) };
68 })[0],
69 };
70});
71vi.mock("expo-image", () => ({
72 Image: (props: {
73 onError: () => void;
74 onLoad: (event: { source: { width: number; height: number } }) => void;
75 }) => {
76 harness.failImage = props.onError;
77 harness.loadImage = props.onLoad;
78 return <img alt="" />;
79 },
80}));
81vi.mock("expo/fetch", () => ({ fetch: vi.fn() }));
82vi.mock("react-native-svg", () => ({ parse: vi.fn(), SvgAst: () => null }));
83vi.mock("@t3tools/client-runtime/state/assets", () => ({ MISSING_FILE_ACCESS_MESSAGE: "" }));
84vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null }));
85vi.mock("../../components/ui/AppText", () => ({
86 AppText: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
87}));
88vi.mock("../../components/MediaActionsMenu", () => ({ MediaActionsMenu: harness.Passthrough }));
89vi.mock("../../components/ui/NativePresentation", () => ({
90 PresentationSource: harness.Passthrough,
91}));
92vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) }));
93vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() }));
94
95import { RegistryContext } from "@effect/atom-react";
96import { EnvironmentId, ThreadId } from "@t3tools/contracts";
97import { AtomRegistry } from "effect/reactivity";
98import { fetch } from "expo/fetch";
99import { parse } from "react-native-svg";
100
101import { FilePreviewGallery } from "../../components/ui/FilePreviewGallery";
102import type { FilePreviewSource } from "../../components/ui/FilePreviewModal.types";
103import { useAssetUrlState } from "../../state/assets";
104import {
105 MarkdownImageAvailableWidthContext,
106 ThreadMarkdownImage,
107 ThreadMarkdownImageView,
108} from "./ThreadMarkdownImage";
109
110it("keeps the tapped workspace image fragment on its gallery page", async () => {
111 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
112 const root = createRoot(document.createElement("div"));
113 const environmentId = EnvironmentId.make("environment-1");
114 const threadId = ThreadId.make("thread-1");
115 const resource = { _tag: "media-file", threadId, path: "/repo/./red.png" } as const;
116 const red = { kind: "image", environmentId, resource, srcFragment: "#detail" } as const;
117 const blue = {
118 kind: "image",
119 environmentId,
120 resource: { ...resource, path: "/repo/./blue.png" },
121 } as const;
122 const openPreview = vi.fn<(source: FilePreviewSource) => void>();
123 vi.mocked(useAssetUrlState).mockReturnValueOnce({
124 _tag: "Success",
125 url: "https://example.test/red.png",
126 expiresAt: 0,
127 });
128 try {
129 await act(async () =>
130 root.render(
131 <FilePreviewGallery value={[red, blue]}>
132 <ThreadMarkdownImage
133 environmentId={environmentId}
134 resource={resource}
135 srcFragment="#detail"
136 alt="Red"
137 onPressPreview={openPreview}
138 />
139 </FilePreviewGallery>,
140 ),
141 );
142 await act(async () => harness.pressable.onPress?.({ nativeEvent: {} }));
143 expect(openPreview).toHaveBeenCalledWith(
144 expect.objectContaining({
145 resource,
146 srcFragment: "#detail",
147 gallery: [expect.objectContaining(red), blue],
148 }),
149 );
150 } finally {
151 await act(async () => root.unmount());
152 }
153});
154
155it("keeps the frame size when the same image reports a different decoded width", async () => {
156 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
157 const container = document.createElement("div");
158 const root = createRoot(container);
159 const frameSize = () =>
160 [...container.querySelectorAll<HTMLElement>("div[data-style]")]
161 .map((element) => JSON.parse(element.dataset.style ?? "null") as Record<string, unknown>)
162 .find((style) => typeof style?.width === "number");
163 try {
164 await act(async () =>
165 root.render(
166 <MarkdownImageAvailableWidthContext value={345}>
167 <ThreadMarkdownImageView
168 uri="https://example.test/hero.png"
169 sourceKey="workspace:hero.png"
170 unavailable={false}
171 alt={null}
172 knownSize={{ width: 1000, height: 585 }}
173 onPressPreview={() => {}}
174 />
175 </MarkdownImageAvailableWidthContext>,
176 ),
177 );
178 // Android reports the bitmap downsampled for the current frame, so the same file
179 // alternates between widths (969 and 970 of 1000) as the frame changes size.
180 await act(async () => harness.loadImage({ source: { width: 970, height: 567 } }));
181 const first = frameSize();
182 expect(first).toBeDefined();
183
184 await act(async () => harness.loadImage({ source: { width: 969, height: 567 } }));
185 expect(frameSize()).toEqual(first);
186 } finally {
187 await act(async () => root.unmount());
188 }
189});
190
191it("retries a failed image once its URI comes back through null", async () => {
192 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
193 const container = document.createElement("div");
194 const root = createRoot(container);
195 const view = (uri: string | null) => (
196 <ThreadMarkdownImageView
197 uri={uri}
198 sourceKey="attachment:a"
199 unavailable={false}
200 alt={null}
201 onPressPreview={() => {}}
202 />
203 );
204 try {
205 await act(async () => root.render(view("https://example.test/a.png")));
206 await act(async () => harness.failImage());
207 expect(container.textContent).toContain("Image unavailable");
208
209 await act(async () => root.render(view(null)));
210 await act(async () => root.render(view("https://example.test/a.png")));
211 expect(container.textContent).not.toContain("Image unavailable");
212 expect(container.querySelector("img")).not.toBeNull();
213 } finally {
214 await act(async () => root.unmount());
215 }
216});
217
218it("fetches a failed SVG again on the next mount but keeps a parsed one", async () => {
219 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
220 // Microtask scheduling lets act() flush an unmounted atom's removal before the next render.
221 const registry = AtomRegistry.make({
222 scheduleTask: (task) => {
223 queueMicrotask(task);
224 return () => {};
225 },
226 });
227 const fetchSvg = vi.mocked(fetch);
228 vi.mocked(parse).mockReturnValue({ props: {} } as ReturnType<typeof parse>);
229 const container = document.createElement("div");
230 const root = createRoot(container);
231 const uri = "https://example.test/a.svg";
232 const view = (mounted: boolean) => (
233 <RegistryContext.Provider value={registry}>
234 {mounted ? (
235 <ThreadMarkdownImageView
236 uri={uri}
237 sourceKey="attachment:svg"
238 unavailable={false}
239 alt={null}
240 format="svg"
241 onPressPreview={() => {}}
242 />
243 ) : null}
244 </RegistryContext.Provider>
245 );
246 try {
247 fetchSvg.mockRejectedValueOnce(new Error("offline"));
248 await act(async () => root.render(view(true)));
249 await vi.waitFor(() => expect(container.textContent).toContain("Image unavailable"));
250
251 await act(async () => root.render(view(false)));
252 fetchSvg.mockResolvedValue({ ok: true, status: 200, text: async () => "<svg />" } as never);
253 await act(async () => root.render(view(true)));
254 await vi.waitFor(() => expect(container.textContent).not.toContain("Image unavailable"));
255 expect(fetchSvg).toHaveBeenCalledTimes(2);
256
257 await act(async () => root.render(view(false)));
258 await act(async () => root.render(view(true)));
259 expect(container.textContent).not.toContain("Image unavailable");
260 expect(fetchSvg).toHaveBeenCalledTimes(2);
261 } finally {
262 await act(async () => root.unmount());
263 registry.dispose();
264 }
265});
266
267it("does not parse an obsolete SVG response after its last reader unmounts", async () => {
268 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
269 const registry = AtomRegistry.make({
270 scheduleTask: (task) => {
271 queueMicrotask(task);
272 return () => {};
273 },
274 });
275 const root = createRoot(document.createElement("div"));
276 const fetchSvg = vi.mocked(fetch);
277 const parseSvg = vi.mocked(parse);
278 fetchSvg.mockReset();
279 parseSvg.mockClear();
280 const body = Promise.withResolvers<string>();
281 fetchSvg.mockResolvedValue({ ok: true, status: 200, text: () => body.promise } as never);
282 try {
283 await act(async () =>
284 root.render(
285 <RegistryContext.Provider value={registry}>
286 <ThreadMarkdownImageView
287 uri="https://example.test/obsolete.svg"
288 sourceKey="attachment:obsolete"
289 unavailable={false}
290 alt={null}
291 format="svg"
292 onPressPreview={() => {}}
293 />
294 </RegistryContext.Provider>,
295 ),
296 );
297 expect(fetchSvg).toHaveBeenCalledOnce();
298 const signal = fetchSvg.mock.calls[0]![1]!.signal!;
299 await act(async () => root.render(null));
300 expect(signal.aborted).toBe(true);
301 await act(async () => body.resolve("<svg />"));
302 expect(parseSvg).not.toHaveBeenCalled();
303 } finally {
304 await act(async () => root.unmount());
305 registry.dispose();
306 }
307});
308
309const zoom = () => {
310 const [{ translateX }, { translateY }, { scale }] = harness.contentStyle().transform!;
311 // Clamping at fit can yield -0, which is the same position.
312 return { scale, x: translateX + 0, y: translateY + 0 };
313};
314const pinch = (phase: "onStart" | "onUpdate", focalX: number, focalY: number, scale: number) =>
315 act(async () => harness.gestures.pinch![phase]!({ focalX, focalY, scale, numberOfPointers: 2 }));
316const endPinch = () => act(async () => harness.gestures.pinch!.onFinalize!({}));
317const layout = (width: number, height: number) =>
318 act(async () => harness.pressable.onLayout?.({ nativeEvent: { layout: { width, height } } }));
319const markdownImage = (sourceKey: string, onPressPreview: () => void = () => {}) => (
320 <MarkdownImageAvailableWidthContext value={345}>
321 <ThreadMarkdownImageView
322 uri={`https://example.test/${sourceKey}.png`}
323 sourceKey={sourceKey}
324 unavailable={false}
325 alt={null}
326 knownSize={{ width: 1000, height: 585 }}
327 onPressPreview={onPressPreview}
328 />
329 </MarkdownImageAvailableWidthContext>
330);
331
332it("does not open the preview when a touch on the inline image pinches or pans it", async () => {
333 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
334 const root = createRoot(document.createElement("div"));
335 const onPressPreview = vi.fn();
336 const touch = (fingers: number) =>
337 act(async () =>
338 harness.pressable.onTouchStart?.({
339 nativeEvent: { touches: Array.from({ length: fingers }, () => ({})) },
340 }),
341 );
342 const release = () =>
343 act(async () => harness.pressable.onPress?.({ nativeEvent: { identifier: 1 } }));
344 try {
345 await act(async () => root.render(markdownImage("hero", onPressPreview)));
346 await touch(1);
347 await touch(2);
348 await release();
349 expect(onPressPreview).not.toHaveBeenCalled();
350
351 await touch(1);
352 await act(async () => harness.gestures.pan!.onStart!({ translationX: 5, translationY: 0 }));
353 await release();
354 expect(onPressPreview).not.toHaveBeenCalled();
355
356 await touch(1);
357 await release();
358 expect(onPressPreview).toHaveBeenCalledOnce();
359
360 // VoiceOver activation has no touch, so an earlier pinch must not swallow it.
361 await touch(2);
362 await act(async () => harness.pressable.onPress?.({ nativeEvent: {} }));
363 expect(onPressPreview).toHaveBeenCalledTimes(2);
364 } finally {
365 await act(async () => root.unmount());
366 }
367});
368
369it("zooms the inline image around the pinch and keeps it until the source or frame changes", async () => {
370 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
371 const root = createRoot(document.createElement("div"));
372 const touchPan = () => {
373 const manager = { fail: vi.fn() };
374 harness.gestures.pan!.onTouchesDown!({}, manager);
375 return manager;
376 };
377 try {
378 await act(async () => root.render(markdownImage("a")));
379 // The frame center is (172.5, 101); the pinch is off center.
380 await layout(345, 202);
381 await pinch("onStart", 300, 150, 1);
382 await pinch("onUpdate", 300, 150, 2);
383 expect(zoom()).toEqual({ scale: 2, x: -127.5, y: -49 });
384 await pinch("onUpdate", 280, 140, 2);
385 expect(zoom()).toEqual({ scale: 2, x: -147.5, y: -59 });
386 await act(async () =>
387 harness.gestures.pinch!.onUpdate!({ focalX: 90, focalY: 90, scale: 2, numberOfPointers: 1 }),
388 );
389 expect(zoom()).toEqual({ scale: 2, x: -147.5, y: -59 });
390 await endPinch();
391
392 await act(async () => harness.loadImage({ source: { width: 1000, height: 585 } }));
393 await act(async () => root.render(markdownImage("a")));
394 await layout(345, 202);
395 expect(zoom()).toEqual({ scale: 2, x: -147.5, y: -59 });
396
397 await pinch("onStart", 100, 50, 1);
398 await pinch("onUpdate", 100, 50, 1.5);
399 expect(zoom()).toEqual({ scale: 3, x: -185, y: -63 });
400 await pinch("onUpdate", 100, 50, 10);
401 expect(zoom().scale).toBe(6);
402 await endPinch();
403
404 const zoomedPan = touchPan();
405 await act(async () => harness.gestures.pan!.onStart!({ translationX: 5, translationY: 0 }));
406 await act(async () =>
407 harness.gestures.pan!.onUpdate!({ translationX: 5000, translationY: -5000 }),
408 );
409 expect(zoomedPan.fail).not.toHaveBeenCalled();
410 expect(zoom()).toEqual({ scale: 6, x: 862.5, y: -505 });
411
412 await pinch("onStart", 172, 100, 1);
413 await pinch("onUpdate", 172, 100, 0.01);
414 await endPinch();
415 expect(zoom()).toEqual({ scale: 1, x: 0, y: 0 });
416 expect(touchPan().fail).toHaveBeenCalledOnce();
417
418 await pinch("onStart", 300, 150, 1);
419 await pinch("onUpdate", 300, 150, 2);
420 await endPinch();
421 await layout(300, 175);
422 expect(zoom()).toEqual({ scale: 1, x: 0, y: 0 });
423
424 await pinch("onStart", 300, 150, 1);
425 await pinch("onUpdate", 300, 150, 2);
426 await endPinch();
427 await act(async () => root.render(markdownImage("b")));
428 expect(zoom()).toEqual({ scale: 1, x: 0, y: 0 });
429
430 for (const panFirst of [true, false]) {
431 await act(async () => root.render(markdownImage(`handoff-${panFirst}`)));
432 await layout(300, 200);
433 await pinch("onStart", 150, 100, 1);
434 await pinch("onUpdate", 150, 100, 2);
435 await endPinch();
436 await act(async () => harness.gestures.pan!.onStart!({ translationX: 0, translationY: 0 }));
437 await pinch("onStart", 150, 100, 1);
438 const panUpdate = () =>
439 act(async () => harness.gestures.pan!.onUpdate!({ translationX: 10, translationY: 0 }));
440 if (panFirst) await panUpdate();
441 await pinch("onUpdate", 150, 100, 1.5);
442 if (!panFirst) await panUpdate();
443 await endPinch();
444 await act(async () => harness.gestures.pan!.onUpdate!({ translationX: 20, translationY: 0 }));
445 expect(zoom()).toEqual({ scale: 3, x: 10, y: 0 });
446 }
447 } finally {
448 await act(async () => root.unmount());
449 }
450});