harmonink

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.

fieldtypewhat it is
familystringFamily name, cleaned of subsetter artefacts
familyRawstringThe name exactly as the file states it
unitsPerEmnumberDesign units in the em box, usually 1000 or 2048
xHeightRationumberReading band over the em box
capHeightRationumber | nullCap height over the em box
ascenderRationumberTallest ascender over the em box
descenderRationumberLowest descender over the em box
inkRationumberFull ink extent over the em box
advanceXnumberMean advance width, in x-heights
gapBoxnumberEmpty width inside the advance, in x-heights
gapStemnumberSidebearing at stem height, in x-heights
stemXnumber | nullStem thickness, in x-heights
topSpreadnumberScatter of flat letter tops
footSpreadnumberScatter of flat letter feet
ascLetterRationumber | nullTallest of b d h k l, over the x-height
weightAxis[number, number] | nullwght axis range, on variable fonts
weightMeasurednumber | nullThe weight a variable font was measured at, else null
monospacebooleanEvery 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.

optiondefaultwhat it does
em512Size 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.

optiondefaultwhat it does
categorymeasuredOverride the classifier
baseSize16Nominal font size in px
xTarget0.54x-height ratio to aim at
deadband0.04Half-width of the leave-alone band
sizeFloor0.90Smallest allowed size-adjust
lineMode'follow''follow' or 'hold'
gridBox24Line box in px, when holding
trackClamp0.025Largest tracking move, in em
trackDeadband0.03Fraction of the ideal to ignore, on the input
trackFloor0.003Below this the output is dropped to 0 and no declaration is written
bounceCutoff0.15Scatter above which a face is handwriting
capGate0.90Cap height, relative to the category median, that triggers anchoring
minLeading5Pixels of clearance below the ink

Returns:

fieldwhat it is
sizeAdjustPercentage for the @font-face descriptor
lineHeightLine box in px, at baseSize
letterSpacingTracking in em, positive is looser
fontWeightWeight that keeps colour steady after scaling, from a 400 base
weightScaleThe multiplier behind it. Apply to any weight you set.
weightAxiswght range on a variable font, else null
renderedSizeWhat baseSize actually draws at
leadingSpace left over above and below the ink, in px
categoryCategory used, measured or overridden
capAnchoredAimed at cap height rather than x-height
trackClampedTracking wanted more than the clamp allows
gridBrokenInk forced the line box past gridBox
weightExactWeight 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);   // 700

Results 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]);   // 400

classify(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)

optiondefaultwhat it does
src—Font URL. Without it, no @font-face is written.
selector.text-normalizedClass or selector to write the rules against
familyfrom rulesOverride 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:

messagewhy
CFF/OTF outlines are not supported yetPostScript outlines. Most desktop .otf files.
no glyf tableBitmap 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 subtableNo character map the parser recognises.
corrupt font fileA 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 .otf files often are not.
  • Variable fonts move along the weight axis only. measure reads 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. familyRaw keeps the original either way.