/
cdn.ts
37 lines (32 loc) · 1.19 KB
/
cdn.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import type { IconifyJSON } from '@iconify/types'
import { loadIcon } from '@iconify/utils/lib/loader/loader'
import { searchForIcon } from '@iconify/utils/lib/loader/modern'
import type { UniversalIconLoader } from '@iconify/utils/lib/loader/types'
import { $fetch } from 'ohmyfetch'
import supportedCollection from './collections.json'
export function createCDNLoader(cdnBase: string): UniversalIconLoader {
const cache = new Map<string, Promise<IconifyJSON>>()
function fetchCollection(name: string) {
if (!supportedCollection.includes(name))
return undefined
if (!cache.has(name))
cache.set(name, $fetch(`${cdnBase}@iconify-json/${name}/icons.json`))
return cache.get(name)!
}
return async (collection, icon, options) => {
let result = await loadIcon(collection, icon, options)
if (result)
return result
const iconSet = await fetchCollection(collection)
if (iconSet) {
// possible icon names
const ids = [
icon,
icon.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(),
icon.replace(/([a-z])(\d+)/g, '$1-$2'),
]
result = await searchForIcon(iconSet, collection, ids, options)
}
return result
}
}