From a JSON file
{ icons } takes a map of names to SVG - a URL or markup per icon, or a map of variants with a default. Pass the object, or a promise of it.
icons.json
{
"anchor": "https://cdn.example.com/icons/anchor.svg",
"bell": {
"default": "https://cdn.example.com/icons/bell.svg",
"active": "https://cdn.example.com/icons/bell-ring.svg",
"muted": "https://cdn.example.com/icons/bell-off.svg"
},
"bookmark": {
"default": "https://cdn.example.com/icons/bookmark.svg",
"active": "https://cdn.example.com/icons/bookmark-check.svg"
}
}
import { register } from '@munsonlabs/sigil'
register('json', {
icons: fetch('/icons.json').then((r) => r.json()),
})
<ml-sigil-icon name="anchor" library="json"></ml-sigil-icon>
<ml-sigil-icon name="bell" library="json"></ml-sigil-icon>
<ml-sigil-icon name="bell" library="json" variant="active"></ml-sigil-icon>
<ml-sigil-icon name="bell" library="json" variant="muted"></ml-sigil-icon>
Loading…
Registration is immediate; the first icon waits for the fetch, then each name and variant is cached.
What icons does for you
The variant lookup, written out as a resolver - fetching and validating a URL value happens automatically either way, so it's skipped here:
const icons = fetch('/icons.json').then((r) => r.json())
register('json', {
resolver: async (name, variant = 'default') => {
const entry = (await icons)[name]
if (!entry) throw new Error(`no icon ${name}`)
return typeof entry === 'string' ? entry : (entry[variant] ?? entry.default)
},
mutator: (svg) => svg.setAttribute('fill', 'currentColor'),
})
Write the resolver form when the map needs logic icons doesn't have - a URL built from the name, a fallback chain, a header on the fetch.
Font classes instead
A JSON file of names to modifier classes, { "heart": "fa-heart", "lock": "fa-lock" }, becomes an icon font:
register('fa', {
className: 'fa',
mapping: await fetch('/fa.json').then((r) => r.json()),
})
<ml-sigil-icon name="heart" library="fa"></ml-sigil-icon>
<!-- <i class="fa fa-heart" aria-hidden="true"></i> -->
mapping as a function
Use a function instead of a record when the lookup needs logic a plain map can't express - like the active suffix below:
const classes: Record<string, string> = await fetch('/fa.json').then((r) => r.json())
register('fa', {
className: 'fa',
mapping: (name, variant) => {
const modifier = classes[name]
if (modifier === undefined) return undefined // not this library's name
return variant === 'active' ? `${modifier} fa-solid` : modifier
},
})
Either form answering undefined means the name isn't this library's; glyphs works the same way. No fetch, no parse, no cache: it's synchronous, so it paints in the same frame.
The font's CSS is yours to load: Font Awesome's stylesheet, or your own @font-face and .fa-heart::before rules. mapping doesn't take a promise, so either await the JSON as above or register once it arrives:
fetch('/fa.json')
.then((r) => r.json())
.then((mapping) => {
register('fa', {
className: 'fa',
mapping,
})
})