Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadMarkdownImage.test.tsx

163 lines6.3 KB

1import type { ReactNode } from "react";
2import { act } from "react";
3import { createRoot } from "react-dom/client";
4import { expect, it, vi } from "vite-plus/test";
5​
6const harness = vi.hoisted(() => ({
7 failImage: () => {},
8 loadImage: (_event: { source: { width: number; height: number } }) => {},
9 Passthrough: ({ children }: { children?: unknown }) => children,
10}));
11​
12vi.mock("react-native", () => ({
13 Pressable: harness.Passthrough,
14 StyleSheet: { absoluteFill: {} },
15 View: ({ children, style }: { children?: ReactNode; style?: unknown }) => (
16 <div data-style={JSON.stringify(style)}>{children}</div>
17 ),
18}));
19vi.mock("expo-image", () => ({
20 Image: (props: {
21 onError: () => void;
22 onLoad: (event: { source: { width: number; height: number } }) => void;
23 }) => {
24 harness.failImage = props.onError;
25 harness.loadImage = props.onLoad;
26 return <img alt="" />;
27 },
28}));
29vi.mock("expo/fetch", () => ({ fetch: vi.fn() }));
30vi.mock("react-native-svg", () => ({ parse: vi.fn(), SvgAst: () => null }));
31vi.mock("@t3tools/client-runtime/state/assets", () => ({ MISSING_FILE_ACCESS_MESSAGE: "" }));
32vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null }));
33vi.mock("../../components/FilePreviewGallery", () => ({
34 useFilePreviewGallery: () => (source: unknown) => source,
35}));
36vi.mock("../../components/ui/AppText", () => ({
37 AppText: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
38}));
39vi.mock("../../components/MediaActionsMenu", () => ({ MediaActionsMenu: harness.Passthrough }));
40vi.mock("../../components/ui/NativePresentation", () => ({
41 PresentationSource: harness.Passthrough,
42}));
43vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) }));
44vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() }));
45​
46import { RegistryContext } from "@effect/atom-react";
47import { AtomRegistry } from "effect/reactivity";
48import { fetch } from "expo/fetch";
49import { parse } from "react-native-svg";
50​
51import { MarkdownImageAvailableWidthContext, ThreadMarkdownImageView } from "./ThreadMarkdownImage";
52​
53it("keeps the frame size when the same image reports a different decoded width", async () => {
54 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
55 const container = document.createElement("div");
56 const root = createRoot(container);
57 const frameSize = () =>
58 [...container.querySelectorAll<HTMLElement>("div[data-style]")]
59 .map((element) => JSON.parse(element.dataset.style ?? "null") as Record<string, unknown>)
60 .find((style) => typeof style?.width === "number");
61 try {
62 await act(async () =>
63 root.render(
64 <MarkdownImageAvailableWidthContext value={345}>
65 <ThreadMarkdownImageView
66 uri="https://example.test/hero.png"
67 sourceKey="workspace:hero.png"
68 unavailable={false}
69 alt={null}
70 knownSize={{ width: 1000, height: 585 }}
71 onPressPreview={() => {}}
72 />
73 </MarkdownImageAvailableWidthContext>,
74 ),
75 );
76 // Android reports the bitmap downsampled for the current frame, so the same file
77 // alternates between widths (969 and 970 of 1000) as the frame changes size.
78 await act(async () => harness.loadImage({ source: { width: 970, height: 567 } }));
79 const first = frameSize();
80 expect(first).toBeDefined();
81​
82 await act(async () => harness.loadImage({ source: { width: 969, height: 567 } }));
83 expect(frameSize()).toEqual(first);
84 } finally {
85 await act(async () => root.unmount());
86 }
87});
88​
89it("retries a failed image once its URI comes back through null", async () => {
90 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
91 const container = document.createElement("div");
92 const root = createRoot(container);
93 const view = (uri: string | null) => (
94 <ThreadMarkdownImageView
95 uri={uri}
96 sourceKey="attachment:a"
97 unavailable={false}
98 alt={null}
99 onPressPreview={() => {}}
100 />
101 );
102 try {
103 await act(async () => root.render(view("https://example.test/a.png")));
104 await act(async () => harness.failImage());
105 expect(container.textContent).toContain("Image unavailable");
106​
107 await act(async () => root.render(view(null)));
108 await act(async () => root.render(view("https://example.test/a.png")));
109 expect(container.textContent).not.toContain("Image unavailable");
110 expect(container.querySelector("img")).not.toBeNull();
111 } finally {
112 await act(async () => root.unmount());
113 }
114});
115​
116it("fetches a failed SVG again on the next mount but keeps a parsed one", async () => {
117 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
118 // Microtask scheduling lets act() flush an unmounted atom's removal before the next render.
119 const registry = AtomRegistry.make({
120 scheduleTask: (task) => {
121 queueMicrotask(task);
122 return () => {};
123 },
124 });
125 const fetchSvg = vi.mocked(fetch);
126 vi.mocked(parse).mockReturnValue({ props: {} } as ReturnType<typeof parse>);
127 const container = document.createElement("div");
128 const root = createRoot(container);
129 const uri = "https://example.test/a.svg";
130 const view = (mounted: boolean) => (
131 <RegistryContext.Provider value={registry}>
132 {mounted ? (
133 <ThreadMarkdownImageView
134 uri={uri}
135 sourceKey="attachment:svg"
136 unavailable={false}
137 alt={null}
138 format="svg"
139 onPressPreview={() => {}}
140 />
141 ) : null}
142 </RegistryContext.Provider>
143 );
144 try {
145 fetchSvg.mockRejectedValueOnce(new Error("offline"));
146 await act(async () => root.render(view(true)));
147 await vi.waitFor(() => expect(container.textContent).toContain("Image unavailable"));
148​
149 await act(async () => root.render(view(false)));
150 fetchSvg.mockResolvedValue({ ok: true, status: 200, text: async () => "<svg />" } as never);
151 await act(async () => root.render(view(true)));
152 await vi.waitFor(() => expect(container.textContent).not.toContain("Image unavailable"));
153 expect(fetchSvg).toHaveBeenCalledTimes(2);
154​
155 await act(async () => root.render(view(false)));
156 await act(async () => root.render(view(true)));
157 expect(container.textContent).not.toContain("Image unavailable");
158 expect(fetchSvg).toHaveBeenCalledTimes(2);
159 } finally {
160 await act(async () => root.unmount());
161 registry.dispose();
162 }
163});