-
-
Notifications
You must be signed in to change notification settings - Fork 130
/
modern.ts
67 lines (59 loc) 路 2.15 KB
/
modern.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { promises as fs } from 'fs'
import { IconifyJSON } from '@iconify/types'
import { iconToSVG } from '@iconify/utils/lib/svg/build'
import { defaults as DefaultIconCustomizations } from '@iconify/utils/lib/customisations'
import { getIconData } from '@iconify/utils/lib/icon-set/get-icon'
import createDebugger from 'debug'
import { FullIconifyIcon } from '@iconify/utils/lib/icon'
import { isPackageExists, resolveModule } from 'local-pkg'
import { ResolvedOptions } from '../types'
import { tryInstallPkg } from './utils'
const debug = createDebugger('unplugin-icons:modern')
const debugCollection = createDebugger('unplugin-icons:modern:collection')
export interface ResolvedIconPath {
collection: string
icon: string
query: Record<string, string | undefined>
}
const _collections: Record<string, IconifyJSON | false> = {}
export async function loadCollection(name: string, autoInstall = false): Promise<IconifyJSON | undefined> {
if (_collections[name] === false)
return undefined
if (_collections[name])
return _collections[name] as IconifyJSON
if (!isPackageExists(`@iconify-json/${name}`)) {
if (autoInstall)
await tryInstallPkg(`@iconify-json/${name}`)
else
return undefined
}
debugCollection(name)
const jsonPath = resolveModule(`@iconify-json/${name}/icons.json`)
if (jsonPath) {
const icons = JSON.parse(await fs.readFile(jsonPath, 'utf8'))
_collections[name] = icons
return icons
}
else {
debugCollection(`failed to load ${name}`)
_collections[name] = false
return undefined
}
}
export function searchForIcon(iconSet: IconifyJSON, collection: string, ids: string[], options?: ResolvedOptions) {
let iconData: FullIconifyIcon | null
for (const id of ids) {
iconData = getIconData(iconSet, id, true)
if (iconData) {
debug(`${collection}:${id}`)
const scale = options?.scale ?? 1
const { attributes, body } = iconToSVG(iconData, {
...DefaultIconCustomizations,
height: `${scale}em`,
width: `${scale}em`,
})
return `<svg ${Object.entries(attributes).map(i => `${i[0]}="${i[1]}"`).join(' ')}>${body}</svg>`
}
}
return null
}