Fonts & measurement
Layout never asks the browser how wide text is. It goes through an injected TextMeasurer, and production uses HarfBuzz (WASM) over the actual font files. This is what makes Folio's line breaks deterministic and lets the same layout run in Node for PDF export or server-side page counts.
The TextMeasurer contract
interface TextMeasurer {
width(text: string, font: FontSpec): number;
/** Ascent/descent as fractions of font size. Defaults to 0.8 / 0.2. */
metrics?(font: FontSpec): { ascent: number; descent: number };
/** px offset at every UTF-16 boundary of `text`, from one shaping pass. */
positions?(text: string, font: FontSpec): number[];
/** Whether the font's primary face has an OpenType feature ('smcp', 'c2sc'). */
hasFeature?(font: FontSpec, tag: string): boolean;
/** The family that renders most of `text` in `font` (the toolbar names it). */
familyFor?(font: FontSpec, text: string): string | null;
}
interface FontSpec {
family: string; // a CSS family list: 'Geist, Noto Sans Arabic'
size: number; // px
weight: number;
style: 'normal' | 'italic';
features?: string; // OpenType features to shape with: 'smcp', 'smcp,c2sc'
letterSpacing?: number; // px after every grapheme cluster (may be negative)
}A measurer must be pure: same input, same output. Layout caches by it. positions is optional but recommended: without it the editor measures text prefixes to place the caret, which is quadratic per line.
familyFor is optional too. FontEngine answers it with the same per-character face choice it measures with, so the toolbar's font field names the face that actually renders the selection (Noto Sans Arabic for Arabic text in a Geist, Noto Sans Arabic stack). Without it, the toolbar shows the first family of the stack that is not generic.
FontEngine
import { FontEngine } from '@nextgensoftwares/folio-fonts';
const engine = await FontEngine.create({ fallback: ['Noto Sans Arabic'] });
engine.addFont({ family: 'Geist', data: geistBytes }); // variable: wght axis read from the font
engine.addFont({ family: 'Noto Sans Arabic', data: arabicRegular });
engine.addFont({ family: 'Noto Sans Arabic', data: arabicBold }); // weight from OS/2 usWeightClass
engine.addFont({ family: 'My Serif', data: bytes, style: 'italic', weight: [300, 700] });
engine.width('Hello', { family: 'Geist', size: 16, weight: 400, style: 'normal' });FontEngine implements TextMeasurer (width, metrics, positions), so you pass it straight to layoutDocument and FolioEditor. HarfBuzz is loaded lazily and once (loadHarfBuzz()), keeping every other entry point synchronous.
How a face is chosen
The engine mirrors what a browser does:
- Family stack.
font.familyis parsed as a CSS list (parseFamilyList), then thefallbackfamilies are appended. - Style, then weight. Within a family,
matchFaceprefers the requested style (italic falls back to normal and vice versa), then ranks weights by CSS Fonts §5.2: inside a face's range is exact; for 400–500 try heavier up to 500, then lighter, then heavier; below 400 lighter first; above 500 heavier first (rankByWeight). - Per-grapheme fallback. If the primary face covers every code point, the text is one run (fast path, no segmentation). Otherwise each grapheme cluster goes to the first face in the stack that covers all its code points. Combining marks and joiners stick to the previous run, and spaces stay in the primary font, as Blink does. So
abc مرحبا xbecomesGeist "abc ",Noto Sans Arabic "مرحبا",Geist " x". - Variable fonts. Variable faces get an instance per requested weight (clamped to the axis range).
Line boxes
metrics(font) returns the primary face's ascent, descent and line gap (the first loaded family in the stack, or its alias), as CSS does for line boxes with a non-normal line-height. With theme.leading: 'below' (Word documents) the line box follows Word instead: the line gap sits above the text, a "multiple" line's extra height below it, an "at least" line puts the text at the bottom and an "exactly" line puts the baseline at 80% of the box; a run in a taller font grows the line to its own single height. Pass the same function to the view (<FolioView metrics>) so painted baselines land where layout put them.
Speed
- Widths are cached per (family, weight, style, text), up to
cacheSizeentries (default 100,000), then reset. - Layout measures segments between break opportunities and sums them, instead of reshaping whole lines.
- HarfBuzz buffers are reused across calls.
Missing fonts: stand-ins and lazy loading
Documents name fonts the host rarely has (a Word file in Verdana, Calibri, Times New Roman). Swapping them silently for the app's own font changes every line break, so @nextgensoftwares/folio-fonts resolves them in three steps:
- The family itself, from the host's
loadFamily(family)hook (a bundle, a font CDN, the document's embedded faces registered withaddFaces). - A stand-in from
fontFallbacks(family)(OFFICE_FALLBACKS): metric-compatible open fonts where they exist (Liberation Serif/Sans/Mono for Times New Roman/Arial/Courier New, Carlito for Calibri, Caladea for Cambria, Comic Relief for Comic Sans MS; same advance widths, so the same line breaks as Word), else the closest look-alike (DejaVu Sans for Verdana; Amiri, Noto Naskh Arabic and Noto Sans Arabic for Traditional Arabic, Simplified Arabic, Sakkal Majalla, Arabic Typesetting and Andalus). A stand-in is one family: Arabic text in a Latin family is drawn with that family's script stand-in when the host registers it (OFFICE_SCRIPT_FALLBACKS: Times New Roman, Arial and Courier New → Noto Naskh Arabic, then Amiri, as Word draws their own Naskh; Tahoma and Segoe UI → Noto Sans Arabic; the engine'sfallbackForreplaces the table), else from the engine'sfallbacklist.createFontLoaderfetches those stand-ins with the family (best effort, throughloadFamily; itsscriptFallbacksoption replaces the table,falseturns it off), so a lazy host loads Noto Naskh Arabic only for documents in Times New Roman. The stand-in is registered as an alias (engine.addAlias('Verdana', 'DejaVu Sans')): the document keeps its family names, the engine measures with the stand-in, andonFaceregisters the same bytes under the original name for drawing. - Missing: reported (
FontReport.missing), drawn with the engine'sfallback. Importers turn the report into one warning each for missing families and for stand-ins.
import { createFontLoader } from '@nextgensoftwares/folio-fonts';
const loader = createFontLoader({
engine,
loadFamily: async (family) => myCdn.faces(family), // [{ family, data, weight, style }] or null
onFace: async (face, name) => { // draw what layout measured
const f = new FontFace(name, face.data, { weight: String(face.weight ?? 400), style: face.style ?? 'normal' });
document.fonts.add(f);
await f.load();
},
});
const result = await importDocx(bytes, {
// Embedded faces first, then the styles' families (before conversion), then what runs used.
resolveFonts: async ({ used, embedded }) => {
await loader.addFaces(embedded);
return loader.ensure(used);
},
lineMetrics: (family) => engine.singleLine(family), // line boxes from the faces that draw
});Each family is fetched once, all four faces (regular, bold, italic, bold italic) when the source has them, so bold and italic text is never synthesized by the browser while HarfBuzz measured the regular face. Licences: Liberation, Carlito, Caladea (SIL OFL) and DejaVu (Bitstream Vera licence) allow bundling unmodified files with their licence text; the playground bundles them under public/fonts/office/.
One LoadFamily for every surface
A document stores only family names. Anything that shows or exports it must load those families first, uploaded ones included, so give every surface the same host function, LoadFamily = (family) => Promise<FontFaceInput[] | null> (built-in files, a Google-style CSS API through cssFontSource, or the host's uploaded-font library):
import { createFontLoader, ensureDocumentFonts, fontLoaderSource, engineFontBytes } from '@nextgensoftwares/folio-fonts';
const loadFamily = async (family) => (await myLibrary.faces(family)) ?? googleFonts(family);
const loader = createFontLoader({ engine, loadFamily, onFace: registerWithDocumentFonts });
// Editor: loads the document's families, and those of pasted or synced content; `fontsPending` meanwhile.
const app = createFolioApp({ doc, measurer: engine, fonts: { loader } });
// Reader: per chapter, before layout.
const fonts = readerFonts({ engine, loadFamily });
const layout = localLayout({ measurer: engine, theme }, { prepare: (doc, o) => fonts.prepare(doc, o.theme ?? theme) });
// Export (browser or Node): load, lay out, embed the faces layout measured with.
const report = await ensureDocumentFonts(loader, doc, theme);
const pdf = await exportPdf(layoutDocument(doc, { measurer: engine, theme }), {
shaper: engine, fonts: engineFontBytes(engine), fontReport: report, onWarning: console.warn,
});documentFamilies(doc, theme) lists what is loaded: the theme's body, mono and heading families, block fontFamily attributes, list marker fonts, textStyle marks and header/footer content. A family that can be neither loaded nor substituted is reported (FontReport.missing, and in exports a warning through onWarning), never silently swapped.
The font picker's source
fonts on FolioApp, FolioToolbar, the phone bar and ThemeEditor takes a list of families or a FontPickerSource:
const source: FontPickerSource = {
list: (query, signal) => fetch(`/api/fonts?q=${encodeURIComponent(query)}`, { signal }).then((r) => r.json()), // FontGroup[]
load: (family) => fontLoaderSource({ loader }).load(family), // awaited before the pick applies; reject = not applied
upload: { label: 'Upload font…', run: () => uploadDialog() }, // resolves { family } or null
store: { get: (key) => api.get(`/me/fonts/${key}`), set: (key, families) => api.put(`/me/fonts/${key}`, families) },
onUse: (family) => analytics.track('font', family),
};
<FolioApp app={app} fonts={source} />list is called as the user types; each call's signal aborts when the next starts. Groups ({ id, label, fonts: [{ family, label?, preview? }] }) are shown in order under Pinned and Recent; preview is a CSS font-family or an image URL. store may be async: the picker shows what it has and updates when get resolves; set failures are logged and the local list kept. The default store is localStorage. fontLoaderSource({ loader, families, groups }) is a ready source over a loader. A string array keeps working as before.
Imported documents: one font policy
Every importer (DOCX, PPTX, later ones) takes the same fonts option, from @nextgensoftwares/folio-import:
import { createFontLoader } from '@nextgensoftwares/folio-fonts';
const loader = createFontLoader({ engine, loadFamily, onFace }); // fallbacks: fontFallbacks() by default
const fonts = { policy: 'substitute', loader, available: (f) => engine.hasFamily(f) } as const;
const docx = await importDocx(bytes, { fonts }); // docx.fonts.report
const pptx = await openPptx(bytes, { fonts }); // pptx.fontspolicy | Embedded faces | Missing families | Warnings |
|---|---|---|---|
substitute (default) | registered first (PowerPoint subsets only when the host has no full copy) | the host's loadFamily, then a metric-compatible stand-in | font-embedded (info), font-substituted, font-missing |
warn | not loaded | nothing loaded: the document keeps its names and lays out with what the host has | font-missing for each family available doesn't know, with usedBy and embedded |
strict | registered | none: the import fails with FontPolicyError (missing: DocumentFont[]) |
Embedded faces whose licence forbids it (OS/2 fsType restricted embedding) are never used: font-embed-restricted. Embedded parts are decoded whatever the wrapper (decodeEmbeddedFont): plain fonts, Word's obfuscated .odttf (the w:fontKey GUID XORed over the first 32 bytes, ECMA-376 §17.8.1), PowerPoint's .fntdata (Embedded OpenType, XOR-encrypted or not; MicroType Express compressed data is reported, not decoded). Font warnings carry family, usedBy, embedded and with, and never document text. The report (DocumentFont[]: family, uses, embedded, status, stand-in) is what a "Fonts in this document" panel shows.
Fonts from the author's machine
A deck often names a font it doesn't embed (Comic Sans MS, Simplified Arabic). The author who imports it usually has the font installed: in Chromium, captureLocalFonts reads those faces through the Local Font Access API and returns them shaped like embedded faces, so the host stores them with the document and every reader (phones, server-side rendering) gets the original:
import { captureLocalFonts } from '@nextgensoftwares/folio-fonts';
button.onclick = async () => { // a user gesture: the browser asks for 'local-fonts'
const { faces, skipped } = await captureLocalFonts(
[{ family: 'Comic Sans MS' }, { family: 'Simplified Arabic', faces: [{ weight: 400 }, { weight: 700 }] }],
{ text: documentText }, // or `text` per family; omitted: whole faces
);
save([...embeddedFonts, ...faces]); // { family, weight, style, data, subset, source }
showStandIns(skipped); // { family, weight?, style?, reason }
};Faces whose licence forbids embedding (OS/2 fsType restricted, or bitmap-only) are skipped (restricted), the rule PowerPoint applies when it embeds; the rest are subset to the text's characters with HarfBuzz (glyphs its layout reaches, every feature and name record kept), unless fsType forbids subsetting. A subset face draws only those characters: text typed later in it falls back. Other reasons: unsupported (Firefox, Safari), denied, not-installed, unreadable. The font list is requested before anything else is awaited, so call it directly from the gesture's handler.
Small caps, all caps, letter spacing and character scale
Four textStyle attrs (Word's Small caps, All caps, character spacing and character scale) are laid out by the engine, so screen, PDF and DOCX agree:
textTransform: 'uppercase': the run is drawn in capitals. The document keeps the text as typed; text items carry the capitals (only case mappings that keep the UTF-16 length, so offsets stay ProseMirror offsets:ßstays).fontVariant: 'small-caps' | 'all-small-caps': when the font's primary face has the OpenTypesmcp(andc2scfor all small caps) feature (TextMeasurer.hasFeature), the run is shaped with it (FontSpec.features) and painters ask for the same glyphs (CSSfont-feature-settings, canvasfontVariantCaps, the PDF writer's HarfBuzz features). Otherwise small caps are synthesized: lowercase letters (every cased letter for all small caps) become capitals atSMALL_CAPS_SCALE(80%, as LibreOffice and Word draw them), split into their own text items; the kerning pair across each split (Ha→H+ smallA) is kept (kernon the left piece: the full-size pair's kerning scaled to the pair's mean size).letterSpacing: a length ('1.5pt', px number), may be negative. It lands onFontSpec.letterSpacing:width()adds it once per grapheme cluster andpositions()includes it (caret and hit-testing stay exact); the DOM painter sets CSSletter-spacing, canvasletterSpacing(per grapheme where the context lacks it), the PDF adds it after each cluster's last glyph.charScale: a percentage (1–600; Word'sw:w, e.g. 66 for condensed Arabic table text). It lands onFontSpec.scaleX(0.66). Measurers ignore it and shape unscaled glyphs; layout multiplies every width it takes from them (textWidth,textPositions), so line breaking, justification, tabs, bidi runs and item widths are scaled, and the editor's caret, hit testing and selections use the same helpers. Painters stretch the glyphs from the item's start: the DOM painters lay the span out atwidth / kwith CSStransform: scaleX(k)from its left edge (RTL text ends on the right edge, which lands on the item's), canvas draws inside a horizontaltransform, the PDF setsTz(and resets it to 100). Word spacing added by justification is unscaled: painters divide it bykinside the stretch. Letter spacing is scaled with the glyphs.
Text without these attrs keeps the exact same code path and cache keys.
Drawing with the same fonts
In the browser, the painter draws text with ordinary DOM text at the positions layout computed. Register the same font bytes with the browser so glyphs match the measurements:
const face = new FontFace('Geist', bytes, { weight: '100 900' });
document.fonts.add(face);
await face.load();If the browser drew with a different font, text would overflow or leave gaps, but line breaks and pagination would not change: they come from HarfBuzz.
Same pages in the browser and on a server
Layout is deterministic: the same document, theme, options and font files give the same pages in a browser and in Node. When a document paginates differently on the two (a server export with more pages than the editor), the usual cause is a family answered by different files: a host font module returning its own "Times New Roman" on one side while the other draws the Liberation Serif stand-in, or a stand-in missing from one deployment. The body font matters most: in a 150-page book, another serif for Times New Roman moved it by 14 to 56 pages.
Compare the two engines' faces for the document's families:
import { diffFaceReports, documentFamilies, faceReport } from '@nextgensoftwares/folio-fonts';
// After ensureDocumentFonts, on each side:
const report = faceReport(engine, documentFamilies(doc, theme));
// Send one side's report to the other (it's plain JSON), then:
diffFaceReports(browserReport, serverReport); // the families whose file or sample width differsEach entry names the family, weight and style, the name the engine resolved it to, the face file's size and hash, and a sample's width. An empty diff means the fonts agree, so look at the other inputs: the theme (a book style applied on one side only), the layout options, or a stored layout made by an older version under the same cache key.
A family nobody loaded is the other cause. documentFamilies walks every text layout measures: blocks and their marks, and content kept in attributes (drawings' text boxes and groups, header and footer parts with their own text boxes, tables inside shapes). If a host loads fonts some other way and misses one, the engine measures that text with the next family of its stack, silently. "Arial Black, Times New Roman" without Arial Black's stand-in loaded is measured as Times New Roman. Ask the engine after laying out:
for (const u of engine.unloaded()) {
// { family: 'arial black', weight: 900, style: 'normal', standIn: 'DejaVu Sans', measuredWith: 'Liberation Serif' }
console.warn(`"${u.family}" was measured with ${u.measuredWith}; load ${u.standIn ?? 'it'} first`);
}
engine.clearUnloaded(); // before the next documentA family loaded since drops out of the list. CSS generic families (serif, system-ui…) at the end of a stack are a choice, not a missing font, and aren't listed. Layout can't load fonts itself, since it's synchronous: load what documentFamilies returns before laying out (ensureDocumentFonts).
Fidelity against Chrome
tools/chrome-compare.mjs lays out every textblock of a corpus with Folio and with headless Chrome, using the same font files, and compares line starts and heights:
pnpm build
PUPPETEER_FROM=/path/with/node_modules/puppeteer node tools/chrome-compare.mjs chapters.ndjsonThe input is NDJSON, one {"c": <ProseMirror doc>} per line; the tool adds a synthetic Arabic / mixed-direction / justified stress set. Current result: 205/206 blocks identical, heights within 0.01 px. The single miss is a line ending within half a pixel of the margin, where Chrome floors advances to 1/64 px.
Math and media
Two more measurers are injected the same way:
MathMeasurer.measure(latex, { display, font })returns{ width, height, depth }. In the browser, a host can render KaTeX off-screen and read the box (the playground'screateKatexMeasurer); load KaTeX's fonts first or boxes are measured in a fallback font. Without one, layout uses a rough estimate.MediaSizer(attrs)returns the intrinsic{ width, height }of a media node (e.g. from upload metadata or a media manifest).@nextgensoftwares/folio-plugin-mediashipsmediaSizer, which readsnaturalWidth/naturalHeight.