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 useLayoutEffect(() => {
15 latestRef.current = resolve;
16 const retries = [...retriesRef.current];
17 retriesRef.current.clear();
18 for (const retry of retries) retry();
19 }, [resolve]);
20
21 const enabled = resolve !== undefined;
22 return useMemo(() => {
23 if (!enabled) return undefined;
24 return (image: MarkdownImageOccurrence) =>
25 new Promise<MarkdownImageSource | undefined>((settle) => {
26 const request = { href: image.url, alt: image.altText || null, title: image.title || null };
27 const attempt = () => {
28 const current = latestRef.current;
29 if (!current) return;
30 Promise.resolve()
31 .then(() => current(request))
32 .then(
33 (source) => settle(source ?? undefined),
34 () => {
35 if (latestRef.current !== current) attempt();
36 else retriesRef.current.add(attempt);
37 },
38 );
39 };
40 attempt();
41 });
42 }, [enabled]);
43}