@nextgensoftwares/folio-fonts
HarfBuzz text measurer with CSS-style face matching and per-grapheme fallback. Guide: Fonts & measurement.
class FontEngine implements TextMeasurer
ts
interface FontEngineOptions {
fallback?: string[]; // families tried after the requested stack, e.g. ['Noto Sans Arabic']
cacheSize?: number; // max cached widths before the cache resets (default 100,000)
}
interface FontFaceInput {
family: string;
data: ArrayBuffer | Uint8Array;
style?: 'normal' | 'italic';
weight?: number | [number, number]; // default: the wght axis range, else OS/2 usWeightClass
}| Member | Signature | Description |
|---|---|---|
FontEngine.create | (options?: FontEngineOptions) => Promise<FontEngine> | loads HarfBuzz (once) and returns an engine |
addFont | (input: FontFaceInput) => LoadedFace | registers a face; clears width and stack caches |
width | (text, font: FontSpec) => number | advance width in px (cached), shaped with font.features, plus font.letterSpacing per grapheme cluster |
positions | (text, font) => number[] | px offset at every UTF-16 boundary, one shaping pass per run (features and letter spacing included) |
hasFeature | (font, tag: string) => boolean | whether the stack's primary face has an OpenType GSUB feature ('smcp', 'c2sc') |
metrics | (font) => { ascent; descent; lineGap } | primary face's ascent/descent/hhea line gap as fractions of the size (0.8 / 0.2 / 0 if none loaded) |
addAlias | (family, target) => void | family resolves to target's faces while it has none of its own (a stand-in: Verdana → DejaVu Sans) |
hasFamily | (family) => boolean | faces registered under family itself (aliases don't count) |
faceData | (family, weight?, style?) => Uint8Array | null | the font file of family's face (own or aliased) for that weight and style: the bytes layout measured, for exporters' fonts callback (faces keep their file: LoadedFace.data) |
singleLine | (family, weight?, style?) => number | undefined | single line height (ascent + descent + line gap, × size) of the face family resolves to, own or aliased: pass it to importers as lineMetrics |
runs | (text, font) => FaceRun[] | splits text into single-face runs (per-grapheme fallback); throws if no font is loaded for the stack |
shape | (run: FaceRun, weight: number, features?: string) => glyph infos and positions | raw HarfBuzz output in font units (for PDF writers) |
ts
interface FaceDescriptor { family: string; style: 'normal' | 'italic'; weightMin: number; weightMax: number }
interface LoadedFace extends FaceDescriptor {
id: number; face: HbFace; upem: number; variable: boolean; cmap: Set<number>;
ascent: number; descent: number; instances: Map<number, HbFont>;
}
interface FaceRun { face: LoadedFace; text: string; start: number } // start = UTF-16 offset in the measured stringText as outlines
engine.outline(text, font) / textOutline(engine, text, font) → OutlineCmd[] ({ op: 'M' | 'L' | 'Q' | 'C' | 'Z', p }): the glyph outlines of text shaped exactly as it is measured (face per run, kerning, ligatures, letter spacing), in px from the start of its baseline, y down. Layout uses it to draw WordArt warps; anything that needs text as paths can.
Office font stand-ins and lazy loading
| Export | Signature | Description |
|---|---|---|
OFFICE_FALLBACKS | Record<string, readonly string[]> | lower-case Office family → open stand-ins, best first: Times New Roman/Arial/Courier New → Liberation Serif/Sans/Mono, Calibri → Carlito, Cambria → Caladea, Georgia → Gelasio, Segoe UI → Selawik (metric-compatible); Verdana → DejaVu Sans, Tahoma → DejaVu Sans Condensed; Symbol/Wingdings → DejaVu Sans |
fontFallbacks | (family, table?) => readonly string[] | stand-ins for a family: the table's (table replaces the built-in one), else classFallbacks |
classifyFont, FONT_CLASSES, type FontClass | (family) => FontClass | null | a family's category (serif, sans, display, handwriting, mono) and width (condensed, normal, wide): popular Office and Google families by name, else from the name (Narrow/Condensed, Hand/Script/Marker, Serif, Mono...) |
classFallbacks | (family) => readonly string[] | open stand-ins of the same class and width, best first (a condensed handwriting font gets Amatic SC, Just Another Hand, Caveat, then narrow faces such as Liberation Sans Narrow and DejaVu Sans Condensed, never a wide sans) |
cssFontSource, type CssFontSourceOptions, type FetchLike | (opts) => LoadFamily | a host hook over a font CSS API (Google Fonts css2, or the host's proxy of it): cssUrl(family), fileUrl?(url), allowHosts (https only; relative proxy URLs allowed), fetch?, maxCssBytes? (512 KB), maxFontBytes? (5 MB), pick?. It keeps TrueType/OpenType files only (what the shaper reads) and checks the font signature. Folio core makes no network calls; hosts wire it in. |
parseFontFaceCss, latinFaces, type CssFontFace | @font-face rules of a stylesheet ({ url, weight, style, unicodeRange?, format? }, TrueType before WOFF2), and the Basic Latin face of each weight/style | |
createFontLoader | (opts: FontLoaderOptions) => FontLoader | loads only the families a document asks for, through the host's loadFamily hook; a family the host can't load gets the first stand-in it can (registered as an alias) |
FontLoaderOptions | { engine; loadFamily: LoadFamily; fallbacks?: (family) => readonly string[]; onFace?: (face, name) => void | Promise<void> } | onFace runs for every face under every name it draws (its own family, then each family it stands in for): register a browser FontFace there |
LoadFamily | (family) => Promise<readonly FontFaceInput[] | null> | the host's font source (bundle, CDN); called once per family |
FontLoader | { ensure(families): Promise<FontReport>; addFaces(faces): Promise<void> } | ensure takes names or CSS stacks (generic names skipped); addFaces registers a document's embedded faces first |
FontReport | { loaded: string[]; substituted: { family; with }[]; missing: string[] } | what ensure did |
FontRegistry | { addFont(input: FontFaceInput); addAlias(family, target); hasFamily(family): boolean } | the part of FontEngine the loader drives (FontLoaderOptions.engine); any object with these three methods works |
FontLoader.subscribe | (fn) => () => void | called after faces are registered (a family or stand-in became measurable): layouts made before are stale |
documentFamilies, contentFamilies | (doc, theme?) => Set<string>, (nodes, out?) => Set<string> | every family a document uses: theme body/mono/headings, block fontFamily, list marker fonts, textStyle marks, header/footer content (from folio-layout) |
ensureDocumentFonts | (loader, doc, theme) => Promise<FontReport> | loads documentFamilies(doc, theme): before layout, display or export |
fontLoaderSource, type FontLoaderSourceOptions | ({ loader, families?, groups?, label? }) => { list(query); load(family) } | a font picker source over a loader; load rejects when the family is missing |
engineFontBytes | (engine) => (font) => Uint8Array | null | export fonts from the engine the layout used (uploaded faces included) |
fontReportWarnings | (report) => string[] | one warning per substituted or missing family |
filterFontGroups, type FontEntry, type FontGroup | (groups, query) => FontGroup[] | font list data shared with the react picker |
Face matching
| Export | Signature | Description |
|---|---|---|
parseFamilyList | (value: string) => string[] | split a CSS font-family list, unquote, lowercase |
rankByWeight | <T extends FaceDescriptor>(faces: readonly T[], w: number) => T[] | CSS Fonts §5.2 weight fallback order |
matchFace | (faces, style, weight) => T | undefined | style first (italic ↔ normal fallback), then weight |
loadHarfBuzz | () => Promise<HarfBuzz> | lazy, single import('harfbuzzjs') (top-level-await WASM) |
Font files and static instances
| Export | Signature | Description |
|---|---|---|
fontFiles | (faces: readonly FaceFile[]) => (font: FontSpec) => Promise<Uint8Array | null> | a fonts callback (PDF and DOCX exporters) over font URLs: nearest weight/style, each file fetched once (fetch) |
FaceFile | { family; src; weight?: number | [number, number]; style? } | one font file |
bundledFontUrls, loadBundledFonts(fetch?) (entry @nextgensoftwares/folio-fonts/bundled) | () => { family, src, weight }[], (fetch?) => Promise<FontFaceInput[]> | the OFL faces this package ships (Geist, Noto Sans Arabic) by URL (literal new URL(…, import.meta.url), so bundlers emit them) and loaded: a last-resort font for exporters; faces that fail to load are left out |
loadFontInstancer | (wasm?: ArrayBuffer | Uint8Array | string | URL) => Promise<FontInstancer> | HarfBuzz's subsetter (harfbuzz-subset.wasm, shipped next to the build as @nextgensoftwares/folio-fonts/harfbuzz-subset.wasm; in Node it is found automatically) |
FontInstancer | { instance(font: Uint8Array, axes: Record<string, number>): Uint8Array | null } | a static instance of a variable font: axes pinned, every glyph and layout table kept |
renameFont | (font: Uint8Array, names: FontNames) => Uint8Array | new style-linked names (name IDs 1/2/4/6; legal strings and IDs 256+ that other tables reference are kept), OS/2 weight and fsSelection, head.macStyle; drops STAT; fresh checksums |
FontNames | { family: string; subfamily: 'Regular' | 'Bold' | 'Italic' | 'Bold Italic'; weight: number } | |
withLegacyKern | (font: Uint8Array) => Uint8Array | adds a format 0 kern table from the font's GPOS pair kerning (ASCII, then Latin-1, other Latin, Greek, Cyrillic pairs; at most 10,920), for readers that only kern with kern (GDI); the font itself when it already has one or has no such kerning |
sfntTable | (font: Uint8Array, tag: string) => DataView | null | a view of one table of a TrueType/OpenType file |
The DOCX exporter uses these to embed exactly the outlines and advances layout measured: Word draws embedded fonts through GDI, which can't apply variations.