Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadMarkdownImage.tsx

298 lines10.8 KB

1import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
2import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
3import { Image } from "expo-image";
4import { createContext, useContext, useEffect, useEffectEvent, useId, useState } from "react";
5import { fetch } from "expo/fetch";
6import { parse, SvgAst, type JsxAST } from "react-native-svg";
7import { Pressable, StyleSheet, View, type ViewStyle } from "react-native";
8​
9import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
10import { useFilePreviewGallery } from "../../components/FilePreviewGallery";
11import { AppText as Text } from "../../components/ui/AppText";
12import type { FilePreviewSource } from "../../components/FilePreviewModal";
13import { MediaActionsMenu } from "../../components/MediaActionsMenu";
14import { PresentationSource } from "../../components/ui/NativePresentation";
15import { useMediaActions } from "../../state/mediaActions";
16import type { MediaActionsSource } from "../../lib/mediaActionsSource";
17import { useAssetUrlState } from "../../state/assets";
18import {
19 MARKDOWN_IMAGE_MAX_WIDTH,
20 type MarkdownImageDisplaySize,
21 resolveMarkdownImageDisplaySize,
22 resolveSvgImageSize,
23} from "./markdownImageSize";
24​
25/** Use known feed width immediately; later image measurement would move already-positioned rows. */
26export const MarkdownImageAvailableWidthContext = createContext(0);
27​
28export function ThreadMarkdownImageView(props: {
29 readonly uri: string | null;
30 readonly sourceKey: string;
31 readonly unavailable: boolean;
32 readonly unavailableDetail?: string | undefined;
33 readonly alt: string | null;
34 readonly knownSize?: { readonly width: number; readonly height: number } | undefined;
35 readonly format?: "svg";
36 readonly actionsSource?: MediaActionsSource;
37 readonly onPressPreview: (source: FilePreviewSource) => void;
38}) {
39 const withGallery = useFilePreviewGallery();
40 const sourceIdentifier = useId();
41 const mediaActions = useMediaActions(props.actionsSource);
42 const contextWidth = useContext(MarkdownImageAvailableWidthContext);
43 const [measuredWidth, setMeasuredWidth] = useState(0);
44 const availableWidth =
45 measuredWidth > 0 && contextWidth > 0
46 ? Math.min(contextWidth, measuredWidth)
47 : contextWidth || measuredWidth;
48 const [decodedSize, setDecodedSize] = useState<{ width: number; height: number } | null>(null);
49 const [failedUri, setFailedUri] = useState<string | null>(null);
50​
51 useEffect(() => {
52 setDecodedSize(null);
53 }, [props.sourceKey]);
54​
55 useEffect(() => {
56 setFailedUri(null);
57 }, [props.uri]);
58​
59 const sourceSize = decodedSize ?? props.knownSize ?? null;
60 const displaySize: MarkdownImageDisplaySize | null =
61 sourceSize === null || availableWidth <= 0
62 ? null
63 : resolveMarkdownImageDisplaySize({
64 sourceWidth: sourceSize.width,
65 sourceHeight: sourceSize.height,
66 availableWidth,
67 });
68 const failed = props.unavailable || (props.uri !== null && failedUri === props.uri);
69 const placeholderWidth: ViewStyle["width"] =
70 availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
71 const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
72​
73 return (
74 <View
75 onLayout={(event) => setMeasuredWidth(event.nativeEvent.layout.width)}
76 style={{ alignSelf: "stretch", gap: 6 }}
77 >
78 {props.uri === null || failed ? (
79 <MediaActionsMenu media={mediaActions}>
80 <Pressable
81 accessibilityRole="imagebutton"
82 accessibilityLabel={props.alt ?? "Markdown image"}
83 accessibilityHint={
84 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
85 }
86 className="items-center justify-center rounded-[10px] bg-md-code-bg"
87 style={frameStyle}
88 >
89 {failed ? (
90 <Text className="px-3 text-center text-xs text-foreground-muted">
91 {props.unavailableDetail
92 ? `Image unavailable. ${props.unavailableDetail}`
93 : "Image unavailable"}
94 </Text>
95 ) : (
96 <AppActivityIndicator />
97 )}
98 </Pressable>
99 </MediaActionsMenu>
100 ) : (
101 <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>
102 <MediaActionsMenu media={mediaActions}>
103 <Pressable
104 accessibilityRole="imagebutton"
105 accessibilityLabel={props.alt ?? "Markdown image"}
106 accessibilityHint={
107 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
108 }
109 onPress={() =>
110 props.onPressPreview(
111 withGallery({
112 kind: "image",
113 uri: props.uri!,
114 name: props.actionsSource?.name ?? props.alt ?? "Image",
115 sourceIdentifier,
116 actionsSource: props.actionsSource,
117 }),
118 )
119 }
120 style={{ alignSelf: "flex-start" }}
121 >
122 <View
123 className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
124 style={frameStyle}
125 >
126 <ThreadMarkdownImageRequest
127 key={props.sourceKey}
128 uri={props.uri}
129 format={props.format}
130 onLoad={setDecodedSize}
131 onError={() => setFailedUri(props.uri)}
132 />
133 </View>
134 </Pressable>
135 </MediaActionsMenu>
136 </PresentationSource>
137 )}
138 {props.alt ? (
139 <Text selectable className="text-xs text-foreground-muted">
140 {props.alt}
141 </Text>
142 ) : null}
143 </View>
144 );
146​
147function ThreadMarkdownImageRequest(props: {
148 readonly uri: string;
149 readonly onLoad: (sourceSize: { width: number; height: number }) => void;
150 readonly onError: () => void;
151 readonly format?: "svg";
152}) {
153 const [loaded, setLoaded] = useState(false);
154​
155 return (
156 <>
157 {props.format === "svg" ? (
158 <ThreadMarkdownSvg
159 uri={props.uri}
160 onLoad={(size) => {
161 setLoaded(true);
162 if (size) props.onLoad(size);
163 }}
164 onError={props.onError}
165 />
166 ) : (
167 <Image
168 source={{ uri: props.uri }}
169 contentFit="contain"
170 cachePolicy="memory-disk"
171 accessible={false}
172 onLoad={(event) => {
173 setLoaded(true);
174 props.onLoad(event.source);
175 }}
176 onError={props.onError}
177 style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}
178 />
179 )}
180 {loaded ? null : (
181 <View
182 pointerEvents="none"
183 style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}
184 >
185 <Text className="text-xs text-foreground-muted">Loading image…</Text>
186 </View>
187 )}
188 </>
189 );
191​
192function ThreadMarkdownSvg(props: {
193 readonly uri: string;
194 readonly onLoad: (size: { width: number; height: number } | null) => void;
195 readonly onError: () => void;
196}) {
197 const [ast, setAst] = useState<JsxAST | null>(null);
198 const onLoad = useEffectEvent(props.onLoad);
199 const onError = useEffectEvent(props.onError);
200 useEffect(() => {
201 const controller = new AbortController();
202 const load = async () => {
203 if (props.uri.startsWith("data:image/svg+xml")) {
204 const comma = props.uri.indexOf(",");
205 if (comma < 0) throw new Error("SVG data URI has no content");
206 const content = decodeURIComponent(props.uri.slice(comma + 1));
207 return props.uri.slice(0, comma).includes(";base64")
208 ? new TextDecoder().decode(
209 Uint8Array.from(atob(content), (character) => character.charCodeAt(0)),
210 )
211 : content;
212 }
213 const response = await fetch(props.uri, { signal: controller.signal });
214 if (!response.ok && !(response.status === 0 && props.uri.startsWith("file://")))
215 throw new Error(`SVG request failed: ${response.status}`);
216 return response.text();
217 };
218 void load()
219 .then((xml) => {
220 const parsed = parse(xml);
221 if (!parsed) throw new Error("SVG has no root element");
222 if (controller.signal.aborted) return;
223 setAst(parsed);
224 onLoad(resolveSvgImageSize(parsed.props));
225 })
226 .catch(() => {
227 if (!controller.signal.aborted) onError();
228 });
229 return () => controller.abort();
230 }, [props.uri]);
231 return <SvgAst ast={ast} override={{ width: "100%", height: "100%", accessible: false }} />;
233​
234export function ThreadMarkdownImage(props: {
235 readonly environmentId: EnvironmentId;
236 readonly resource: Extract<
237 AssetResource,
238 { readonly _tag: "attachment" | "media-file" | "draft-workspace-file" | "tool-output-image" }
239 >;
240 readonly alt: string | null;
241 readonly srcFragment?: string;
242 readonly actionsSource?: MediaActionsSource;
243 readonly onPressPreview: (source: FilePreviewSource) => void;
244}) {
245 const withGallery = useFilePreviewGallery();
246 const assetUrl = useAssetUrlState(props.environmentId, props.resource);
247​
248 return (
249 <ThreadMarkdownImageView
250 uri={assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null}
251 sourceKey={
252 props.resource._tag === "attachment"
253 ? `attachment:${props.resource.attachmentId}`
254 : props.resource._tag === "tool-output-image"
255 ? `tool-output:${props.resource.itemId}:${props.resource.index}`
256 : `workspace:${props.resource.path}`
257 }
258 unavailable={assetUrl._tag === "Failure"}
259 unavailableDetail={
260 assetUrl._tag === "Failure" && assetUrl.reason === "missing-file-access"
261 ? MISSING_FILE_ACCESS_MESSAGE
262 : undefined
263 }
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 );
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 );