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

ThreadMarkdownImage.tsx

367 lines14.1 KB

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