|
| 1 | +import { useAtomValue } from "@effect/atom-react"; |
1 | 2 | import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets"; |
2 | 3 | import type { AssetResource, EnvironmentId } from "@t3tools/contracts"; |
| 4 | +import * as Data from "effect/Data"; |
| 5 | +import * as Effect from "effect/Effect"; |
| 6 | +import { AsyncResult, Atom } from "effect/reactivity"; |
3 | 7 | import { Image } from "expo-image"; |
4 | | -import { createContext, useContext, useEffect, useEffectEvent, useId, useState } from "react"; |
| 8 | +import { createContext, useContext, useId, useState } from "react"; |
5 | 9 | import { fetch } from "expo/fetch"; |
6 | 10 | import { parse, SvgAst, type JsxAST } from "react-native-svg"; |
7 | 11 | import { Pressable, StyleSheet, View, type ViewStyle } from "react-native"; |
@@ -25,6 +29,58 @@ import { |
25 | 29 | /** Use known feed width immediately; later image measurement would move already-positioned rows. */ |
26 | 30 | export const MarkdownImageAvailableWidthContext = createContext(0); |
27 | 31 |
|
| 32 | +type ImageSize = { readonly width: number; readonly height: number }; |
| 33 | + |
| 34 | +class SvgLoadError extends Data.TaggedError("SvgLoadError")<{ readonly cause: unknown }> {} |
| 35 | + |
| 36 | +async 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(); |
| 52 | +} |
| 53 | + |
| 54 | +type 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. |
| 59 | +const 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 | + |
| 66 | +const 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 | + |
| 82 | +const noSvgDocumentAtom = Atom.make(AsyncResult.initial<SvgDocument, SvgLoadError>()); |
| 83 | + |
28 | 84 | export function ThreadMarkdownImageView(props: { |
29 | 85 | readonly uri: string | null; |
30 | 86 | readonly sourceKey: string; |
@@ -45,12 +101,14 @@ export function ThreadMarkdownImageView(props: { |
45 | 101 | measuredWidth > 0 && contextWidth > 0 |
46 | 102 | ? Math.min(contextWidth, measuredWidth) |
47 | 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; |
48 | 108 | // Keyed by source so a new source drops the previous image's decoded dimensions. |
49 | | - const [decoded, setDecoded] = useState<{ |
50 | | - sourceKey: string; |
51 | | - size: { width: number; height: number }; |
52 | | - } | null>(null); |
53 | | - const decodedSize = decoded?.sourceKey === props.sourceKey ? decoded.size : null; |
| 109 | + const [decoded, setDecoded] = useState<{ sourceKey: string; size: ImageSize } | null>(null); |
| 110 | + const decodedSize = |
| 111 | + svgDocument?.size ?? (decoded?.sourceKey === props.sourceKey ? decoded.size : null); |
54 | 112 | // A failure belongs to one URI; any URI change, including through null, retries. |
55 | 113 | const [failure, setFailure] = useState({ uri: props.uri, failed: false }); |
56 | 114 | if (failure.uri !== props.uri) setFailure({ uri: props.uri, failed: false }); |
@@ -65,7 +123,9 @@ export function ThreadMarkdownImageView(props: { |
65 | 123 | availableWidth, |
66 | 124 | }); |
67 | 125 | const failed = |
68 | | - props.unavailable || (props.uri !== null && failure.uri === props.uri && failure.failed); |
| 126 | + props.unavailable || |
| 127 | + (props.uri !== null && failure.uri === props.uri && failure.failed) || |
| 128 | + AsyncResult.isFailure(svg); |
69 | 129 | const placeholderWidth: ViewStyle["width"] = |
70 | 130 | availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%"; |
71 | 131 | const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 }; |
@@ -123,13 +183,16 @@ export function ThreadMarkdownImageView(props: { |
123 | 183 | className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg" |
124 | 184 | style={frameStyle} |
125 | 185 | > |
126 | | - <ThreadMarkdownImageRequest |
127 | | - key={props.sourceKey} |
128 | | - uri={props.uri} |
129 | | - format={props.format} |
130 | | - onLoad={(size) => setDecoded({ sourceKey: props.sourceKey, size })} |
131 | | - onError={() => setFailure({ uri: props.uri, failed: true })} |
132 | | - /> |
| 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 | + )} |
133 | 196 | </View> |
134 | 197 | </Pressable> |
135 | 198 | </MediaActionsMenu> |
@@ -146,89 +209,47 @@ export function ThreadMarkdownImageView(props: { |
146 | 209 |
|
147 | 210 | function ThreadMarkdownImageRequest(props: { |
148 | 211 | readonly uri: string; |
149 | | - readonly onLoad: (sourceSize: { width: number; height: number }) => void; |
| 212 | + readonly onLoad: (sourceSize: ImageSize) => void; |
150 | 213 | readonly onError: () => void; |
151 | | - readonly format?: "svg"; |
152 | 214 | }) { |
153 | 215 | const [loaded, setLoaded] = useState(false); |
154 | 216 |
|
155 | 217 | return ( |
156 | 218 | <> |
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 | | - )} |
| 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 />} |
188 | 232 | </> |
189 | 233 | ); |
190 | 234 | } |
191 | 235 |
|
192 | | -function 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 }} />; |
| 236 | +function 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 | + ); |
| 245 | +} |
| 246 | + |
| 247 | +function 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 | + ); |
232 | 253 | } |
233 | 254 |
|
234 | 255 | export function ThreadMarkdownImage(props: { |
|