-
Notifications
You must be signed in to change notification settings - Fork 5
/
module.ts
346 lines (318 loc) · 11.3 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import { addBuildPlugin, addTemplate, defineNuxtModule, resolveAlias, resolvePath, useNuxt } from '@nuxt/kit'
import jiti from 'jiti'
import type { ResourceMeta } from 'vue-bundle-renderer'
import { join, relative } from 'pathe'
import { withoutLeadingSlash } from 'ufo'
import local from './providers/local'
import google from './providers/google'
import bunny from './providers/bunny'
import fontshare from './providers/fontshare'
import adobe from './providers/adobe'
import fontsource from './providers/fontsource'
import { FontFamilyInjectionPlugin, type FontFaceResolution } from './plugins/transform'
import { generateFontFace } from './css/render'
import type { GenericCSSFamily } from './css/parse'
import { setupPublicAssetStrategy } from './assets'
import type { FontFamilyManualOverride, FontFamilyProviderOverride, FontProvider, ModuleHooks, ModuleOptions } from './types'
import { setupDevtoolsConnection } from './devtools'
import { logger } from './logger'
export type {
FontProvider,
FontFaceData,
FontFallback,
FontFamilyManualOverride,
FontFamilyOverrides,
FontFamilyProviderOverride,
FontProviderName,
NormalizedFontFaceData,
ResolveFontFacesOptions,
LocalFontSource,
RemoteFontSource,
FontSource,
ModuleOptions,
} from './types'
const defaultValues = {
weights: [400],
styles: ['normal', 'italic'] as const,
subsets: [
'cyrillic-ext',
'cyrillic',
'greek-ext',
'greek',
'vietnamese',
'latin-ext',
'latin',
],
fallbacks: {
'serif': ['Times New Roman'],
'sans-serif': ['Arial'],
'monospace': ['Courier New'],
'cursive': [],
'fantasy': [],
'system-ui': [
'BlinkMacSystemFont',
'Segoe UI',
'Roboto',
'Helvetica Neue',
'Arial',
],
'ui-serif': ['Times New Roman'],
'ui-sans-serif': ['Arial'],
'ui-monospace': ['Courier New'],
'ui-rounded': [],
'emoji': [],
'math': [],
'fangsong': [],
},
} satisfies ModuleOptions['defaults']
export default defineNuxtModule<ModuleOptions>({
meta: {
name: '@nuxt/fonts',
configKey: 'fonts',
},
defaults: {
devtools: true,
experimental: {
processCSSVariables: false,
},
defaults: {},
assets: {
prefix: '/_fonts',
},
local: {},
google: {},
adobe: {
id: '',
},
providers: {
local,
adobe,
google,
bunny,
fontshare,
fontsource,
},
},
async setup(options, nuxt) {
// Skip when preparing
if (nuxt.options._prepare) return
// Custom merging for defaults - providing a value for any default will override module
// defaults entirely (to prevent array merging)
const normalizedDefaults = {
weights: (options.defaults?.weights || defaultValues.weights).map(v => String(v)),
styles: options.defaults?.styles || defaultValues.styles,
subsets: options.defaults?.subsets || defaultValues.subsets,
fallbacks: Object.fromEntries(Object.entries(defaultValues.fallbacks).map(([key, value]) => [
key,
Array.isArray(options.defaults?.fallbacks) ? options.defaults.fallbacks : options.defaults?.fallbacks?.[key as GenericCSSFamily] || value,
])) as Record<GenericCSSFamily, string[]>,
}
if (!options.defaults?.fallbacks || !Array.isArray(options.defaults.fallbacks)) {
const fallbacks = (options.defaults!.fallbacks as Exclude<NonNullable<typeof options.defaults>['fallbacks'], string[]>) ||= {}
for (const _key in defaultValues.fallbacks) {
const key = _key as keyof typeof defaultValues.fallbacks
fallbacks[key] ||= defaultValues.fallbacks[key]
}
}
const providers = await resolveProviders(options.providers)
const prioritisedProviders = new Set<string>()
// Allow registering and disabling providers
nuxt.hook('modules:done', async () => {
await nuxt.callHook('fonts:providers', providers)
const setups: Array<void | Promise<void>> = []
for (const key in providers) {
const provider = providers[key]!
if (options.providers?.[key] === false || (options.provider && options.provider !== key)) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete providers[key]
}
else if (provider.setup) {
setups.push(provider.setup(options[key as 'google' | 'local' | 'adobe'] || {}, nuxt))
}
}
await Promise.all(setups)
for (const val of options.priority || []) {
if (val in providers) prioritisedProviders.add(val)
}
for (const provider in providers) {
prioritisedProviders.add(provider)
}
})
const { normalizeFontData } = setupPublicAssetStrategy(options.assets)
const { exposeFont } = setupDevtoolsConnection(nuxt.options.dev && !!options.devtools)
async function resolveFontFaceWithOverride(fontFamily: string, override?: FontFamilyManualOverride | FontFamilyProviderOverride, fallbackOptions?: { fallbacks: string[], generic?: GenericCSSFamily }): Promise<FontFaceResolution | undefined> {
const fallbacks = override?.fallbacks || normalizedDefaults.fallbacks[fallbackOptions?.generic || 'sans-serif']
if (override && 'src' in override) {
const fonts = normalizeFontData({
src: override.src,
display: override.display,
weight: override.weight,
style: override.style,
})
exposeFont({
type: 'manual',
fontFamily,
fonts,
})
return {
fallbacks,
fonts,
}
}
// Respect fonts that should not be resolved through `@nuxt/fonts`
if (override?.provider === 'none') {
return
}
// Respect custom weights, styles and subsets options
const defaults = { ...normalizedDefaults, fallbacks }
for (const key of ['weights', 'styles', 'subsets'] as const) {
if (override?.[key]) {
defaults[key as 'weights'] = override[key]!.map(v => String(v))
}
}
// Handle explicit provider
if (override?.provider) {
if (override.provider in providers) {
const result = await providers[override.provider]!.resolveFontFaces!(fontFamily, defaults)
// Rewrite font source URLs to be proxied/local URLs
const fonts = normalizeFontData(result?.fonts || [])
if (!fonts.length || !result) {
logger.warn(`Could not produce font face declaration from \`${override.provider}\` for font family \`${fontFamily}\`.`)
return
}
exposeFont({
type: 'override',
fontFamily,
provider: override.provider,
fonts,
})
return {
fallbacks: result.fallbacks || defaults.fallbacks,
fonts,
}
}
// If not registered, log and fall back to default providers
logger.warn(`Unknown provider \`${override.provider}\` for font family \`${fontFamily}\`. Falling back to default providers.`)
}
for (const key of prioritisedProviders) {
const provider = providers[key]!
if (provider.resolveFontFaces) {
const result = await provider.resolveFontFaces(fontFamily, defaults)
if (result) {
// Rewrite font source URLs to be proxied/local URLs
const fonts = normalizeFontData(result.fonts)
if (fonts.length > 0) {
exposeFont({
type: 'auto',
fontFamily,
provider: key,
fonts,
})
return {
fallbacks: result.fallbacks || defaults.fallbacks,
fonts,
}
}
if (override) {
logger.warn(`Could not produce font face declaration for \`${fontFamily}\` with override.`)
}
}
}
}
}
nuxt.options.css.push('#build/nuxt-fonts-global.css')
addTemplate({
filename: 'nuxt-fonts-global.css',
write: true, // Seemingly necessary to allow vite to process file 🤔
async getContents() {
let css = ''
for (const family of options.families || []) {
if (!family.global) continue
const result = await resolveFontFaceWithOverride(family.name, family)
for (const font of result?.fonts || []) {
// We only inject basic `@font-face` as metrics for fallbacks don't make sense
// in this context unless we provide a name for the user to use elsewhere as a
// `font-family`.
css += generateFontFace(family.name, font) + '\n'
}
}
return css
},
})
const fontMap = new Map<string, Set<string>>()
nuxt.hook('build:manifest', (manifest) => {
function addPreloadLinks(chunk: ResourceMeta, urls: Set<string>) {
chunk.assets ||= []
for (const url of urls) {
chunk.assets.push(url)
if (!manifest[url]) {
manifest[url] = {
file: relative(nuxt.options.app.buildAssetsDir, url),
resourceType: 'font',
preload: true,
}
}
}
}
// CSS files in bundle
for (const id in manifest) {
const chunk = manifest[id]!
if (!chunk.css || chunk.css.length === 0) continue
for (const css of chunk.css) {
const assetName = withoutLeadingSlash(join(nuxt.options.app.buildAssetsDir, css))
if (fontMap.has(assetName)) {
addPreloadLinks(chunk, fontMap.get(assetName)!)
}
}
}
// Source files in bundle
for (const [id, urls] of fontMap) {
const chunk = manifest[relative(nuxt.options.srcDir, id)]
if (!chunk) continue
addPreloadLinks(chunk, urls)
}
})
addBuildPlugin(FontFamilyInjectionPlugin({
dev: nuxt.options.dev,
fontsToPreload: fontMap,
processCSSVariables: options.experimental?.processCSSVariables,
shouldPreload(fontFamily, fontFace) {
const override = options.families?.find(f => f.name === fontFamily)
if (override && override.preload !== undefined) {
return override.preload
}
if (options.defaults?.preload !== undefined) {
return options.defaults.preload
}
return fontFace.src.some(s => 'url' in s) && !fontFace.unicodeRange
},
async resolveFontFace(fontFamily, fallbackOptions) {
const override = options.families?.find(f => f.name === fontFamily)
// This CSS will be injected in a separate location
if (override?.global) {
return
}
return resolveFontFaceWithOverride(fontFamily, override, fallbackOptions)
},
}))
},
})
async function resolveProviders(_providers: ModuleOptions['providers'] = {}) {
const nuxt = useNuxt()
const _jiti = jiti(nuxt.options.rootDir, { interopDefault: true })
const providers = { ..._providers }
for (const key in providers) {
const value = providers[key]
if (value === false) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete providers[key]
}
if (typeof value === 'string') {
providers[key] = await _jiti(await resolvePath(resolveAlias(value)))
}
}
return providers as Record<string, FontProvider>
}
declare module '@nuxt/schema' {
interface NuxtHooks extends ModuleHooks {}
}