Open History to see the last commit
1import { useLayoutEffect, useMemo, useRef } from "react";
2import type { MarkdownImageOccurrence, MarkdownImageSource } from "react-native-enriched-markdown";
3import type { MarkdownImageSourceResolver } from "./SelectableMarkdownText.types";
4
5/**
6 * Enriched asks about each image once and reads `resolveImageSource` like an
7 * event handler, so a failed image would keep its placeholder until remount.
8 * Our resolver fails while the environment is unreachable and is replaced when
9 * that changes, so a failed image stays pending and asks the next resolver.
10 */
11export function useRetryingImageSource(resolve: MarkdownImageSourceResolver | undefined) {
12 const latestRef = useRef(resolve);
13 const retriesRef = useRef(new Set<() => void>());
14 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed resolver to a ref and retries images that failed under the previous one
15 useLayoutEffect(() => {
16 latestRef.current = resolve;
17 const retries = [...retriesRef.current];
18 retriesRef.current.clear();
19 for (const retry of retries) retry();
20 }, [resolve]);
21
22 const enabled = resolve !== undefined;
23 return useMemo(() => {
24 if (!enabled) return undefined;
25 return (image: MarkdownImageOccurrence) =>
26 new Promise<MarkdownImageSource | undefined>((settle) => {
27 const request = { href: image.url, alt: image.altText || null, title: image.title || null };
28 const attempt = () => {
29 const current = latestRef.current;
30 if (!current) return;
31 Promise.resolve()
32 .then(() => current(request))
33 .then(
34 (source) => settle(source ?? undefined),
35 () => {
36 if (latestRef.current !== current) attempt();
37 else retriesRef.current.add(attempt);
38 },
39 );
40 };
41 attempt();
42 });
43 }, [enabled]);
44}