import { useCallback, useEffect, useReducer, useRef } from 'react'; import { STATUS } from '../config'; import type { FetchError, Props, State } from '../types'; import type CacheStore from './cache'; import { canUseDOM, isSupportedEnvironment, randomString, request } from './helpers'; import { useMount, usePrevious } from './hooks'; import { convertToElement } from './utils'; export default function useInlineSVG(props: Props, cacheStore: CacheStore) { const { baseURL, cacheElements = false, cacheRequests = true, description, fetchOptions, onError, onLoad, preProcessor, src, title, uniqueHash, uniquifyIDs, } = props; const hashRef = useRef(uniqueHash); // Read once, like `hashRef`: a later `uniqueHash` doesn't replace a random hash already in use. const hasStableHash = useRef(uniqueHash !== undefined).current; // A random hash makes the key unique to this instance, so the entry could never be reused. const shouldCacheElement = cacheElements && !(uniquifyIDs && !hasStableHash); const fetchOptionsRef = useRef(fetchOptions); const onErrorRef = useRef(onError); const onLoadRef = useRef(onLoad); const preProcessorRef = useRef(preProcessor); fetchOptionsRef.current = fetchOptions; onErrorRef.current = onError; onLoadRef.current = onLoad; preProcessorRef.current = preProcessor; const getHash = useCallback(() => { const hash = hashRef.current ?? randomString(8); hashRef.current = hash; return hash; }, []); const [state, setState] = useReducer( (previousState: State, nextState: Partial) => ({ ...previousState, ...nextState, }), { content: '', element: null, isCached: false, status: STATUS.IDLE, }, (initial): State => { const cached = cacheRequests && cacheStore.isCached(src); if (!cached) { return initial; } const cachedContent = cacheStore.getContent(src); try { const convertedElement = convertToElement({ ...props, cacheElements: shouldCacheElement, handleError: () => {}, hash: uniquifyIDs ? getHash() : '', content: cachedContent, }); if (convertedElement) { return { content: cachedContent, element: convertedElement, isCached: true, status: STATUS.READY, }; } } catch { // Fall through to effect-driven flow } return { ...initial, content: cachedContent, isCached: true, status: STATUS.LOADED, }; }, ); const { content, element, isCached, status } = state; const previousProps = usePrevious(props); const previousState = usePrevious(state); const isActive = useRef(false); const isInitialized = useRef(false); const handleError = useCallback((error: Error | FetchError) => { if (isActive.current) { setState({ status: error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED, }); onErrorRef.current?.(error); } }, []); const getElement = useCallback(() => { try { const convertedElement = convertToElement({ baseURL, cacheElements: shouldCacheElement, content, description, handleError, hash: uniquifyIDs ? getHash() : '', preProcessor: preProcessorRef.current, src, title, uniquifyIDs, }); if (!convertedElement) { throw new Error('Could not convert the src to a React element'); } setState({ element: convertedElement, status: STATUS.READY, }); } catch (error: any) { handleError(error); } }, [ baseURL, content, description, getHash, handleError, shouldCacheElement, src, title, uniquifyIDs, ]); // Mount useMount(() => { isActive.current = true; if (!canUseDOM() || isInitialized.current) { return undefined; } try { if (status === STATUS.READY) { onLoadRef.current?.(src, isCached); } else if (status === STATUS.IDLE) { if (!isSupportedEnvironment()) { throw new Error('Browser does not support SVG'); } if (!src) { throw new Error('Missing src'); } setState({ content: '', element: null, isCached: false, status: STATUS.LOADING }); } } catch (error: any) { handleError(error); } isInitialized.current = true; return () => { isActive.current = false; }; }); // Src changes useEffect(() => { if (!canUseDOM() || !previousProps) { return; } if (previousProps.src !== src) { if (!src) { handleError(new Error('Missing src')); return; } setState({ content: '', element: null, isCached: false, status: STATUS.LOADING }); } }, [handleError, previousProps, src]); // Fetch content when status is LOADING useEffect(() => { if (status !== STATUS.LOADING) { return undefined; } const controller = new AbortController(); let active = true; (async () => { try { const dataURI = /^data:image\/svg[^,]*?(;base64)?,(.*)/.exec(src); let inlineSrc; if (dataURI) { inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]); } else if (src.includes(' { active = false; controller.abort(); }; }, [cacheRequests, cacheStore, handleError, src, status]); // LOADED -> READY useEffect(() => { if (status === STATUS.LOADED && content) { getElement(); } }, [content, getElement, status]); // Title and description changes useEffect(() => { if (!canUseDOM() || !previousProps || previousProps.src !== src) { return; } if (previousProps.title !== title || previousProps.description !== description) { getElement(); } }, [description, getElement, previousProps, src, title]); // READY -> onLoad useEffect(() => { if (!previousState) { return; } if (status === STATUS.READY && previousState.status !== STATUS.READY) { onLoadRef.current?.(src, isCached); } }, [isCached, previousState, src, status]); return { element, status }; }