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

ThreadMarkdownImage.tsx

303 lines11.0 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 { ActivityIndicator, 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/**
26 * Width the feed lays markdown out in. The feed already knows this from its
27 * viewport, so an image can size its frame on the first render instead of
28 * waiting for its own onLayout, which would change the row's height once more
29 * after the list has positioned the rows below it.
30 */
31export const MarkdownImageAvailableWidthContext = createContext(0);
32​
33export function ThreadMarkdownImageView(props: {
34 readonly uri: string | null;
35 readonly sourceKey: string;
36 readonly unavailable: boolean;
37 readonly unavailableDetail?: string | undefined;
38 readonly alt: string | null;
39 readonly knownSize?: { readonly width: number; readonly height: number } | undefined;
40 readonly format?: "svg";
41 readonly actionsSource?: MediaActionsSource;
42 readonly onPressPreview: (source: FilePreviewSource) => void;
43}) {
44 const withGallery = useFilePreviewGallery();
45 const sourceIdentifier = useId();
46 const mediaActions = useMediaActions(props.actionsSource);
47 const contextWidth = useContext(MarkdownImageAvailableWidthContext);
48 const [measuredWidth, setMeasuredWidth] = useState(0);
49 const availableWidth =
50 measuredWidth > 0 && contextWidth > 0
51 ? Math.min(contextWidth, measuredWidth)
52 : contextWidth || measuredWidth;
53 const [decodedSize, setDecodedSize] = useState<{ width: number; height: number } | null>(null);
54 const [failedUri, setFailedUri] = useState<string | null>(null);
55​
56 useEffect(() => {
57 setDecodedSize(null);
58 }, [props.sourceKey]);
59​
60 useEffect(() => {
61 setFailedUri(null);
62 }, [props.uri]);
63​
64 const sourceSize = decodedSize ?? props.knownSize ?? null;
65 const displaySize: MarkdownImageDisplaySize | null =
66 sourceSize === null || availableWidth <= 0
67 ? null
68 : resolveMarkdownImageDisplaySize({
69 sourceWidth: sourceSize.width,
70 sourceHeight: sourceSize.height,
71 availableWidth,
72 });
73 const failed = props.unavailable || (props.uri !== null && failedUri === props.uri);
74 const placeholderWidth: ViewStyle["width"] =
75 availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
76 const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
77​
78 return (
79 <View
80 onLayout={(event) => setMeasuredWidth(event.nativeEvent.layout.width)}
81 style={{ alignSelf: "stretch", gap: 6 }}
82 >
83 {props.uri === null || failed ? (
84 <MediaActionsMenu media={mediaActions}>
85 <Pressable
86 accessibilityRole="imagebutton"
87 accessibilityLabel={props.alt ?? "Markdown image"}
88 accessibilityHint={
89 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
90 }
91 className="items-center justify-center rounded-[10px] bg-md-code-bg"
92 style={frameStyle}
93 >
94 {failed ? (
95 <Text className="px-3 text-center text-xs text-foreground-muted">
96 {props.unavailableDetail
97 ? `Image unavailable. ${props.unavailableDetail}`
98 : "Image unavailable"}
99 </Text>
100 ) : (
101 <AppActivityIndicator />
102 )}
103 </Pressable>
104 </MediaActionsMenu>
105 ) : (
106 <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>
107 <MediaActionsMenu media={mediaActions}>
108 <Pressable
109 accessibilityRole="imagebutton"
110 accessibilityLabel={props.alt ?? "Markdown image"}
111 accessibilityHint={
112 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
113 }
114 onPress={() =>
115 props.onPressPreview(
116 withGallery({
117 kind: "image",
118 uri: props.uri!,
119 name: props.actionsSource?.name ?? props.alt ?? "Image",
120 sourceIdentifier,
121 actionsSource: props.actionsSource,
122 }),
123 )
124 }
125 style={{ alignSelf: "flex-start" }}
126 >
127 <View
128 className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
129 style={frameStyle}
130 >
131 <ThreadMarkdownImageRequest
132 key={props.sourceKey}
133 uri={props.uri}
134 format={props.format}
135 onLoad={setDecodedSize}
136 onError={() => setFailedUri(props.uri)}
137 />
138 </View>
139 </Pressable>
140 </MediaActionsMenu>
141 </PresentationSource>
142 )}
143 {props.alt ? (
144 <Text selectable className="text-xs text-foreground-muted">
145 {props.alt}
146 </Text>
147 ) : null}
148 </View>
149 );
151​
152function ThreadMarkdownImageRequest(props: {
153 readonly uri: string;
154 readonly onLoad: (sourceSize: { width: number; height: number }) => void;
155 readonly onError: () => void;
156 readonly format?: "svg";
157}) {
158 const [loaded, setLoaded] = useState(false);
159​
160 return (
161 <>
162 {props.format === "svg" ? (
163 <ThreadMarkdownSvg
164 uri={props.uri}
165 onLoad={(size) => {
166 setLoaded(true);
167 if (size) props.onLoad(size);
168 }}
169 onError={props.onError}
170 />
171 ) : (
172 <Image
173 source={{ uri: props.uri }}
174 contentFit="contain"
175 cachePolicy="memory-disk"
176 accessible={false}
177 onLoad={(event) => {
178 setLoaded(true);
179 props.onLoad(event.source);
180 }}
181 onError={props.onError}
182 style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}
183 />
184 )}
185 {loaded ? null : (
186 <View
187 pointerEvents="none"
188 style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}
189 >
190 <Text className="text-xs text-foreground-muted">Loading image…</Text>
191 </View>
192 )}
193 </>
194 );
196​
197function ThreadMarkdownSvg(props: {
198 readonly uri: string;
199 readonly onLoad: (size: { width: number; height: number } | null) => void;
200 readonly onError: () => void;
201}) {
202 const [ast, setAst] = useState<JsxAST | null>(null);
203 const onLoad = useEffectEvent(props.onLoad);
204 const onError = useEffectEvent(props.onError);
205 useEffect(() => {
206 const controller = new AbortController();
207 const load = async () => {
208 if (props.uri.startsWith("data:image/svg+xml")) {
209 const comma = props.uri.indexOf(",");
210 if (comma < 0) throw new Error("SVG data URI has no content");
211 const content = decodeURIComponent(props.uri.slice(comma + 1));
212 return props.uri.slice(0, comma).includes(";base64")
213 ? new TextDecoder().decode(
214 Uint8Array.from(atob(content), (character) => character.charCodeAt(0)),
215 )
216 : content;
217 }
218 const response = await fetch(props.uri, { signal: controller.signal });
219 if (!response.ok && !(response.status === 0 && props.uri.startsWith("file://")))
220 throw new Error(`SVG request failed: ${response.status}`);
221 return response.text();
222 };
223 void load()
224 .then((xml) => {
225 const parsed = parse(xml);
226 if (!parsed) throw new Error("SVG has no root element");
227 if (controller.signal.aborted) return;
228 setAst(parsed);
229 onLoad(resolveSvgImageSize(parsed.props));
230 })
231 .catch(() => {
232 if (!controller.signal.aborted) onError();
233 });
234 return () => controller.abort();
235 }, [props.uri]);
236 return <SvgAst ast={ast} override={{ width: "100%", height: "100%", accessible: false }} />;
238​
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 unavailableDetail={
265 assetUrl._tag === "Failure" && assetUrl.reason === "missing-file-access"
266 ? MISSING_FILE_ACCESS_MESSAGE
267 : undefined
268 }
269 knownSize={assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined}
270 format={
271 (props.resource._tag === "media-file" || props.resource._tag === "draft-workspace-file") &&
272 /\.svg$/i.test(props.resource.path)
273 ? "svg"
274 : undefined
275 }
276 alt={props.alt}
277 actionsSource={props.actionsSource}
278 onPressPreview={(source) => {
279 const { uri: _uri, ...rest } = source as FilePreviewSource & { uri?: string };
280 props.onPressPreview(
281 withGallery({
282 ...rest,
283 gallery: undefined,
284 environmentId: props.environmentId,
285 resource: props.resource,
286 }),
287 );
288 }}
289 />
290 );
292​
293export function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {
294 return (
295 <ThreadMarkdownImageView
296 uri={null}
297 sourceKey="unavailable"
298 unavailable
299 alt={props.alt}
300 onPressPreview={() => undefined}
301 />
302 );