|
| 1 | +import { parseIconWithLoader } from '@unocss/preset-icons/browser' |
| 2 | +import DOMPurify from 'dompurify' |
| 3 | + |
| 4 | +// The client can be embedded directly into a host page's DOM as a |
| 5 | +// shadow-rooted custom element with no iframe of its own. UnoCSS's atomic |
| 6 | +// classes (build-time and `@unocss/runtime` alike) inject/observe against |
| 7 | +// `document`, which is the host page's single document either way — outside |
| 8 | +// the shadow boundary, invisible to anything mounted inside it. Icons are the |
| 9 | +// one part of this UI whose class names aren't all known at the client's own |
| 10 | +// build time (an installed Nuxt module can report any Iconify id as its |
| 11 | +// icon), so they can't be fully covered by the build-time UnoCSS extraction |
| 12 | +// either. Fetching and inlining the SVG ourselves sidesteps both problems — |
| 13 | +// no CSS generation, no DOM root to get wrong. |
| 14 | +const cache = new Map<string, Promise<string | undefined>>() |
| 15 | + |
| 16 | +async function fetchIconifySvg(collection: string, icon: string): Promise<string | undefined> { |
| 17 | + const url = `https://api.iconify.design/${collection}/${icon}.svg?color=currentColor&width=1.2em&height=1.2em` |
| 18 | + try { |
| 19 | + const res = await fetch(url, { signal: AbortSignal.timeout(10_000) }) |
| 20 | + if (!res.ok) |
| 21 | + return undefined |
| 22 | + return DOMPurify.sanitize(await res.text(), { USE_PROFILES: { svg: true } }) |
| 23 | + } |
| 24 | + catch { |
| 25 | + // Offline / flaky CDN — degrade to a blank icon rather than throwing out |
| 26 | + // of the caller's async effect. |
| 27 | + return undefined |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Resolve a UnoCSS-style icon id (`carbon-tree-view-alt`, `i-logos-vue`, |
| 33 | + * `carbon:settings`, ...) to inline, sanitized SVG markup, fetched from the |
| 34 | + * Iconify API and cached in-memory. Returns `undefined` when the id doesn't |
| 35 | + * parse as a known Iconify collection, or the fetch fails. |
| 36 | + */ |
| 37 | +export function getIconifySvg(id: string): Promise<string | undefined> { |
| 38 | + const cached = cache.get(id) |
| 39 | + if (cached) |
| 40 | + return cached |
| 41 | + |
| 42 | + const promise = parseIconWithLoader(id.replace(/^i-/, ''), fetchIconifySvg) |
| 43 | + .then(result => result?.svg) |
| 44 | + .catch(() => undefined) |
| 45 | + cache.set(id, promise) |
| 46 | + // Don't cache a failed lookup — a later render (e.g. once back online) can |
| 47 | + // retry it. |
| 48 | + promise.then(svg => svg === undefined && cache.delete(id)) |
| 49 | + return promise |
| 50 | +} |
0 commit comments