waybetter/packages/runtime/src/fonts.ts
CRT 7568126f2b runtime + host: the theme engine (theme documents, choice catalog, page runtime, fonts; native theme state)
The site-independent theme engine moves from wayBetter for X into the framework:
- runtime/themeSpec.ts: theme document types, the schema's defaults (BASE_*), sanitizing,
  import, overrides, ensureContrast, font roles/stacks, font choices, backgrounds.
- runtime/themeChoice.ts: ThemeChoice and createThemeCatalog(builtins) (normalize, base,
  resolve, palette, all), choiceForId, serializeChoice.
- runtime/themeRuntime.ts: installThemeRuntime(win, site) (live CSS over the site's rules,
  --wb-* vars, site color mode, first-frame snapshot), collectRules, resolvedFonts.
- runtime/fonts.ts: bundled fonts and owner-downloaded Google Fonts from bytes.
- themeApi exports hexToRgb, mix and MONO_FAMILIES (one copy: themeTokens and themeSpec use them).
- host theme.rs: ThemeChoice/ThemeScopes over a site's ThemeSite (envelope checks against
  theme.schema.json, which theme a tab shows, page color, delivery script).
2026-09-29 06:07:59 +00:00

73 lines
4.5 KiB
TypeScript

// Theme fonts in a site's page. Sites usually block remote and `data:` font URLs (CSP `font-src`),
// but a FontFace built from bytes performs no fetch, so bundled families (Geist and Geist Mono: the
// app embeds their woff2 files in its page runtime) are registered only when a theme uses them, and
// Google Fonts the owner downloaded arrive as bytes from native code (`provideFonts`).
import { BUNDLED_FONTS } from './themeSpec.ts';
/** Unicode ranges of the Latin and Latin Extended subsets (@fontsource file names `latin`, `latin-ext`). */
export const LATIN_RANGE = 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD';
export const LATIN_EXT_RANGE = 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF';
/** A bundled family's files: base64 woff2 (variable, weights 100-900) with the unicode range each covers. */
export type BundledFontFiles = Record<string, Array<[base64: string, unicodeRange: string]>>;
const loaded = new WeakMap<Document, Set<string>>();
const log = (family: string, error: unknown) => console.error(`[wayBetter] font ${family} failed`, error);
/** Registers the bundled families `names` (BUNDLED_FONTS) from `files`, once per document. */
export function loadBundledFonts(doc: Document, names: string[], files: BundledFontFiles): void {
let done = loaded.get(doc);
if (!done) loaded.set(doc, done = new Set());
for (const name of names) {
const faces = files[name];
const family = BUNDLED_FONTS[name];
if (!faces || !family || done.has(name)) continue;
done.add(name);
for (const [base64, unicodeRange] of faces) {
const bytes = Uint8Array.from(atob(base64), char => char.charCodeAt(0));
const face = new FontFace(family, bytes.buffer, { weight: '100 900', style: 'normal', unicodeRange, display: 'swap' });
doc.fonts.add(face);
face.load().catch(error => log(name, error));
}
}
}
/**
* Google Fonts the owner downloaded: native code validates and caches the woff2 files and hands
* their bytes to site tabs whose theme uses them. The page never requests a font; each family is
* registered once per document (again only when its bytes change, e.g. after picking other weights).
*/
export type ProvidedFont = { family: string; faces: Array<{ weight: [number, number]; unicodeRange: string | null; data: string }> };
const provided = new WeakMap<Document, Map<string, string>>();
const FAMILY = /^[A-Za-z0-9][A-Za-z0-9 ]{0,47}$/;
/** Registers the provided families (validated again; at most 8 families of 24 faces); returns the families added. */
export function provideFonts(doc: Document, fonts: unknown): string[] {
const added: string[] = [];
if (!Array.isArray(fonts)) return added;
let known = provided.get(doc);
if (!known) provided.set(doc, known = new Map());
for (const font of fonts.slice(0, 8) as ProvidedFont[]) {
if (!font || typeof font.family !== 'string' || !FAMILY.test(font.family) || !Array.isArray(font.faces)) continue;
const key = font.faces.map(face => `${face?.weight}|${typeof face?.data === 'string' ? face.data.length : 0}`).join(',');
if (known.get(font.family) === key) continue;
// Other weights of a family replace its earlier faces.
for (const face of [...doc.fonts]) if ((face as FontFace).family.replace(/"/g, '') === font.family && (face as FontFace & { wbGoogle?: boolean }).wbGoogle) doc.fonts.delete(face as FontFace);
known.set(font.family, key);
for (const face of font.faces.slice(0, 24)) {
if (!face || typeof face.data !== 'string' || !Array.isArray(face.weight)) continue;
try {
const bytes = Uint8Array.from(atob(face.data), char => char.charCodeAt(0));
const [min, max] = face.weight.map(Number) as [number, number];
const descriptors: FontFaceDescriptors = { weight: min === max ? String(min) : `${min} ${max}`, style: 'normal', display: 'swap' };
if (typeof face.unicodeRange === 'string' && /^[U+0-9A-Fa-f?, -]{1,4000}$/.test(face.unicodeRange)) descriptors.unicodeRange = face.unicodeRange;
const fontFace = Object.assign(new FontFace(font.family, bytes.buffer, descriptors), { wbGoogle: true });
doc.fonts.add(fontFace);
fontFace.load().catch(error => log(font.family, error));
} catch (error) { log(font.family, error); }
}
added.push(font.family);
}
return added;
}