import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useRef, useState } from 'react';
import { css, styled, vui } from '../core';
import { cs } from '../utils';
import cache from './cache';
import { getAttributes, getSvgContent, initState, stringToHTML } from './helpers';
export const SvgBase = styled.svgBox(({ pathFill }) => {
    return css `
    ${pathFill !== undefined &&
        (Array.isArray(pathFill)
            ? pathFill
                .map((fill, index) => `
					& > path:nth-child(${index + 1}) {
						fill: ${fill};
					}
				`)
                .join()
            : `
				& > path {
					fill: ${pathFill};
				}
			`)}
  `;
});
/**
 * Displays an svg element based on provided children or 'src' prop.
 *
 * When using src, it loads the content from the given URL and saves in in cache.
 *
 * Then, renders the svg by parsing loaded content (Review potential for XSS due to innerHTML).
 */
export const Svg = vui((props, ref) => {
    const { children, className, src, ...rest } = props;
    const [state, setState] = useState(initState());
    const isMountedRef = useRef(false);
    const srcRef = useRef(src);
    const { content = '', svgAttributes = {} } = state;
    const innerHTML = !children ? { __html: content } : undefined;
    useEffect(() => {
        isMountedRef.current = true;
        return () => {
            isMountedRef.current = false;
        };
    }, []);
    useEffect(() => {
        srcRef.current = src;
        async function loadSvg(src) {
            try {
                const response = await cache.get(src);
                const content = getSvgContent(response);
                const svgEl = stringToHTML(response);
                const svgAttributes = getAttributes(svgEl);
                svgAttributes['data-src'] = src ?? '';
                // Update state only when requested 'src' and current 'src' are the same
                if (srcRef.current === src && isMountedRef.current) {
                    setState({ content, svgAttributes });
                }
            }
            catch (error) {
                console.error(error); // eslint-disable-line no-console
                if (isMountedRef.current) {
                    setState(initState());
                }
            }
        }
        src && loadSvg(src);
    }, [src]);
    return (_jsx(SvgBase, { className: cs('vui-svg', className), dangerouslySetInnerHTML: innerHTML, ref: ref, xmlns: "http://www.w3.org/2000/svg", ...svgAttributes, ...rest, children: children }));
});
Svg.displayName = 'Svg';
export default Svg;
//# sourceMappingURL=svg.js.map