Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
3import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
4import * as Data from "effect/Data";
5import * as Effect from "effect/Effect";
6import { AsyncResult, Atom } from "effect/reactivity";
7import { Image } from "expo-image";
8import { createContext, useContext, useId, useState } from "react";
9import { fetch } from "expo/fetch";
10import { parse, SvgAst, type JsxAST } from "react-native-svg";
11import { Pressable, StyleSheet, View, type ViewStyle } from "react-native";
12
13import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
14import { useFilePreviewGallery } from "../../components/FilePreviewGallery";
15import { AppText as Text } from "../../components/ui/AppText";
16import type { FilePreviewSource } from "../../components/FilePreviewModal";
17import { MediaActionsMenu } from "../../components/MediaActionsMenu";
18import { PresentationSource } from "../../components/ui/NativePresentation";
19import { useMediaActions } from "../../state/mediaActions";
20import type { MediaActionsSource } from "../../lib/mediaActionsSource";
21import { useAssetUrlState } from "../../state/assets";
22import { assetImageCacheKey } from "../../lib/assetImageSource";
23import {
24 MARKDOWN_IMAGE_MAX_WIDTH,
25 type MarkdownImageDisplaySize,
26 resolveMarkdownImageDisplaySize,
27 resolveSvgImageSize,
28} from "./markdownImageSize";
29
30/** Use known feed width immediately; later image measurement would move already-positioned rows. */
31export const MarkdownImageAvailableWidthContext = createContext(0);
32
33type ImageSize = { readonly width: number; readonly height: number };
34
35class SvgLoadError extends Data.TaggedError("SvgLoadError")<{ readonly cause: unknown }> {}
36
37async function readSvgXml(uri: string, signal: AbortSignal): Promise<string> {
38 if (uri.startsWith("data:image/svg+xml")) {
39 const comma = uri.indexOf(",");
40 if (comma < 0) throw new Error("SVG data URI has no content");
41 const content = decodeURIComponent(uri.slice(comma + 1));
42 return uri.slice(0, comma).includes(";base64")
43 ? new TextDecoder().decode(
44 Uint8Array.from(atob(content), (character) => character.charCodeAt(0)),
45 )
46 : content;
47 }
48 // expo/fetch, not the runtime HttpClient: it is the one that reads file:// URIs.
49 const response = await fetch(uri, { signal });
50 if (!response.ok && !(response.status === 0 && uri.startsWith("file://")))
51 throw new Error(`SVG request failed: ${response.status}`);
52 return response.text();
53}
54
55type SvgDocument = { readonly ast: JsxAST; readonly size: ImageSize | null };
56
57// Feed rows unmount as they scroll away. Only parsed documents outlive their
58// readers (for the row that scrolls back); a failed load is dropped with its last
59// reader so the next mount fetches again.
60const parsedSvgDocumentAtom = Atom.family((_uri: string) =>
61 Atom.make<SvgDocument | null>(null).pipe(
62 Atom.setIdleTTL(60_000),
63 Atom.withLabel("mobile:thread-markdown-svg-parsed"),
64 ),
65);
66
67const svgDocumentAtom = Atom.family((uri: string) =>
68 Atom.make((get) => {
69 const parsed = parsedSvgDocumentAtom(uri);
70 const cached = get(parsed);
71 if (cached !== null) return Effect.succeed(cached);
72 return Effect.tryPromise({
73 try: async (signal): Promise<SvgDocument> => {
74 const ast = parse(await readSvgXml(uri, signal));
75 if (!ast) throw new Error("SVG has no root element");
76 return { ast, size: resolveSvgImageSize(ast.props) };
77 },
78 catch: (cause) => new SvgLoadError({ cause }),
79 }).pipe(Effect.tap((document) => Effect.sync(() => get.set(parsed, document))));
80 }).pipe(Atom.withLabel("mobile:thread-markdown-svg")),
81);
82
83const noSvgDocumentAtom = Atom.make(AsyncResult.initial<SvgDocument, SvgLoadError>());
84
85export function ThreadMarkdownImageView(props: {
86 readonly uri: string | null;
87 readonly sourceKey: string;
88 readonly cacheKey?: string | undefined;
89 readonly unavailable: boolean;
90 readonly unavailableDetail?: string | undefined;
91 readonly alt: string | null;
92 readonly knownSize?: { readonly width: number; readonly height: number } | undefined;
93 readonly format?: "svg";
94 readonly actionsSource?: MediaActionsSource;
95 readonly onPressPreview: (source: FilePreviewSource) => void;
96}) {
97 const withGallery = useFilePreviewGallery();
98 const sourceIdentifier = useId();
99 const mediaActions = useMediaActions(props.actionsSource);
100 const contextWidth = useContext(MarkdownImageAvailableWidthContext);
101 const [measuredWidth, setMeasuredWidth] = useState(0);
102 const availableWidth =
103 measuredWidth > 0 && contextWidth > 0
104 ? Math.min(contextWidth, measuredWidth)
105 : contextWidth || measuredWidth;
106 const svg = useAtomValue(
107 props.format === "svg" && props.uri !== null ? svgDocumentAtom(props.uri) : noSvgDocumentAtom,
108 );
109 const svgDocument = AsyncResult.isSuccess(svg) ? svg.value : null;
110 // Keyed by source so a new source drops the previous image's decoded dimensions.
111 const [decoded, setDecoded] = useState<{ sourceKey: string; size: ImageSize } | null>(null);
112 const decodedSize =
113 svgDocument?.size ?? (decoded?.sourceKey === props.sourceKey ? decoded.size : null);
114 // A failure belongs to one URI; any URI change, including through null, retries.
115 const [failure, setFailure] = useState({ uri: props.uri, failed: false });
116 if (failure.uri !== props.uri) setFailure({ uri: props.uri, failed: false });
117
118 const sourceSize = decodedSize ?? props.knownSize ?? null;
119 const displaySize: MarkdownImageDisplaySize | null =
120 sourceSize === null || availableWidth <= 0
121 ? null
122 : resolveMarkdownImageDisplaySize({
123 sourceWidth: sourceSize.width,
124 sourceHeight: sourceSize.height,
125 availableWidth,
126 });
127 const failed =
128 props.unavailable ||
129 (props.uri !== null && failure.uri === props.uri && failure.failed) ||
130 AsyncResult.isFailure(svg);
131 const placeholderWidth: ViewStyle["width"] =
132 availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
133 const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
134
135 return (
136 <View
137 onLayout={(event) => setMeasuredWidth(event.nativeEvent.layout.width)}
138 style={{ alignSelf: "stretch", gap: 6 }}
139 >
140 {props.uri === null || failed ? (
141 <MediaActionsMenu media={mediaActions}>
142 <Pressable
143 accessibilityRole="imagebutton"
144 accessibilityLabel={props.alt ?? "Markdown image"}
145 accessibilityHint={
146 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
147 }
148 className="items-center justify-center rounded-[10px] bg-md-code-bg"
149 style={frameStyle}
150 >
151 {failed ? (
152 <Text className="px-3 text-center text-xs text-foreground-muted">
153 {props.unavailableDetail
154 ? `Image unavailable. ${props.unavailableDetail}`
155 : "Image unavailable"}
156 </Text>
157 ) : (
158 <AppActivityIndicator />
159 )}
160 </Pressable>
161 </MediaActionsMenu>
162 ) : (
163 <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>
164 <MediaActionsMenu media={mediaActions}>
165 <Pressable
166 accessibilityRole="imagebutton"
167 accessibilityLabel={props.alt ?? "Markdown image"}
168 accessibilityHint={
169 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
170 }
171 onPress={() =>
172 props.onPressPreview(
173 withGallery({
174 kind: "image",
175 uri: props.uri!,
176 name: props.actionsSource?.name ?? props.alt ?? "Image",
177 sourceIdentifier,
178 actionsSource: props.actionsSource,
179 }),
180 )
181 }
182 style={{ alignSelf: "flex-start" }}
183 >
184 <View
185 className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
186 style={frameStyle}
187 >
188 {props.format === "svg" ? (
189 <ThreadMarkdownSvg ast={svgDocument?.ast ?? null} />
190 ) : (
191 <ThreadMarkdownImageRequest
192 key={props.sourceKey}
193 uri={props.uri}
194 cacheKey={props.cacheKey}
195 onLoad={(size) =>
196 // Only the first decode counts: later loads report the bitmap
197 // downsampled for the current frame (969 vs 970 wide), so keeping
198 // them resizes the frame, which reloads the image, and so on.
199 setDecoded((current) =>
200 current?.sourceKey === props.sourceKey
201 ? current
202 : { sourceKey: props.sourceKey, size },
203 )
204 }
205 onError={() => setFailure({ uri: props.uri, failed: true })}
206 />
207 )}
208 </View>
209 </Pressable>
210 </MediaActionsMenu>
211 </PresentationSource>
212 )}
213 {props.alt ? (
214 <Text selectable className="text-xs text-foreground-muted">
215 {props.alt}
216 </Text>
217 ) : null}
218 </View>
219 );
220}
221
222function ThreadMarkdownImageRequest(props: {
223 readonly uri: string;
224 readonly cacheKey: string | undefined;
225 readonly onLoad: (sourceSize: ImageSize) => void;
226 readonly onError: () => void;
227}) {
228 const [loaded, setLoaded] = useState(false);
229
230 return (
231 <>
232 <Image
233 source={{ uri: props.uri, cacheKey: props.cacheKey }}
234 contentFit="contain"
235 cachePolicy="memory-disk"
236 accessible={false}
237 onLoad={(event) => {
238 setLoaded(true);
239 props.onLoad(event.source);
240 }}
241 onError={props.onError}
242 style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}
243 />
244 {loaded ? null : <ThreadMarkdownImageLoading />}
245 </>
246 );
247}
248
249function ThreadMarkdownImageLoading() {
250 return (
251 <View
252 pointerEvents="none"
253 style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}
254 >
255 <Text className="text-xs text-foreground-muted">Loading image…</Text>
256 </View>
257 );
258}
259
260function ThreadMarkdownSvg(props: { readonly ast: JsxAST | null }) {
261 return props.ast === null ? (
262 <ThreadMarkdownImageLoading />
263 ) : (
264 <SvgAst ast={props.ast} override={{ width: "100%", height: "100%", accessible: false }} />
265 );
266}
267
268export function ThreadMarkdownImage(props: {
269 readonly environmentId: EnvironmentId;
270 readonly resource: Extract<
271 AssetResource,
272 { readonly _tag: "attachment" | "media-file" | "draft-workspace-file" | "tool-output-image" }
273 >;
274 readonly alt: string | null;
275 readonly srcFragment?: string;
276 readonly actionsSource?: MediaActionsSource;
277 readonly onPressPreview: (source: FilePreviewSource) => void;
278}) {
279 const withGallery = useFilePreviewGallery();
280 const assetUrl = useAssetUrlState(props.environmentId, props.resource);
281 const resourceKey =
282 props.resource._tag === "attachment"
283 ? `attachment:${props.resource.attachmentId}`
284 : props.resource._tag === "tool-output-image"
285 ? `tool-output:${props.resource.itemId}:${props.resource.index}`
286 : `workspace:${props.resource.path}`;
287 // The view keeps the first decoded size per key, so a file edited in place needs a
288 // new key; a re-signed URL for the same revision must not get one.
289 const sourceKey =
290 assetUrl._tag === "Success" && assetUrl.fileRevision !== undefined
291 ? `${resourceKey}@${assetUrl.fileRevision}`
292 : resourceKey;
293
294 return (
295 <ThreadMarkdownImageView
296 uri={assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null}
297 cacheKey={
298 assetUrl._tag === "Success"
299 ? assetImageCacheKey(props.environmentId, props.resource, assetUrl.fileRevision)
300 : undefined
301 }
302 sourceKey={sourceKey}
303 unavailable={assetUrl._tag === "Failure"}
304 unavailableDetail={
305 assetUrl._tag === "Failure" && assetUrl.reason === "missing-file-access"
306 ? MISSING_FILE_ACCESS_MESSAGE
307 : undefined
308 }
309 knownSize={assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined}
310 format={
311 (props.resource._tag === "media-file" || props.resource._tag === "draft-workspace-file") &&
312 /\.svg$/i.test(props.resource.path)
313 ? "svg"
314 : undefined
315 }
316 alt={props.alt}
317 actionsSource={props.actionsSource}
318 onPressPreview={(source) => {
319 const { uri: _uri, ...rest } = source as FilePreviewSource & { uri?: string };
320 props.onPressPreview(
321 withGallery({
322 ...rest,
323 gallery: undefined,
324 environmentId: props.environmentId,
325 resource: props.resource,
326 }),
327 );
328 }}
329 />
330 );
331}
332
333export function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {
334 return (
335 <ThreadMarkdownImageView
336 uri={null}
337 sourceKey="unavailable"
338 unavailable
339 alt={props.alt}
340 onPressPreview={() => undefined}
341 />
342 );
343}