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

ThreadMarkdownImage.tsx

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