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