API reference
Five functions and a handful of constants. Measurements and rules are separate exports, because the measurements are facts and the rules are opinions.
import { measure, normalize, classify, toCSS } from 'harmonink';
import { measureLive } from 'harmonink/live';Subpaths: harmonink/measure, harmonink/normalize,harmonink/live, harmonink/css. Use them in browser bundles so the woff2 parser and node:zlib stay out.
measure(buffer, { weight })
Reads a font binary and returns its metrics. Accepts .ttf,.otf, .woff and .woff2, as long as the outlines are TrueType. Node only, since it needs node:zlib for woff2. A variable font is measured at weight, 400 unless you set it, clamped to the font's wght axis.
| field | type | what it is |
|---|---|---|
| family | string | Family name, cleaned of subsetter artefacts |
| familyRaw | string | The name exactly as the file states it |
| unitsPerEm | number | Design units in the em box, usually 1000 or 2048 |
| xHeightRatio | number | Reading band over the em box |
| capHeightRatio | number | null | Cap height over the em box |
| ascenderRatio | number | Tallest ascender over the em box |
| descenderRatio | number | Lowest descender over the em box |
| inkRatio | number | Full ink extent over the em box |
| advanceX | number | Mean advance width, in x-heights |
| gapBox | number | Empty width inside the advance, in x-heights |
| gapStem | number | Sidebearing at stem height, in x-heights |
| stemX | number | null | Stem thickness, in x-heights |
| topSpread | number | Scatter of flat letter tops |
| footSpread | number | Scatter of flat letter feet |
| ascLetterRatio | number | null | Tallest of b d h k l, over the x-height |
| weightAxis | [number, number] | null | wght axis range, on variable fonts |
| weightMeasured | number | null | The weight a variable font was measured at, else null |
| monospace | boolean | Every letter has the same advance |
All ratios are frequency-weighted across the Latin lowercase, so common letters count for more than q and z.
measureLive(family, options)
The same shape, measured in a browser from a font that is already loaded. Rasterises each glyph to a canvas and counts pixels.
| option | default | what it does |
|---|---|---|
| em | 512 | Size to measure at. Larger is more precise and slower. |
| size | — | Overrides em for the canvas font size. |
| canvas | — | Reuse a canvas instead of creating one. |
Returns approximate: true and glyphsMeasured alongside the usual fields. weightAxis is always null, because canvas cannot see the axis. Await document.fonts.load() first or you will measure the fallback font without being told.
It disagrees with the parser on a few faces. Where glyphs overhang their own advances, canvas and the outlines report different sidebearings, which is enough to flip Pacifico between handwriting and serif and change the tracking it gets. Five faces are affected and they are listed intest/live-verify.mjs. Use measure when you have the bytes.
normalize(metrics, options)
Turns metrics into CSS values. This is the opinionated half.
| option | default | what it does |
|---|---|---|
| category | measured | Override the classifier |
| baseSize | 16 | Nominal font size in px |
| xTarget | 0.54 | x-height ratio to aim at |
| deadband | 0.04 | Half-width of the leave-alone band |
| sizeFloor | 0.90 | Smallest allowed size-adjust |
| lineMode | 'follow' | 'follow' or 'hold' |
| gridBox | 24 | Line box in px, when holding |
| trackClamp | 0.025 | Largest tracking move, in em |
| trackDeadband | 0.03 | Fraction of the ideal to ignore, on the input |
| trackFloor | 0.003 | Below this the output is dropped to 0 and no declaration is written |
| bounceCutoff | 0.15 | Scatter above which a face is handwriting |
| capGate | 0.90 | Cap height, relative to the category median, that triggers anchoring |
| minLeading | 5 | Pixels of clearance below the ink |
Returns:
| field | what it is |
|---|---|
| sizeAdjust | Percentage for the @font-face descriptor |
| lineHeight | Line box in px, at baseSize |
| letterSpacing | Tracking in em, positive is looser |
| fontWeight | Weight that keeps colour steady after scaling, from a 400 base |
| weightScale | The multiplier behind it. Apply to any weight you set. |
| weightAxis | wght range on a variable font, else null |
| renderedSize | What baseSize actually draws at |
| leading | Space left over above and below the ink, in px |
| category | Category used, measured or overridden |
| capAnchored | Aimed at cap height rather than x-height |
| trackClamped | Tracking wanted more than the clamp allows |
| gridBroken | Ink forced the line box past gridBox |
| weightExact | Weight came off a real axis, not a snap to hundreds |
Every constant in DEFAULTS can be passed as an option, so you can move the target or widen the deadband without forking anything.How it works shows what each one is set against.
weightFor(rules, baseWeight, steps)
A scaled-up face draws heavier at the same nominal weight, so the weight comes back down in proportion. fontWeight is that correction applied to 400.weightFor applies it to whatever weight you actually set.
import { normalize, weightFor } from 'harmonink';
const rules = normalize(metrics); // weightScale: 0.81
weightFor(rules, 400); // 300
weightFor(rules, 700); // 600
weightFor(rules, 900); // 700Results land on 100s, because that is all most families ship. Passsteps when you know the real list and it will snap to that instead, so a family with only 400, 500, 600 and 700 never gets asked for a 300 it does not have. A variable font with a wght axis lands exactly, with no snapping, unless you pass steps.
weightFor(rules, 500, [400, 500, 600, 700]); // 400classify(metrics, options)
Returns 'sans-serif', 'serif', 'monospace' or'handwriting'. Geometric, not editorial: a hand-drawn face with regular letterforms comes back as sans-serif, because nothing in the outlines says otherwise.
toCSS(rules, options)
| option | default | what it does |
|---|---|---|
| src | — | Font URL. Without it, no @font-face is written. |
| selector | .text-normalized | Class or selector to write the rules against |
| family | from rules | Override the family name |
Writes font-size: 1em and a unitless line height so the class composes at any inherited size. size-adjust and letter-spacing are left out when they come out as the identity, since writing them claims a correction that did not happen and would override an inherited value.
Exported constants
DEFAULTS holds every tunable. GAP_IDEAL,BOX_IDEAL, GAP_FLOOR and CAP_MEDIAN are the per-category tables, keyed by category name. All are plain objects, safe to read and spread.
Errors
measure throws rather than returning something half-measured:
| message | why |
|---|---|
| CFF/OTF outlines are not supported yet | PostScript outlines. Most desktop .otf files. |
| no glyf table | Bitmap font, or a container with no outlines in it. |
| no outline for "x" | No Latin lowercase, so there is no x-height to read. |
| no usable cmap subtable | No character map the parser recognises. |
| corrupt font file | A damaged or cut-short file. The message goes on to say what was wrong. |
measureLive throws if fewer than 20 of the 26 lowercase letters render, which usually means the font never loaded and you are measuring a fallback.
Limits
- No CFF outlines. Google Fonts are fine. Desktop
.otffiles often are not. - Variable fonts move along the weight axis only.
measurereads the font at the weight you ask for, 400 by default. Optical size, width and slant stay at the font's default. - Latin only. The whole method rests on the lowercase x.
- Family names can carry a style word. A subset whose default instance is not Regular may report as "Figtree Light". Obvious mangling gets cleaned, but a bare trailing style word does not, because "Shadows Into Light" is a real family name.
familyRawkeeps the original either way.