|
| 1 | +"use client"; |
| 2 | +import { useEffect, useState, useLayoutEffect, useRef } from "react"; |
| 3 | +import { CUSTOM_SVG_DIR, SPRITE_PATH } from "./config"; |
| 4 | +import { renderUse } from "./_shared"; |
| 5 | +import { IconProps } from "./icons/CustomIcon"; |
| 6 | + |
| 7 | +type Payload = { attrs: Record<string, string>; innerHTML: string }; |
| 8 | +const mem = new Map<string, Payload>(); |
| 9 | + |
| 10 | +function extractSVGContent(svg: string): Payload { |
| 11 | + const div = document.createElement("div"); |
| 12 | + div.innerHTML = svg.trim(); |
| 13 | + const svgEl = div.querySelector("svg"); |
| 14 | + if (!svgEl) throw new Error("Bad SVG: <svg> not found"); |
| 15 | + // sanitize |
| 16 | + div.querySelectorAll("script").forEach((n) => n.remove()); |
| 17 | + svgEl.querySelectorAll("*").forEach((el) => { |
| 18 | + for (const { name } of Array.from(el.attributes)) if (/^on[a-z]+/i.test(name)) el.removeAttribute(name); |
| 19 | + }); |
| 20 | + const attrs: Record<string, string> = {}; |
| 21 | + for (const a of Array.from(svgEl.attributes)) if (!/^(width|height)$/i.test(a.name)) attrs[a.name] = a.value; |
| 22 | + return { attrs, innerHTML: svgEl.innerHTML.trim() }; |
| 23 | +} |
| 24 | + |
| 25 | +function DevCustomIcon({ name, size, height, width, ...rest }: IconProps) { |
| 26 | + const [payload, setPayload] = useState<Payload | null>(() => (typeof window !== "undefined" ? mem.get(name) ?? null : null)); |
| 27 | + const svgRef = useRef<SVGSVGElement>(null); |
| 28 | + |
| 29 | + // After mount, stamp raw attributes so React doesn't validate/camelCase them. |
| 30 | + useLayoutEffect(() => { |
| 31 | + const el = svgRef.current; |
| 32 | + if (!el || !payload) return; |
| 33 | + // Merge class from payload with incoming className, if any |
| 34 | + const incomingClass = (rest as any).className ?? ""; |
| 35 | + let payloadClass = payload.attrs.class ?? payload.attrs.className ?? ""; |
| 36 | + const mergedClass = [incomingClass, payloadClass].filter(Boolean).join(" ").trim(); |
| 37 | + if (mergedClass) el.setAttribute("class", mergedClass); |
| 38 | + // Apply all other attrs (skip class handled above and width/height) |
| 39 | + for (const [k, v] of Object.entries(payload.attrs)) { |
| 40 | + if (k === "class" || k === "className") continue; |
| 41 | + if (/^(width|height)$/i.test(k)) continue; |
| 42 | + if (k === "xmlns" || k.startsWith("xmlns:")) continue; |
| 43 | + el.setAttribute(k, v); |
| 44 | + } |
| 45 | + }, [payload, rest]); |
| 46 | + |
| 47 | + useEffect(() => { |
| 48 | + if (typeof window === "undefined") return; |
| 49 | + const ctrl = new AbortController(); |
| 50 | + // sanitize for leading/trailing slashes |
| 51 | + const base = "/" + String(CUSTOM_SVG_DIR).replace(/^\/+|\/+$/g, ""); |
| 52 | + const url = `${base}/${encodeURIComponent(name)}.svg?v=${Date.now()}`; |
| 53 | + fetch(url, { cache: "no-store", signal: ctrl.signal }) |
| 54 | + .then((r) => (r.ok ? r.text() : Promise.reject(new Error(`HTTP ${r.status}`)))) |
| 55 | + .then((txt) => { |
| 56 | + if (ctrl.signal.aborted) return; |
| 57 | + const p = extractSVGContent(txt); |
| 58 | + mem.set(name, p); |
| 59 | + setPayload(p); |
| 60 | + }) |
| 61 | + .catch((err) => { |
| 62 | + if (err.name !== "AbortError") console.warn(`[CustomIcon] failed to load ${url}:`, err); |
| 63 | + if (!ctrl.signal.aborted) setPayload(null); |
| 64 | + }); |
| 65 | + return () => ctrl.abort(); |
| 66 | + }, [name]); |
| 67 | + |
| 68 | + if (payload) { |
| 69 | + return ( |
| 70 | + <svg |
| 71 | + ref={svgRef} |
| 72 | + {...(size != null ? { width: size, height: size } : {})} |
| 73 | + {...(height != null ? { height } : {})} |
| 74 | + {...(width != null ? { width } : {})} |
| 75 | + {...rest} |
| 76 | + dangerouslySetInnerHTML={{ __html: payload.innerHTML }} |
| 77 | + /> |
| 78 | + ); |
| 79 | + } |
| 80 | + |
| 81 | + // fallback if fetch fails in dev |
| 82 | + return renderUse(name, width, height, size, SPRITE_PATH, rest); |
| 83 | +} |
| 84 | + |
| 85 | +export default DevCustomIcon; |
0 commit comments