Open History to see the last commit
1import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
2import { Image } from "expo-image";
3import { createContext, useContext, useEffect, useEffectEvent, useId, useState } from "react";
4import { fetch } from "expo/fetch";
5import { parse, SvgAst, type JsxAST } from "react-native-svg";
6import { ActivityIndicator, Pressable, StyleSheet, View, type ViewStyle } from "react-native";
7
8import { AppActivityIndicator } from "../../components/AppActivityIndicator";
9import { useFilePreviewGallery } from "../../components/FilePreviewGallery";
10import { AppText as Text } from "../../components/AppText";
11import type { FilePreviewSource } from "../../components/FilePreviewModal";
12import { MediaActionsMenu } from "../../components/MediaActionsMenu";
13import { PresentationSource } from "../../components/NativePresentation";
14import { useMediaActions } from "../../state/mediaActions";
15import type { MediaActionsSource } from "../../lib/mediaActionsSource";
16import { useAssetUrlState } from "../../state/assets";
17import {
18 MARKDOWN_IMAGE_MAX_WIDTH,
19 type MarkdownImageDisplaySize,
20 resolveMarkdownImageDisplaySize,
21 resolveSvgImageSize,
22} from "./markdownImageSize";
23
24/**
25 * Width the feed lays markdown out in. The feed already knows this from its
26 * viewport, so an image can size its frame on the first render instead of
27 * waiting for its own onLayout, which would change the row's height once
28 * more after the list has positioned the rows below it. It is an upper
29 * bound: a list item or blockquote indents its column, and the measured
30 * width takes over once it is known.
31 */
32export const MarkdownImageAvailableWidthContext = createContext(0);
33
34export function ThreadMarkdownImageView(props: {
35 readonly uri: string | null;
36 readonly sourceKey: string;
37 readonly unavailable: boolean;
38 readonly alt: string | null;
39 /** Pixel size from the server, when it could read the header; the frame is final from the first render. */
40 readonly knownSize?: { readonly width: number; readonly height: number } | undefined;
41 readonly format?: "svg";
42 readonly actionsSource?: MediaActionsSource;
43 readonly onPressPreview: (source: FilePreviewSource) => void;
44}) {
45 const withGallery = useFilePreviewGallery();
46 const sourceIdentifier = useId();
47 const mediaActions = useMediaActions(props.actionsSource);
48 const contextWidth = useContext(MarkdownImageAvailableWidthContext);
49 const [measuredWidth, setMeasuredWidth] = useState(0);
50 const availableWidth =
51 measuredWidth > 0 && contextWidth > 0
52 ? Math.min(contextWidth, measuredWidth)
53 : contextWidth || measuredWidth;
54 const [decodedSize, setDecodedSize] = useState<{ width: number; height: number } | null>(null);
55 const [failedUri, setFailedUri] = useState<string | null>(null);
56
57 useEffect(() => {
58 setDecodedSize(null);
59 }, [props.sourceKey]);
60
61 useEffect(() => {
62 setFailedUri(null);
63 }, [props.uri]);
64
65 // The decoded size is what the platform actually drew, so it wins over the
66 // server's header hint once it exists.
67 const sourceSize = decodedSize ?? props.knownSize ?? null;
68 const displaySize: MarkdownImageDisplaySize | null =
69 sourceSize === null || availableWidth <= 0
70 ? null
71 : resolveMarkdownImageDisplaySize({
72 sourceWidth: sourceSize.width,
73 sourceHeight: sourceSize.height,
74 availableWidth,
75 });
76 const failed = props.unavailable || (props.uri !== null && failedUri === props.uri);
77 const placeholderWidth: ViewStyle["width"] =
78 availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
79 const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
80
81 return (
82 <View
83 onLayout={(event) => setMeasuredWidth(event.nativeEvent.layout.width)}
84 style={{ alignSelf: "stretch", gap: 6 }}
85 >
86 {props.uri === null || failed ? (
87 <MediaActionsMenu media={mediaActions}>
88 <Pressable
89 accessibilityRole="imagebutton"
90 accessibilityLabel={props.alt ?? "Markdown image"}
91 accessibilityHint={
92 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
93 }
94 className="items-center justify-center rounded-[10px] bg-md-code-bg"
95 style={frameStyle}
96 >
97 {failed ? (
98 <Text className="text-xs text-foreground-muted">Image unavailable</Text>
99 ) : (
100 <AppActivityIndicator />
101 )}
102 </Pressable>
103 </MediaActionsMenu>
104 ) : (
105 <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>
106 <MediaActionsMenu media={mediaActions}>
107 <Pressable
108 accessibilityRole="imagebutton"
109 accessibilityLabel={props.alt ?? "Markdown image"}
110 accessibilityHint={
111 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
112 }
113 onPress={() =>
114 props.onPressPreview(
115 withGallery({
116 kind: "image",
117 uri: props.uri!,
118 name: props.actionsSource?.name ?? props.alt ?? "Image",
119 sourceIdentifier,
120 actionsSource: props.actionsSource,
121 }),
122 )
123 }
124 style={{ alignSelf: "flex-start" }}
125 >
126 <View
127 className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
128 style={frameStyle}
129 >
130 <ThreadMarkdownImageRequest
131 key={props.uri}
132 uri={props.uri}
133 format={props.format}
134 onLoad={setDecodedSize}
135 onError={() => setFailedUri(props.uri)}
136 />
137 </View>
138 </Pressable>
139 </MediaActionsMenu>
140 </PresentationSource>
141 )}
142 {props.alt ? (
143 <Text selectable className="text-xs text-foreground-muted">
144 {props.alt}
145 </Text>
146 ) : null}
147 </View>
148 );
149}
150
151function ThreadMarkdownImageRequest(props: {
152 readonly uri: string;
153 readonly onLoad: (sourceSize: { width: number; height: number }) => void;
154 readonly onError: () => void;
155 readonly format?: "svg";
156}) {
157 const [loaded, setLoaded] = useState(false);
158
159 return (
160 <>
161 {props.format === "svg" ? (
162 <ThreadMarkdownSvg
163 uri={props.uri}
164 onLoad={(size) => {
165 setLoaded(true);
166 if (size) props.onLoad(size);
167 }}
168 onError={props.onError}
169 />
170 ) : (
171 <Image
172 source={{ uri: props.uri }}
173 contentFit="contain"
174 cachePolicy="memory-disk"
175 accessible={false}
176 onLoad={(event) => {
177 setLoaded(true);
178 props.onLoad(event.source);
179 }}
180 onError={props.onError}
181 style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}
182 />
183 )}
184 {loaded ? null : (
185 <View
186 pointerEvents="none"
187 style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}
188 >
189 <Text className="text-xs text-foreground-muted">Loading image…</Text>
190 </View>
191 )}
192 </>
193 );
194}
195
196function ThreadMarkdownSvg(props: {
197 readonly uri: string;
198 readonly onLoad: (size: { width: number; height: number } | null) => void;
199 readonly onError: () => void;
200}) {
201 const [ast, setAst] = useState<JsxAST | null>(null);
202 const onLoad = useEffectEvent(props.onLoad);
203 const onError = useEffectEvent(props.onError);
204 useEffect(() => {
205 const controller = new AbortController();
206 const load = async () => {
207 if (props.uri.startsWith("data:image/svg+xml")) {
208 const comma = props.uri.indexOf(",");
209 if (comma < 0) throw new Error("SVG data URI has no content");
210 const content = decodeURIComponent(props.uri.slice(comma + 1));
211 return props.uri.slice(0, comma).includes(";base64")
212 ? new TextDecoder().decode(
213 Uint8Array.from(atob(content), (character) => character.charCodeAt(0)),
214 )
215 : content;
216 }
217 const response = await fetch(props.uri, { signal: controller.signal });
218 if (!response.ok && !(response.status === 0 && props.uri.startsWith("file://")))
219 throw new Error(`SVG request failed: ${response.status}`);
220 return response.text();
221 };
222 void load()
223 .then((xml) => {
224 const parsed = parse(xml);
225 if (!parsed) throw new Error("SVG has no root element");
226 if (controller.signal.aborted) return;
227 setAst(parsed);
228 onLoad(resolveSvgImageSize(parsed.props));
229 })
230 .catch(() => {
231 if (!controller.signal.aborted) onError();
232 });
233 return () => controller.abort();
234 }, [props.uri]);
235 return <SvgAst ast={ast} override={{ width: "100%", height: "100%", accessible: false }} />;
236}
237
238/** Environment-hosted image that loads through a signed asset URL. */
239export function ThreadMarkdownImage(props: {
240 readonly environmentId: EnvironmentId;
241 readonly resource: Extract<
242 AssetResource,
243 { readonly _tag: "attachment" | "media-file" | "draft-workspace-file" | "tool-output-image" }
244 >;
245 readonly alt: string | null;
246 readonly srcFragment?: string;
247 readonly actionsSource?: MediaActionsSource;
248 readonly onPressPreview: (source: FilePreviewSource) => void;
249}) {
250 const withGallery = useFilePreviewGallery();
251 const assetUrl = useAssetUrlState(props.environmentId, props.resource);
252
253 return (
254 <ThreadMarkdownImageView
255 uri={assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null}
256 sourceKey={
257 props.resource._tag === "attachment"
258 ? `attachment:${props.resource.attachmentId}`
259 : props.resource._tag === "tool-output-image"
260 ? `tool-output:${props.resource.itemId}:${props.resource.index}`
261 : `workspace:${props.resource.path}`
262 }
263 unavailable={assetUrl._tag === "Failure"}
264 knownSize={assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined}
265 format={
266 (props.resource._tag === "media-file" || props.resource._tag === "draft-workspace-file") &&
267 /\.svg$/i.test(props.resource.path)
268 ? "svg"
269 : undefined
270 }
271 alt={props.alt}
272 actionsSource={props.actionsSource}
273 onPressPreview={(source) => {
274 const { uri: _uri, ...rest } = source as FilePreviewSource & { uri?: string };
275 props.onPressPreview(
276 withGallery({
277 ...rest,
278 gallery: undefined,
279 environmentId: props.environmentId,
280 resource: props.resource,
281 }),
282 );
283 }}
284 />
285 );
286}
287
288export function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {
289 return (
290 <ThreadMarkdownImageView
291 uri={null}
292 sourceKey="unavailable"
293 unavailable
294 alt={props.alt}
295 onPressPreview={() => undefined}
296 />
297 );
298}