-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathmodule.ts
228 lines (206 loc) · 7.48 KB
/
module.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { basename, join } from 'node:path'
import fs from 'node:fs/promises'
import { defineNuxtModule, addPlugin, addServerHandler, hasNuxtModule, createResolver, addTemplate, addComponent, logger } from '@nuxt/kit'
import { addCustomTab } from '@nuxt/devtools-kit'
import type { Nuxt } from '@nuxt/schema'
import fg from 'fast-glob'
import type { IconifyJSON } from '@iconify/types'
import { parseSVGContent, convertParsedSVG } from '@iconify/utils/lib/svg/parse'
import collectionNames from './collections'
import { schema } from './schema'
import type { ModuleOptions, ResolvedServerBundleOptions, CustomCollection, ServerBundleOptions, NuxtIconRuntimeOptions } from './types'
import { unocssIntegration } from './integrations/unocss'
export type { ModuleOptions }
export default defineNuxtModule<ModuleOptions>({
meta: {
name: 'nuxt-icon',
configKey: 'icon',
compatibility: {
nuxt: '^3.0.0',
},
},
defaults: {
// Module options
componentName: 'Icon',
serverBundle: 'auto',
serverKnownCssClasses: [],
// Runtime options
provider: schema['provider'].$default,
class: schema['class'].$default,
size: schema['size'].$default,
aliases: schema['aliases'].$default,
iconifyApiEndpoint: schema['iconifyApiEndpoint'].$default,
fallbackToApi: schema['fallbackToApi'].$default,
cssSelectorPrefix: schema['cssSelectorPrefix'].$default,
cssWherePseudo: schema['cssWherePseudo'].$default,
cssLayer: schema['cssLayer'].$default,
mode: schema['mode'].$default,
attrs: schema['attrs'].$default,
collections: schema['collections'].$default,
},
async setup(options, nuxt) {
const resolver = createResolver(import.meta.url)
addPlugin(
resolver.resolve('./runtime/plugin'),
)
addComponent({
name: options.componentName || 'Icon',
global: true,
filePath: resolver.resolve('./runtime/components/index'),
})
addServerHandler({
route: '/api/_nuxt_icon/:collection',
handler: resolver.resolve('./runtime/server/api'),
})
// Merge options to app.config
const runtimeOptions = Object.fromEntries(
Object.entries(options)
.filter(([key]) => key in schema),
)
if (!runtimeOptions.collections) {
runtimeOptions.collections = runtimeOptions.fallbackToApi
? collectionNames
: options.serverBundle === 'auto'
? collectionNames
: options.serverBundle
? options.serverBundle.collections
: []
}
nuxt.options.appConfig.icon = Object.assign(
nuxt.options.appConfig.icon || {},
runtimeOptions,
)
// Define types for the app.config compatible with Nuxt Studio
nuxt.hook('schema:extend', (schemas) => {
schemas.push({
appConfig: {
icon: schema,
},
})
})
// Bundle icons for server
const bundle = resolveServerBundle(
nuxt,
(!options.serverBundle || options.provider !== 'server')
? {}
: (options.serverBundle === 'auto')
? discoverLocalCollections()
: options.serverBundle,
options.customCollections,
)
const template = addTemplate({
filename: 'nuxt-icon-server-bundle.mjs',
write: true,
async getContents() {
const { collections } = await bundle
nuxt.options.appConfig.icon ||= {}
const appIcons = nuxt.options.appConfig.icon as NuxtIconRuntimeOptions
appIcons.collections ||= []
for (const collection of collections) {
const prefix = typeof collection === 'string' ? collection : collection.prefix
if (!appIcons.collections.includes(prefix))
appIcons.collections.push(prefix)
}
const isBundling = !nuxt.options.dev
// When in dev mode, we avoid bundling the icons to improve performance
// Get rid of the require() when ESM JSON modules are widely supported
function getImport(collection: string) {
return isBundling
? `import('@iconify-json/${collection}/icons.json').then(m => m.default)`
: `require('@iconify-json/${collection}/icons.json')`
}
const lines = [
...(isBundling
? []
: [
`import { createRequire } from 'module'`,
`const require = createRequire(import.meta.url)`,
]
),
`export const collections = {`,
...collections.map(collection => typeof collection === 'string'
? ` '${collection}': () => ${getImport(collection)},`
: ` '${collection.prefix}': () => (${JSON.stringify(collection)}),`),
`}`,
]
return lines.join('\n')
},
})
nuxt.options.nitro.alias ||= {}
nuxt.options.nitro.alias['#nuxt-icon-server-bundle'] = template.dst
// Devtools
addCustomTab({
name: 'icones',
title: 'Icônes',
icon: 'https://icones.js.org/favicon.svg',
view: {
type: 'iframe',
src: 'https://icones.js.org',
},
})
// Server-only runtime config for known CSS selectors
options.serverKnownCssClasses ||= []
const serverKnownCssClasses = options.serverKnownCssClasses || []
nuxt.options.runtimeConfig.icon = {
serverKnownCssClasses,
}
nuxt.hook('nitro:init', async (_nitro) => {
_nitro.options.runtimeConfig.icon = {
serverKnownCssClasses,
}
})
if (hasNuxtModule('@unocss/nuxt'))
unocssIntegration(nuxt, options)
await nuxt.callHook('icon:serverKnownCssClasses', serverKnownCssClasses)
},
})
async function discoverLocalCollections(): Promise<ServerBundleOptions> {
const isPackageExists = await import('local-pkg').then(r => r.isPackageExists)
const collections = collectionNames
.filter(collection => isPackageExists('@iconify-json/' + collection))
if (collections.length)
logger.success(`Nuxt Icon discovered local-installed ${collections.length} collections:`, collections.join(', '))
return { collections }
}
async function resolveServerBundle(
nuxt: Nuxt,
options: ServerBundleOptions | Promise<ServerBundleOptions>,
customCollections: CustomCollection[] = [],
): Promise<ResolvedServerBundleOptions> {
const resolved = await options
return {
collections: await Promise.all(([...(resolved.collections || []), ...customCollections])
.map(c => resolveCollection(nuxt, c))),
}
}
async function resolveCollection(nuxt: Nuxt, collection: string | IconifyJSON | CustomCollection): Promise<string | IconifyJSON> {
if (typeof collection === 'string')
return collection
// Custom collection
if ('dir' in collection) {
const dir = join(nuxt.options.rootDir, collection.dir)
const files = (await fg('*.svg', { cwd: dir, onlyFiles: true }))
.sort()
const json: IconifyJSON = {
...collection,
icons: Object.fromEntries(await Promise.all(files.map(async (file) => {
const name = basename(file, '.svg')
let svg = await fs.readFile(join(dir, file), 'utf-8')
const cleanupIdx = svg.indexOf('<svg')
if (cleanupIdx > 0)
svg = svg.slice(cleanupIdx)
const data = convertParsedSVG(parseSVGContent(svg)!)!
if (data.top === 0)
delete data.top
if (data.left === 0)
delete data.left
return [name, data]
}))),
}
// @ts-expect-error remove extra properties
delete json.dir
logger.success(`Nuxt Icon loaded local collection \`${json.prefix}\` with ${files.length} icons`)
return json
}
return collection
}