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

ThreadMarkdownImage.tsx

319 lines12.1 KB

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