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/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 { WorkspaceMutationIdContext } from "./workspaceMutationIdContext";
23import { assetImageCacheKey } from "../../lib/assetImageSource";
24import {
25 MARKDOWN_IMAGE_MAX_WIDTH,
26 type MarkdownImageDisplaySize,
27 resolveMarkdownImageDisplaySize,
28 resolveSvgImageSize,
29} from "./markdownImageSize";
30
31/** Use known feed width immediately; later image measurement would move already-positioned rows. */
32export const MarkdownImageAvailableWidthContext = createContext(0);
33
34type ImageSize = { readonly width: number; readonly height: number };
35
36class SvgLoadError extends Schema.TaggedError<SvgLoadError>()("SvgLoadError", {
37 cause: Schema.Defect(),
38}) {}
39
40async function readSvgXml(uri: string, signal: AbortSignal): Promise<string> {
41 if (uri.startsWith("data:image/svg+xml")) {
42 const comma = uri.indexOf(",");
43 if (comma < 0) throw new Error("SVG data URI has no content");
44 const content = decodeURIComponent(uri.slice(comma + 1));
45 return uri.slice(0, comma).includes(";base64")
46 ? new TextDecoder().decode(
47 Uint8Array.from(atob(content), (character) => character.charCodeAt(0)),
48 )
49 : content;
50 }
51 // expo/fetch, not the runtime HttpClient: it is the one that reads file:// URIs.
52 const response = await fetch(uri, { signal });
53 if (!response.ok && !(response.status === 0 && uri.startsWith("file://")))
54 throw new Error(`SVG request failed: ${response.status}`);
55 return response.text();
56}
57
58type SvgDocument = { readonly ast: JsxAST; readonly size: ImageSize | null };
59
60// Feed rows unmount as they scroll away. Only parsed documents outlive their
61// readers (for the row that scrolls back); a failed load is dropped with its last
62// reader so the next mount fetches again.
63const parsedSvgDocumentAtom = Atom.family((_uri: string) =>
64 Atom.make<SvgDocument | null>(null).pipe(
65 Atom.setIdleTTL(60_000),
66 Atom.withLabel("mobile:thread-markdown-svg-parsed"),
67 ),
68);
69
70const svgDocumentAtom = Atom.family((uri: string) =>
71 Atom.make((get) => {
72 const parsed = parsedSvgDocumentAtom(uri);
73 const cached = get(parsed);
74 if (cached !== null) return Effect.succeed(cached);
75 return Effect.tryPromise({
76 try: async (signal): Promise<SvgDocument> => {
77 const xml = await readSvgXml(uri, signal);
78 signal.throwIfAborted();
79 const ast = parse(xml);
80 if (!ast) throw new Error("SVG has no root element");
81 return { ast, size: resolveSvgImageSize(ast.props) };
82 },
83 catch: (cause) => new SvgLoadError({ cause }),
84 }).pipe(Effect.tap((document) => Effect.sync(() => get.set(parsed, document))));
85 }).pipe(Atom.withLabel("mobile:thread-markdown-svg")),
86);
87
88const noSvgDocumentAtom = Atom.make(AsyncResult.initial<SvgDocument, SvgLoadError>());
89
90export function ThreadMarkdownImageView(props: {
91 readonly uri: string | null;
92 readonly sourceKey: string;
93 readonly cacheKey?: string | undefined;
94 readonly unavailable: boolean;
95 readonly unavailableDetail?: string | undefined;
96 readonly alt: string | null;
97 readonly knownSize?: { readonly width: number; readonly height: number } | undefined;
98 readonly format?: "svg";
99 readonly actionsSource?: MediaActionsSource;
100 readonly onPressPreview: (source: FilePreviewSource) => void;
101}) {
102 const withGallery = useFilePreviewGallery();
103 const sourceIdentifier = useId();
104 const mediaActions = useMediaActions(props.actionsSource);
105 const contextWidth = useContext(MarkdownImageAvailableWidthContext);
106 const [measuredWidth, setMeasuredWidth] = useState(0);
107 const availableWidth =
108 measuredWidth > 0 && contextWidth > 0
109 ? Math.min(contextWidth, measuredWidth)
110 : contextWidth || measuredWidth;
111 const svg = useAtomValue(
112 props.format === "svg" && props.uri !== null ? svgDocumentAtom(props.uri) : noSvgDocumentAtom,
113 );
114 const svgDocument = AsyncResult.isSuccess(svg) ? svg.value : null;
115 // Keyed by source so a new source drops the previous image's decoded dimensions.
116 const [decoded, setDecoded] = useState<{ sourceKey: string; size: ImageSize } | null>(null);
117 const decodedSize =
118 svgDocument?.size ?? (decoded?.sourceKey === props.sourceKey ? decoded.size : null);
119 // A failure belongs to one URI; any URI change, including through null, retries.
120 const [failure, setFailure] = useState({ uri: props.uri, failed: false });
121 if (failure.uri !== props.uri) setFailure({ uri: props.uri, failed: false });
122
123 const sourceSize = decodedSize ?? props.knownSize ?? null;
124 const displaySize: MarkdownImageDisplaySize | null =
125 sourceSize === null || availableWidth <= 0
126 ? null
127 : resolveMarkdownImageDisplaySize({
128 sourceWidth: sourceSize.width,
129 sourceHeight: sourceSize.height,
130 availableWidth,
131 });
132 const failed =
133 props.unavailable ||
134 (props.uri !== null && failure.uri === props.uri && failure.failed) ||
135 AsyncResult.isFailure(svg);
136 const placeholderWidth: ViewStyle["width"] =
137 availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
138 const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
139
140 return (
141 <View
142 onLayout={(event) => setMeasuredWidth(event.nativeEvent.layout.width)}
143 style={{ alignSelf: "stretch", gap: 6 }}
144 >
145 {props.uri === null || failed ? (
146 <MediaActionsMenu media={mediaActions}>
147 <Pressable
148 accessibilityRole="imagebutton"
149 accessibilityLabel={props.alt ?? "Markdown image"}
150 accessibilityHint={
151 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
152 }
153 className="items-center justify-center rounded-[10px] bg-md-code-bg"
154 style={frameStyle}
155 >
156 {failed ? (
157 <Text className="px-3 text-center text-xs text-foreground-muted">
158 {props.unavailableDetail
159 ? `Image unavailable. ${props.unavailableDetail}`
160 : "Image unavailable"}
161 </Text>
162 ) : (
163 <AppActivityIndicator />
164 )}
165 </Pressable>
166 </MediaActionsMenu>
167 ) : (
168 <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>
169 <MediaActionsMenu media={mediaActions}>
170 <Pressable
171 accessibilityRole="imagebutton"
172 accessibilityLabel={props.alt ?? "Markdown image"}
173 accessibilityHint={
174 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
175 }
176 onPress={() =>
177 props.onPressPreview(
178 withGallery({
179 kind: "image",
180 uri: props.uri!,
181 name: props.actionsSource?.name ?? props.alt ?? "Image",
182 sourceIdentifier,
183 actionsSource: props.actionsSource,
184 }),
185 )
186 }
187 style={{ alignSelf: "flex-start" }}
188 >
189 <View
190 className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
191 style={frameStyle}
192 >
193 {props.format === "svg" ? (
194 <ThreadMarkdownSvg ast={svgDocument?.ast ?? null} />
195 ) : (
196 <ThreadMarkdownImageRequest
197 key={props.sourceKey}
198 uri={props.uri}
199 cacheKey={props.cacheKey}
200 onLoad={(size) =>
201 // Only the first decode counts: later loads report the bitmap
202 // downsampled for the current frame (969 vs 970 wide), so keeping
203 // them resizes the frame, which reloads the image, and so on.
204 setDecoded((current) =>
205 current?.sourceKey === props.sourceKey
206 ? current
207 : { sourceKey: props.sourceKey, size },
208 )
209 }
210 onError={() => setFailure({ uri: props.uri, failed: true })}
211 />
212 )}
213 </View>
214 </Pressable>
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 unavailable={assetUrl._tag === "Failure"}
314 unavailableDetail={
315 assetUrl._tag === "Failure" && assetUrl.reason === "missing-file-access"
316 ? MISSING_FILE_ACCESS_MESSAGE
317 : undefined
318 }
319 knownSize={assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined}
320 format={
321 (props.resource._tag === "media-file" || props.resource._tag === "draft-workspace-file") &&
322 /\.svg$/i.test(props.resource.path)
323 ? "svg"
324 : undefined
325 }
326 alt={props.alt}
327 actionsSource={props.actionsSource}
328 onPressPreview={(source) => {
329 const { uri: _uri, ...rest } = source as FilePreviewSource & { uri?: string };
330 props.onPressPreview(
331 withGallery({
332 ...rest,
333 gallery: undefined,
334 environmentId: props.environmentId,
335 resource: props.resource,
336 }),
337 );
338 }}
339 />
340 );
341}
342
343export function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {
344 return (
345 <ThreadMarkdownImageView
346 uri={null}
347 sourceKey="unavailable"
348 unavailable
349 alt={props.alt}
350 onPressPreview={() => undefined}
351 />
352 );
353}