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