@timber-js/app 0.2.0-alpha.247 → 0.2.0-alpha.248
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/fonts/ast.d.ts.map +1 -1
- package/dist/fonts/bundle.d.ts +26 -8
- package/dist/fonts/bundle.d.ts.map +1 -1
- package/dist/fonts/fallbacks.d.ts +46 -8
- package/dist/fonts/fallbacks.d.ts.map +1 -1
- package/dist/fonts/font-metrics.d.ts +54 -0
- package/dist/fonts/font-metrics.d.ts.map +1 -0
- package/dist/fonts/local-fallback.d.ts +64 -0
- package/dist/fonts/local-fallback.d.ts.map +1 -0
- package/dist/fonts/local.d.ts.map +1 -1
- package/dist/fonts/sfnt.d.ts +30 -0
- package/dist/fonts/sfnt.d.ts.map +1 -0
- package/dist/fonts/transform.d.ts.map +1 -1
- package/dist/fonts/types.d.ts +29 -0
- package/dist/fonts/types.d.ts.map +1 -1
- package/dist/index.js +1063 -352
- package/dist/index.js.map +1 -1
- package/dist/plugins/build-manifest.d.ts +5 -0
- package/dist/plugins/build-manifest.d.ts.map +1 -1
- package/dist/plugins/fonts.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/fonts/ast.ts +35 -2
- package/src/fonts/bundle.ts +71 -17
- package/src/fonts/fallbacks.ts +92 -28
- package/src/fonts/font-metrics.ts +236 -0
- package/src/fonts/local-fallback.ts +249 -0
- package/src/fonts/local.ts +14 -1
- package/src/fonts/pipeline.ts +6 -3
- package/src/fonts/sfnt.ts +185 -0
- package/src/fonts/transform.ts +4 -1
- package/src/fonts/types.ts +29 -0
- package/src/plugins/build-manifest.ts +1 -1
- package/src/plugins/fonts.ts +28 -2
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
import type { Plugin } from 'vite';
|
|
19
19
|
import type { PluginContext } from '../plugin-context.ts';
|
|
20
20
|
import { type BuildManifest } from '../server/build-manifest.ts';
|
|
21
|
+
import type { SegmentNode, RouteFile } from '../routing/types.ts';
|
|
21
22
|
interface OutputChunk {
|
|
22
23
|
type: 'chunk';
|
|
23
24
|
fileName: string;
|
|
@@ -73,6 +74,10 @@ export declare function parseViteManifest(viteManifest: Record<string, ViteManif
|
|
|
73
74
|
* Keys are input file paths relative to root.
|
|
74
75
|
*/
|
|
75
76
|
export declare function buildManifestFromBundle(bundle: OutputBundle, base: string, root: string): BuildManifest;
|
|
77
|
+
/**
|
|
78
|
+
* Collect all route file paths (layout, page) from the route tree.
|
|
79
|
+
*/
|
|
80
|
+
export declare function collectRouteFilePaths(node: SegmentNode<RouteFile>): string[];
|
|
76
81
|
/**
|
|
77
82
|
* Create the timber-build-manifest Vite plugin.
|
|
78
83
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-manifest.d.ts","sourceRoot":"","sources":["../../src/plugins/build-manifest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAIH,OAAO,KAAK,EAAE,MAAM,EAAkB,MAAM,MAAM,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"build-manifest.d.ts","sourceRoot":"","sources":["../../src/plugins/build-manifest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAIH,OAAO,KAAK,EAAE,MAAM,EAAkB,MAAM,MAAM,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACvF,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAIlE,UAAU,WAAW;IACnB,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;KAAE,CAAC;IAC7C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,cAAc,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC3E;AAED,UAAU,WAAW;IACnB,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,KAAK,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,WAAW,GAAG,WAAW,CAAC,CAAC;AAK9D;;;GAGG;AACH,UAAU,iBAAiB;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,EAAE,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACpB;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,EAC/C,IAAI,EAAE,MAAM,GACX,aAAa,CAmBf;AAqCD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,YAAY,EACpB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,GACX,aAAa,CA0Cf;AAgED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,WAAW,CAAC,SAAS,CAAC,GAAG,MAAM,EAAE,CAO5E;AAuDD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAqI9D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fonts.d.ts","sourceRoot":"","sources":["../../src/plugins/fonts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,EAAE,MAAM,EAAiC,MAAM,MAAM,CAAC;AAClE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"fonts.d.ts","sourceRoot":"","sources":["../../src/plugins/fonts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,EAAE,MAAM,EAAiC,MAAM,MAAM,CAAC;AAClE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAiCjE,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,GACzB,MAAM,uBAAuB,CAAC;AAE/B;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,+DAA+D;IAC/D,kBAAkB,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI,CAAC;IAClD;;;OAGG;IACH,aAAa,IAAI,MAAM,EAAE,CAAC;CAC3B;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,GAAG;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,CAoRhF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@timber-js/app",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.248",
|
|
4
4
|
"description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare-workers",
|
package/src/fonts/ast.ts
CHANGED
|
@@ -299,6 +299,17 @@ function extractGoogleConfig(objNode: ObjectExpressionNode): GoogleFontConfig {
|
|
|
299
299
|
return config;
|
|
300
300
|
}
|
|
301
301
|
|
|
302
|
+
function isAdjustFontFallback(
|
|
303
|
+
value: boolean | string | undefined
|
|
304
|
+
): value is NonNullable<LocalFontConfig['adjustFontFallback']> {
|
|
305
|
+
return (
|
|
306
|
+
typeof value === 'boolean' ||
|
|
307
|
+
value === 'Arial' ||
|
|
308
|
+
value === 'Times New Roman' ||
|
|
309
|
+
value === 'monospace'
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
302
313
|
/** Shared implementation for LocalFontConfig extraction from an object node. */
|
|
303
314
|
function extractLocalConfig(objNode: ObjectExpressionNode): LocalFontConfig | null {
|
|
304
315
|
const props = objectProperties(objNode);
|
|
@@ -314,12 +325,34 @@ function extractLocalConfig(objNode: ObjectExpressionNode): LocalFontConfig | nu
|
|
|
314
325
|
const familyNode = props.get('family');
|
|
315
326
|
const family = familyNode ? extractString(familyNode) : undefined;
|
|
316
327
|
|
|
328
|
+
// Optional options: present-but-not-static is a hard failure (the caller
|
|
329
|
+
// reports it), never a silent default.
|
|
330
|
+
const options: Pick<LocalFontConfig, 'preload' | 'adjustFontFallback' | 'fallback'> = {};
|
|
331
|
+
const preloadNode = props.get('preload');
|
|
332
|
+
if (preloadNode) {
|
|
333
|
+
const b = extractBoolean(preloadNode);
|
|
334
|
+
if (b === undefined) return null;
|
|
335
|
+
options.preload = b;
|
|
336
|
+
}
|
|
337
|
+
const adjustNode = props.get('adjustFontFallback');
|
|
338
|
+
if (adjustNode) {
|
|
339
|
+
const value = extractBoolean(adjustNode) ?? extractString(adjustNode);
|
|
340
|
+
if (!isAdjustFontFallback(value)) return null;
|
|
341
|
+
options.adjustFontFallback = value;
|
|
342
|
+
}
|
|
343
|
+
const fallbackNode = props.get('fallback');
|
|
344
|
+
if (fallbackNode) {
|
|
345
|
+
const list = extractStringArray(fallbackNode);
|
|
346
|
+
if (!list) return null;
|
|
347
|
+
options.fallback = list;
|
|
348
|
+
}
|
|
349
|
+
|
|
317
350
|
const srcNode = props.get('src');
|
|
318
351
|
if (!srcNode) return null;
|
|
319
352
|
|
|
320
353
|
const srcString = extractString(srcNode);
|
|
321
354
|
if (srcString !== undefined) {
|
|
322
|
-
return { src: srcString, display, variable, family };
|
|
355
|
+
return { src: srcString, display, variable, family, ...options };
|
|
323
356
|
}
|
|
324
357
|
|
|
325
358
|
if (srcNode.type === 'ArrayExpression') {
|
|
@@ -331,7 +364,7 @@ function extractLocalConfig(objNode: ObjectExpressionNode): LocalFontConfig | nu
|
|
|
331
364
|
entries.push(entry);
|
|
332
365
|
}
|
|
333
366
|
if (entries.length === 0) return null;
|
|
334
|
-
return { src: entries, display, variable, family };
|
|
367
|
+
return { src: entries, display, variable, family, ...options };
|
|
335
368
|
}
|
|
336
369
|
|
|
337
370
|
return null;
|
package/src/fonts/bundle.ts
CHANGED
|
@@ -89,50 +89,104 @@ export function emitFontAssets(
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
/**
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
* `filePath` values (which are absolute) and is consistent with how
|
|
95
|
-
* `buildManifest.css` keys work after TIM-1014.
|
|
92
|
+
* Map each font importer to the route files (layouts and pages) that
|
|
93
|
+
* import it, directly or through any chain of modules.
|
|
96
94
|
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
95
|
+
* A font is usually defined in a shared module (`app/fonts.ts`) and applied
|
|
96
|
+
* in a layout that imports it. The manifest is read per matched route
|
|
97
|
+
* segment (`collectRouteFonts`), so an entry keyed only by the defining
|
|
98
|
+
* module would never be found. Walking *up* the importer graph from each
|
|
99
|
+
* font module is cheap — there are a handful of font modules, and the walk
|
|
100
|
+
* stops at modules already visited.
|
|
101
|
+
*
|
|
102
|
+
* `getImporters` is Rollup's `getModuleInfo(id)?.importers` from the RSC
|
|
103
|
+
* build, where layouts and pages are real modules. A route file reached
|
|
104
|
+
* through another route file (a page importing a layout's module) still
|
|
105
|
+
* counts: the font is in that page's graph.
|
|
106
|
+
*/
|
|
107
|
+
export function mapFontImportersToRoutes(
|
|
108
|
+
importers: Iterable<string>,
|
|
109
|
+
routeFiles: Iterable<string>,
|
|
110
|
+
getImporters: (id: string) => readonly string[] | null | undefined
|
|
111
|
+
): Map<string, string[]> {
|
|
112
|
+
const routeSet = new Set(routeFiles);
|
|
113
|
+
const result = new Map<string, string[]>();
|
|
114
|
+
for (const importer of importers) {
|
|
115
|
+
const routes: string[] = [];
|
|
116
|
+
const visited = new Set<string>([importer]);
|
|
117
|
+
const queue = [importer];
|
|
118
|
+
while (queue.length > 0) {
|
|
119
|
+
const id = queue.shift()!;
|
|
120
|
+
if (routeSet.has(id)) routes.push(id);
|
|
121
|
+
for (const parent of getImporters(id) ?? []) {
|
|
122
|
+
if (visited.has(parent)) continue;
|
|
123
|
+
visited.add(parent);
|
|
124
|
+
queue.push(parent);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
result.set(importer, routes);
|
|
128
|
+
}
|
|
129
|
+
return result;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Only upright faces are preloaded — italics are rarely above the fold. */
|
|
133
|
+
const isUpright = (style: string | undefined) => style === undefined || style === 'normal';
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Populate `buildManifest.fonts` with the font binaries to preload, keyed
|
|
137
|
+
* by absolute path. The keys are the font's importer plus every route file
|
|
138
|
+
* that reaches it (`routesByImporter`, from `mapFontImportersToRoutes`), so
|
|
139
|
+
* `collectRouteFonts` finds a font defined outside the layout that applies
|
|
140
|
+
* it. Keys are absolute, matching the route manifest's `filePath` values
|
|
141
|
+
* (and `buildManifest.css`, TIM-1014).
|
|
142
|
+
*
|
|
143
|
+
* Fonts with `preload: false` and non-upright faces are left out. All
|
|
144
|
+
* hrefs are content-hashed and prefixed with Vite's resolved `base`.
|
|
100
145
|
*/
|
|
101
146
|
export function writeFontManifest(
|
|
102
147
|
pipeline: FontPipeline,
|
|
103
148
|
buildManifest: BuildManifest,
|
|
104
|
-
base = '/'
|
|
149
|
+
base = '/',
|
|
150
|
+
routesByImporter?: ReadonlyMap<string, readonly string[]>
|
|
105
151
|
): void {
|
|
106
152
|
const urlPrefix = fontUrlPrefix(base);
|
|
107
|
-
const
|
|
153
|
+
const fontsByKey = new Map<string, Map<string, ManifestFontEntry>>();
|
|
108
154
|
|
|
109
155
|
for (const entry of pipeline.entries()) {
|
|
110
|
-
|
|
156
|
+
if (entry.preload === false) continue;
|
|
157
|
+
const preloads: ManifestFontEntry[] = [];
|
|
111
158
|
|
|
112
159
|
if (entry.provider === 'local' && entry.localSources) {
|
|
113
160
|
for (const src of entry.localSources) {
|
|
161
|
+
if (!isUpright(src.style)) continue;
|
|
114
162
|
const filename = src.hashedBasename ?? fontOutputBasename(src.path);
|
|
115
|
-
|
|
116
|
-
manifestEntries.push({
|
|
163
|
+
preloads.push({
|
|
117
164
|
href: `${urlPrefix}/${filename}`,
|
|
118
|
-
format,
|
|
165
|
+
format: inferFontFormat(src.path),
|
|
119
166
|
crossOrigin: 'anonymous',
|
|
120
167
|
});
|
|
121
168
|
}
|
|
122
169
|
} else if (entry.cachedFiles) {
|
|
123
170
|
for (const cf of entry.cachedFiles) {
|
|
124
|
-
|
|
171
|
+
if (!isUpright(cf.face.style)) continue;
|
|
172
|
+
preloads.push({
|
|
125
173
|
href: `${urlPrefix}/${cf.hashedFilename}`,
|
|
126
174
|
format: 'woff2',
|
|
127
175
|
crossOrigin: 'anonymous',
|
|
128
176
|
});
|
|
129
177
|
}
|
|
130
178
|
}
|
|
179
|
+
if (preloads.length === 0) continue;
|
|
131
180
|
|
|
132
|
-
|
|
181
|
+
const keys = new Set([entry.importer, ...(routesByImporter?.get(entry.importer) ?? [])]);
|
|
182
|
+
for (const key of keys) {
|
|
183
|
+
const byHref = fontsByKey.get(key) ?? new Map<string, ManifestFontEntry>();
|
|
184
|
+
for (const preload of preloads) byHref.set(preload.href, preload);
|
|
185
|
+
fontsByKey.set(key, byHref);
|
|
186
|
+
}
|
|
133
187
|
}
|
|
134
188
|
|
|
135
|
-
for (const [
|
|
136
|
-
buildManifest.fonts[
|
|
189
|
+
for (const [key, byHref] of fontsByKey) {
|
|
190
|
+
buildManifest.fonts[key] = [...byHref.values()];
|
|
137
191
|
}
|
|
138
192
|
}
|
package/src/fonts/fallbacks.ts
CHANGED
|
@@ -5,9 +5,15 @@
|
|
|
5
5
|
* `size-adjust`, `ascent-override`, `descent-override`, and
|
|
6
6
|
* `line-gap-override` to match custom font metrics and eliminate CLS.
|
|
7
7
|
*
|
|
8
|
+
* Google fonts use the precomputed `FALLBACK_METRICS` table below. Local
|
|
9
|
+
* fonts compute their faces from the font file (`local-fallback.ts`); both
|
|
10
|
+
* paths produce `FallbackFace` values serialized by `generateFallbackFaceCss`.
|
|
11
|
+
*
|
|
8
12
|
* Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
|
|
9
13
|
*/
|
|
10
14
|
|
|
15
|
+
import type { FontCategory } from './font-metrics.ts';
|
|
16
|
+
|
|
11
17
|
/**
|
|
12
18
|
* Font metrics for size-adjusted fallback calculation.
|
|
13
19
|
*
|
|
@@ -158,7 +164,8 @@ const SERIF_FAMILIES = new Set([
|
|
|
158
164
|
'cormorant garamond',
|
|
159
165
|
]);
|
|
160
166
|
|
|
161
|
-
|
|
167
|
+
/** Guess a family's generic category from its name alone. */
|
|
168
|
+
export function getGenericFamily(family: string): FontCategory {
|
|
162
169
|
const lc = family.toLowerCase();
|
|
163
170
|
if (lc.includes('mono') || lc.includes('code')) return 'monospace';
|
|
164
171
|
if ((lc.includes('serif') && !lc.includes('sans')) || SERIF_FAMILIES.has(lc)) {
|
|
@@ -167,59 +174,116 @@ export function getGenericFamily(family: string): string {
|
|
|
167
174
|
return 'sans-serif';
|
|
168
175
|
}
|
|
169
176
|
|
|
177
|
+
// ─── Fallback faces ──────────────────────────────────────────────────────
|
|
178
|
+
|
|
170
179
|
/**
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
* This produces a complete @font-face block with override descriptors
|
|
174
|
-
* that FontFaceDescriptor doesn't natively support.
|
|
180
|
+
* One size-adjusted fallback `@font-face`. Percentages are final CSS values
|
|
181
|
+
* (e.g. `107.64` → `size-adjust: 107.64%`).
|
|
175
182
|
*/
|
|
176
|
-
export
|
|
177
|
-
|
|
178
|
-
|
|
183
|
+
export interface FallbackFace {
|
|
184
|
+
/** `'<Family> Fallback'`. */
|
|
185
|
+
family: string;
|
|
186
|
+
/** System fonts tried in order, as `local()` sources. */
|
|
187
|
+
local: string[];
|
|
188
|
+
/** `font-weight` descriptor. Omitted for the regular face (defaults to normal). */
|
|
189
|
+
weight?: string;
|
|
190
|
+
sizeAdjust: number;
|
|
191
|
+
ascentOverride: number;
|
|
192
|
+
descentOverride: number;
|
|
193
|
+
lineGapOverride: number;
|
|
194
|
+
}
|
|
179
195
|
|
|
180
|
-
|
|
196
|
+
/** The fallback family name for `family`. */
|
|
197
|
+
export function fallbackFamilyName(family: string): string {
|
|
198
|
+
return `${family} Fallback`;
|
|
199
|
+
}
|
|
181
200
|
|
|
201
|
+
/** Serialize a fallback face to an `@font-face` rule. */
|
|
202
|
+
export function generateFallbackFaceCss(face: FallbackFace): string {
|
|
182
203
|
const lines = [
|
|
183
204
|
'@font-face {',
|
|
184
|
-
` font-family: '${
|
|
185
|
-
` src: local('${
|
|
186
|
-
` size-adjust: ${metrics.sizeAdjust}%;`,
|
|
187
|
-
` ascent-override: ${metrics.ascentOverride}%;`,
|
|
188
|
-
` descent-override: ${metrics.descentOverride}%;`,
|
|
189
|
-
` line-gap-override: ${metrics.lineGapOverride}%;`,
|
|
190
|
-
'}',
|
|
205
|
+
` font-family: '${face.family}';`,
|
|
206
|
+
` src: ${face.local.map((name) => `local('${name}')`).join(', ')};`,
|
|
191
207
|
];
|
|
192
|
-
|
|
208
|
+
if (face.weight) lines.push(` font-weight: ${face.weight};`);
|
|
209
|
+
lines.push(
|
|
210
|
+
` size-adjust: ${face.sizeAdjust}%;`,
|
|
211
|
+
` ascent-override: ${face.ascentOverride}%;`,
|
|
212
|
+
` descent-override: ${face.descentOverride}%;`,
|
|
213
|
+
` line-gap-override: ${face.lineGapOverride}%;`,
|
|
214
|
+
'}'
|
|
215
|
+
);
|
|
193
216
|
return lines.join('\n');
|
|
194
217
|
}
|
|
195
218
|
|
|
196
219
|
/**
|
|
197
|
-
*
|
|
220
|
+
* The fallback faces for a Google font, from the precomputed table. Empty
|
|
221
|
+
* when the family isn't in the table.
|
|
198
222
|
*/
|
|
223
|
+
export function googleFallbackFaces(family: string): FallbackFace[] {
|
|
224
|
+
const metrics = FALLBACK_METRICS[family.toLowerCase()];
|
|
225
|
+
if (!metrics) return [];
|
|
226
|
+
return [
|
|
227
|
+
{
|
|
228
|
+
family: fallbackFamilyName(family),
|
|
229
|
+
local: [metrics.fallbackFont],
|
|
230
|
+
sizeAdjust: metrics.sizeAdjust,
|
|
231
|
+
ascentOverride: metrics.ascentOverride,
|
|
232
|
+
descentOverride: metrics.descentOverride,
|
|
233
|
+
lineGapOverride: metrics.lineGapOverride,
|
|
234
|
+
},
|
|
235
|
+
];
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Check whether the Google fallback table has metrics for a family. */
|
|
199
239
|
export function hasFallbackMetrics(family: string): boolean {
|
|
200
240
|
return family.toLowerCase() in FALLBACK_METRICS;
|
|
201
241
|
}
|
|
202
242
|
|
|
243
|
+
/**
|
|
244
|
+
* Generate the fallback `@font-face` CSS for a Google font, or `null` when
|
|
245
|
+
* the family isn't in the table.
|
|
246
|
+
*/
|
|
247
|
+
export function generateFallbackCss(family: string): string | null {
|
|
248
|
+
const faces = googleFallbackFaces(family);
|
|
249
|
+
return faces.length > 0 ? faces.map(generateFallbackFaceCss).join('\n\n') : null;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ─── Font stack ──────────────────────────────────────────────────────────
|
|
253
|
+
|
|
254
|
+
export interface FontStackOptions {
|
|
255
|
+
/** Generic family. Defaults to the name heuristic (`getGenericFamily`). */
|
|
256
|
+
generic?: FontCategory;
|
|
257
|
+
/** Whether a `'<Family> Fallback'` face exists. Defaults to the Google table. */
|
|
258
|
+
hasFallbackFace?: boolean;
|
|
259
|
+
/**
|
|
260
|
+
* Replaces the default generic tail (`system-ui, sans-serif`, etc.) —
|
|
261
|
+
* the `fallback` option of `next/font`. Entries are emitted verbatim.
|
|
262
|
+
*/
|
|
263
|
+
fallback?: string[];
|
|
264
|
+
}
|
|
265
|
+
|
|
203
266
|
/**
|
|
204
267
|
* Build the full font stack string for a font, including its
|
|
205
268
|
* size-adjusted fallback and a generic family.
|
|
206
269
|
*
|
|
207
270
|
* Example: `'Inter', 'Inter Fallback', system-ui, sans-serif`
|
|
208
271
|
*/
|
|
209
|
-
export function buildFontStack(family: string): string {
|
|
210
|
-
const generic = getGenericFamily(family);
|
|
211
|
-
const
|
|
272
|
+
export function buildFontStack(family: string, options: FontStackOptions = {}): string {
|
|
273
|
+
const generic = options.generic ?? getGenericFamily(family);
|
|
274
|
+
const hasFallbackFace = options.hasFallbackFace ?? hasFallbackMetrics(family);
|
|
212
275
|
|
|
213
276
|
const parts = [`'${family}'`];
|
|
214
|
-
if (
|
|
277
|
+
if (hasFallbackFace) parts.push(`'${fallbackFamilyName(family)}'`);
|
|
215
278
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
parts.push('
|
|
279
|
+
if (options.fallback) {
|
|
280
|
+
parts.push(...options.fallback);
|
|
281
|
+
} else {
|
|
282
|
+
// system-ui for sans-serif fonts, ui-monospace for mono
|
|
283
|
+
if (generic === 'monospace') parts.push('ui-monospace');
|
|
284
|
+
else if (generic === 'sans-serif') parts.push('system-ui');
|
|
285
|
+
parts.push(generic);
|
|
221
286
|
}
|
|
222
|
-
parts.push(generic);
|
|
223
287
|
|
|
224
288
|
return parts.join(', ');
|
|
225
289
|
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read the vertical and horizontal metrics a size-adjusted fallback needs
|
|
3
|
+
* from a font file (TTF / OTF / WOFF / WOFF2).
|
|
4
|
+
*
|
|
5
|
+
* Fields read:
|
|
6
|
+
*
|
|
7
|
+
* - `head.unitsPerEm`
|
|
8
|
+
* - ascent / descent / lineGap — from `hhea`, or from `OS/2` sTypo* when
|
|
9
|
+
* `fsSelection` bit 7 (USE_TYPO_METRICS) is set, which is what browsers
|
|
10
|
+
* do with such fonts
|
|
11
|
+
* - `OS/2.xAvgCharWidth`, and the advance widths of a letter-frequency
|
|
12
|
+
* weighted Latin sample (`cmap` → glyph id → `hmtx`), the same sample
|
|
13
|
+
* Next.js's `adjustFontFallback` and capsize use
|
|
14
|
+
* - whether the font is monospace: `post.isFixedPitch`, `OS/2` PANOSE
|
|
15
|
+
* proportion = monospaced, or every sampled glyph sharing one advance
|
|
16
|
+
* - whether it is serif or sans, from PANOSE / IBM font class, when the
|
|
17
|
+
* font declares it
|
|
18
|
+
*
|
|
19
|
+
* Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { readSfntTables } from './sfnt.ts';
|
|
23
|
+
|
|
24
|
+
/** The generic CSS family a font belongs to. */
|
|
25
|
+
export type FontCategory = 'sans-serif' | 'serif' | 'monospace';
|
|
26
|
+
|
|
27
|
+
export interface FontMetrics {
|
|
28
|
+
unitsPerEm: number;
|
|
29
|
+
/** Positive, in font units. */
|
|
30
|
+
ascent: number;
|
|
31
|
+
/** Positive (distance below the baseline), in font units. */
|
|
32
|
+
descent: number;
|
|
33
|
+
lineGap: number;
|
|
34
|
+
/** `OS/2.xAvgCharWidth`, or `undefined` when the table is absent / zero. */
|
|
35
|
+
xAvgCharWidth?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Mean advance of `AVG_WIDTH_SAMPLE` in font units, or `undefined` when
|
|
38
|
+
* the font lacks a sampled character or its `hmtx` is unreadable.
|
|
39
|
+
*/
|
|
40
|
+
sampleAvgWidth?: number;
|
|
41
|
+
/** True for fixed-pitch fonts. */
|
|
42
|
+
monospace: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* `serif` / `sans-serif` when the font's PANOSE or IBM class says so;
|
|
45
|
+
* `undefined` when it does not (caller falls back to a name heuristic).
|
|
46
|
+
*/
|
|
47
|
+
declaredCategory?: 'serif' | 'sans-serif';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Letter-frequency weighted Latin sample, with spaces for word length.
|
|
52
|
+
* Identical to Next.js's `calcAverageWidth` (packages/font/src/local/
|
|
53
|
+
* get-fallback-metrics-from-font-file.ts) so the reference widths of the
|
|
54
|
+
* fallback bases are comparable.
|
|
55
|
+
*/
|
|
56
|
+
export const AVG_WIDTH_SAMPLE = 'aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ';
|
|
57
|
+
|
|
58
|
+
/** Characters whose advances must all match for a font to count as monospace. */
|
|
59
|
+
const MONO_PROBE = 'abcdefghijklmnopqrstuvwxyz0123456789 ';
|
|
60
|
+
|
|
61
|
+
const TABLES = ['head', 'hhea', 'OS/2', 'post', 'cmap', 'hmtx'] as const;
|
|
62
|
+
|
|
63
|
+
/** Parse metrics from font bytes. `null` when the file can't be read. */
|
|
64
|
+
export function readFontMetrics(data: Uint8Array): FontMetrics | null {
|
|
65
|
+
const tables = readSfntTables(data, TABLES);
|
|
66
|
+
if (!tables) return null;
|
|
67
|
+
const head = tables.get('head');
|
|
68
|
+
const hhea = tables.get('hhea');
|
|
69
|
+
if (!head || !hhea || head.byteLength < 54 || hhea.byteLength < 36) return null;
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const unitsPerEm = head.getUint16(18);
|
|
73
|
+
if (unitsPerEm === 0) return null;
|
|
74
|
+
|
|
75
|
+
let ascent = hhea.getInt16(4);
|
|
76
|
+
let descent = hhea.getInt16(6);
|
|
77
|
+
let lineGap = hhea.getInt16(8);
|
|
78
|
+
const numberOfHMetrics = hhea.getUint16(34);
|
|
79
|
+
|
|
80
|
+
const os2 = tables.get('OS/2');
|
|
81
|
+
let xAvgCharWidth: number | undefined;
|
|
82
|
+
let declaredCategory: FontMetrics['declaredCategory'];
|
|
83
|
+
let panoseMono = false;
|
|
84
|
+
if (os2 && os2.byteLength >= 78) {
|
|
85
|
+
const avg = os2.getInt16(2);
|
|
86
|
+
if (avg > 0) xAvgCharWidth = avg;
|
|
87
|
+
const fsSelection = os2.getUint16(62);
|
|
88
|
+
if (fsSelection & (1 << 7)) {
|
|
89
|
+
ascent = os2.getInt16(68);
|
|
90
|
+
descent = os2.getInt16(70);
|
|
91
|
+
lineGap = os2.getInt16(72);
|
|
92
|
+
}
|
|
93
|
+
const panose = (i: number) => os2.getUint8(32 + i);
|
|
94
|
+
// PANOSE family kind 2 = Latin Text; only then do the digits below
|
|
95
|
+
// mean serif style (byte 1) and proportion (byte 3).
|
|
96
|
+
if (panose(0) === 2) {
|
|
97
|
+
const serifStyle = panose(1);
|
|
98
|
+
if (serifStyle >= 2 && serifStyle <= 10) declaredCategory = 'serif';
|
|
99
|
+
else if (serifStyle >= 11 && serifStyle <= 13) declaredCategory = 'sans-serif';
|
|
100
|
+
panoseMono = panose(3) === 9;
|
|
101
|
+
}
|
|
102
|
+
if (!declaredCategory) {
|
|
103
|
+
// IBM font class (high byte of sFamilyClass): 1–5 and 7 are serif
|
|
104
|
+
// classes, 8 is sans serif.
|
|
105
|
+
const ibmClass = os2.getInt16(30) >> 8;
|
|
106
|
+
if ((ibmClass >= 1 && ibmClass <= 5) || ibmClass === 7) declaredCategory = 'serif';
|
|
107
|
+
else if (ibmClass === 8) declaredCategory = 'sans-serif';
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const post = tables.get('post');
|
|
112
|
+
const isFixedPitch = post !== undefined && post.byteLength >= 16 && post.getUint32(12) !== 0;
|
|
113
|
+
|
|
114
|
+
const advanceOf = buildAdvanceLookup(tables.get('cmap'), tables.get('hmtx'), numberOfHMetrics);
|
|
115
|
+
const sampleAvgWidth = advanceOf ? averageAdvance(AVG_WIDTH_SAMPLE, advanceOf) : undefined;
|
|
116
|
+
const sameAdvance = advanceOf ? allSameAdvance(MONO_PROBE, advanceOf) : false;
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
unitsPerEm,
|
|
120
|
+
ascent,
|
|
121
|
+
descent: Math.abs(descent),
|
|
122
|
+
lineGap,
|
|
123
|
+
xAvgCharWidth,
|
|
124
|
+
sampleAvgWidth,
|
|
125
|
+
monospace: isFixedPitch || panoseMono || sameAdvance,
|
|
126
|
+
declaredCategory,
|
|
127
|
+
};
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
type AdvanceLookup = (codePoint: number) => number | undefined;
|
|
134
|
+
|
|
135
|
+
function averageAdvance(sample: string, advanceOf: AdvanceLookup): number | undefined {
|
|
136
|
+
let total = 0;
|
|
137
|
+
for (const ch of sample) {
|
|
138
|
+
const advance = advanceOf(ch.codePointAt(0)!);
|
|
139
|
+
if (advance === undefined) return undefined;
|
|
140
|
+
total += advance;
|
|
141
|
+
}
|
|
142
|
+
return total / sample.length;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function allSameAdvance(sample: string, advanceOf: AdvanceLookup): boolean {
|
|
146
|
+
let first: number | undefined;
|
|
147
|
+
for (const ch of sample) {
|
|
148
|
+
const advance = advanceOf(ch.codePointAt(0)!);
|
|
149
|
+
if (advance === undefined) return false;
|
|
150
|
+
if (first === undefined) first = advance;
|
|
151
|
+
else if (advance !== first) return false;
|
|
152
|
+
}
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Code point → advance width, via `cmap` and `hmtx`. */
|
|
157
|
+
function buildAdvanceLookup(
|
|
158
|
+
cmap: DataView | undefined,
|
|
159
|
+
hmtx: DataView | undefined,
|
|
160
|
+
numberOfHMetrics: number
|
|
161
|
+
): AdvanceLookup | null {
|
|
162
|
+
if (!cmap || !hmtx || numberOfHMetrics === 0) return null;
|
|
163
|
+
if (hmtx.byteLength < numberOfHMetrics * 4) return null;
|
|
164
|
+
const glyphOf = buildGlyphLookup(cmap);
|
|
165
|
+
if (!glyphOf) return null;
|
|
166
|
+
return (codePoint) => {
|
|
167
|
+
const gid = glyphOf(codePoint);
|
|
168
|
+
if (!gid) return undefined; // 0 is .notdef — the character is missing
|
|
169
|
+
// Glyphs past numberOfHMetrics share the last advance (monospace tail).
|
|
170
|
+
const index = Math.min(gid, numberOfHMetrics - 1);
|
|
171
|
+
return hmtx.getUint16(index * 4);
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Pick a Unicode `cmap` subtable (format 4 or 12) and return a lookup.
|
|
177
|
+
* Preference: (3,10) / (0,4+) full repertoire, then (3,1) / (0,x) BMP.
|
|
178
|
+
*/
|
|
179
|
+
function buildGlyphLookup(cmap: DataView): ((codePoint: number) => number) | null {
|
|
180
|
+
const numSubtables = cmap.getUint16(2);
|
|
181
|
+
let best: { offset: number; rank: number } | null = null;
|
|
182
|
+
for (let i = 0; i < numSubtables; i++) {
|
|
183
|
+
const rec = 4 + i * 8;
|
|
184
|
+
const platform = cmap.getUint16(rec);
|
|
185
|
+
const encoding = cmap.getUint16(rec + 2);
|
|
186
|
+
const offset = cmap.getUint32(rec + 4);
|
|
187
|
+
if (offset + 4 > cmap.byteLength) continue;
|
|
188
|
+
const format = cmap.getUint16(offset);
|
|
189
|
+
if (format !== 4 && format !== 12) continue;
|
|
190
|
+
const unicode = platform === 0 || (platform === 3 && (encoding === 1 || encoding === 10));
|
|
191
|
+
if (!unicode) continue;
|
|
192
|
+
const rank = format === 12 ? 2 : 1;
|
|
193
|
+
if (!best || rank > best.rank) best = { offset, rank };
|
|
194
|
+
}
|
|
195
|
+
if (!best) return null;
|
|
196
|
+
const offset = best.offset;
|
|
197
|
+
return cmap.getUint16(offset) === 12 ? cmapFormat12(cmap, offset) : cmapFormat4(cmap, offset);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function cmapFormat4(cmap: DataView, offset: number): (codePoint: number) => number {
|
|
201
|
+
const segCount = cmap.getUint16(offset + 6) / 2;
|
|
202
|
+
const endCodes = offset + 14;
|
|
203
|
+
const startCodes = endCodes + segCount * 2 + 2;
|
|
204
|
+
const idDeltas = startCodes + segCount * 2;
|
|
205
|
+
const idRangeOffsets = idDeltas + segCount * 2;
|
|
206
|
+
return (cp) => {
|
|
207
|
+
if (cp > 0xffff) return 0;
|
|
208
|
+
for (let s = 0; s < segCount; s++) {
|
|
209
|
+
if (cp > cmap.getUint16(endCodes + s * 2)) continue;
|
|
210
|
+
const start = cmap.getUint16(startCodes + s * 2);
|
|
211
|
+
if (cp < start) return 0;
|
|
212
|
+
const delta = cmap.getInt16(idDeltas + s * 2);
|
|
213
|
+
const rangeOffsetPos = idRangeOffsets + s * 2;
|
|
214
|
+
const rangeOffset = cmap.getUint16(rangeOffsetPos);
|
|
215
|
+
if (rangeOffset === 0) return (cp + delta) & 0xffff;
|
|
216
|
+
const glyphPos = rangeOffsetPos + rangeOffset + (cp - start) * 2;
|
|
217
|
+
if (glyphPos + 2 > cmap.byteLength) return 0;
|
|
218
|
+
const glyph = cmap.getUint16(glyphPos);
|
|
219
|
+
return glyph === 0 ? 0 : (glyph + delta) & 0xffff;
|
|
220
|
+
}
|
|
221
|
+
return 0;
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function cmapFormat12(cmap: DataView, offset: number): (codePoint: number) => number {
|
|
226
|
+
const numGroups = cmap.getUint32(offset + 12);
|
|
227
|
+
return (cp) => {
|
|
228
|
+
for (let g = 0; g < numGroups; g++) {
|
|
229
|
+
const rec = offset + 16 + g * 12;
|
|
230
|
+
const start = cmap.getUint32(rec);
|
|
231
|
+
const end = cmap.getUint32(rec + 4);
|
|
232
|
+
if (cp >= start && cp <= end) return cmap.getUint32(rec + 8) + (cp - start);
|
|
233
|
+
}
|
|
234
|
+
return 0;
|
|
235
|
+
};
|
|
236
|
+
}
|