Dev.to WebDev 🛠 Dev 👁 2 📖 7 min read

Satori won't fit your text for you: sizing headlines with real font metrics

A headline on a Pinterest pin should be as big as the box allows: three words get huge letters, eight words get smaller ones, and nothing ever runs past the edge. In a browser you'd reach for CSS tricks or measure the DO

A headline on a Pinterest pin should be as big as the box allows: three words get huge letters, eight words get smaller ones, and nothing ever runs past the edge. In a browser you'd reach for CSS tricks or measure the DOM. In Satori, the server-side renderer I use, there's no DOM to measure, and it won't shrink text to fit.

My first version guessed widths with an average character width per font. It worked until a headline in condensed capitals came out wider than the pin. This post is the replacement: read the real width of every letter from the font file, then do the line breaking and sizing myself.

Why an average width fails

A common shortcut is width ≈ characters × fontSize × factor, with a factor like 0.55 for a typical sans. That's fine for lowercase body text. It breaks on headlines, which are often uppercase and often set in display faces where letter widths vary wildly. In Oswald Bold, "COLOURWORK" is full of wide capitals (O, C, W, R); an average factor undershoots it, the size comes out too large, and the word runs off the pin.

The fix is to know the advance width of each glyph, which is exactly what the font file stores.

Reading glyph widths from a WOFF file

I already ship WOFF files for Satori, so I read the same files. You need four tables:

  • head: unitsPerEm, the scale everything else is measured in.
  • hhea: numberOfHMetrics, how many entries hmtx has.
  • hmtx: the advance width of each glyph.
  • cmap: which glyph index draws which Unicode code point.

A WOFF 1 file is a table directory plus tables that are each optionally zlib-compressed. Node has zlib built in, so unpacking takes a few lines:

function tables(buf: Buffer): Map<string, Buffer> {
  if (buf.toString("latin1", 0, 4) !== "wOFF") throw new Error("not a WOFF 1 file");
  const out = new Map<string, Buffer>();
  const count = buf.readUInt16BE(12);
  for (let i = 0; i < count; i++) {
    const at = 44 + i * 20; // the WOFF header is 44 bytes, each directory entry 20
    const tag = buf.toString("latin1", at, at + 4);
    const offset = buf.readUInt32BE(at + 4);
    const compLength = buf.readUInt32BE(at + 8);
    const origLength = buf.readUInt32BE(at + 12);
    const raw = buf.subarray(offset, offset + compLength);
    out.set(tag, compLength < origLength ? zlib.inflateSync(raw) : raw);
  }
  return out;
}

The cmap table has several subtables. I take a Unicode one, preferring format 12 (full Unicode range) over format 4 (the Basic Multilingual Plane, as segments). Format 12 is a list of [start, end, firstGlyph] groups. Format 4 is the one with segment arrays and idRangeOffset; it's fiddly but well documented in the OpenType spec, and about thirty lines.

With a code point to glyph map, the widths fall out:

const unitsPerEm = head.readUInt16BE(18);
const metrics = hhea.readUInt16BE(34); // numberOfHMetrics
// Glyphs past the last entry share its width (monospaced tails).
const glyphWidth = (glyph: number) => hmtx.readUInt16BE(Math.min(glyph, metrics - 1) * 4) / unitsPerEm;

const advance = new Map<number, number>();
for (const [code, glyph] of charMap(cmap)) advance.set(code, glyphWidth(glyph));

Widths are stored in em, so multiplying by the font size gives pixels.

One more decision: what about characters the font doesn't have? @fontsource files are subset (I ship the Latin subset), so an unusual character may be missing. I assume it's as wide as the widest capital, so the headline errs small rather than spilling:

const caps = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map((c) => advance.get(c.charCodeAt(0)) ?? 0);
return { advance, fallback: Math.max(...caps) || 0.7 };

The public API is a function that returns a measuring function, cached per file:

export function measurer(family: string, weight: number): ((text: string) => number) | undefined {
  const file = FONT_FILES.find((f) => f.family === family && f.weight === weight)?.file;
  const m = file ? load(file) : null;
  if (!m) return undefined;
  return (text) => {
    let width = 0;
    for (const ch of text) width += m.advance.get(ch.codePointAt(0)!) ?? m.fallback;
    return width;
  };
}

If a file can't be read, the caller falls back to the old average factor, logged, rather than failing the render. This ignores kerning, which is why the layout below keeps a 3% safety margin.

Wrapping at a given size

With a measure, a line's width at a size is the sum of its words plus the spaces, plus letter spacing if the design uses any:

export function wordWidth(text: string, size: number, m: Metrics): number {
  return m.measure(text) * size + (m.letterSpacing ?? 0) * [...text].length;
}

Greedy wrapping at one size is the classic loop: add words while the line fits. It returns null if a single word is wider than the box, which is the signal to try a smaller size:

function wrap(words: Word[], size: number, width: number, m: Metrics): Line[] | null {
  const lines: Line[] = [];
  let line: Line = [];
  for (const w of words) {
    if (wordWidth(w.text, size, m) > width) return null;
    const next = [...line, w];
    if (line.length && lineWidth(next, size, m) > width) {
      lines.push(line);
      line = [w];
    } else line = next;
  }
  if (line.length) lines.push(line);
  return lines;
}

Finding the largest size that fits

Each template describes its headline box: width, maximum lines, maximum height, a size range. The fitter steps down from the maximum until everything fits:

const BUDGET = 0.97; // room for kerning and rounding in the renderer

// o: { width, maxLines, max, min, maxHeight?, lineHeight?, balanced? }
export function fitLines(words: Word[], m: Metrics, o: FitOptions): Fit {
  const width = o.width * BUDGET;
  const height = (n: number, size: number) => n * size * (o.lineHeight ?? 1.1);
  for (let size = o.max; size >= o.min; size -= 4) {
    const lines = wrap(words, size, width, m);
    if (!lines || lines.length > o.maxLines) continue;
    if (o.maxHeight && height(lines.length, size) > o.maxHeight) continue;
    return { size, lines: o.balanced ? balance(lines, size, width, m) : lines };
  }
  // Nothing fits: shrink until the widest word does, so no word runs past the box.
  const widest = Math.min(...words.map((w) => (width - (m.letterSpacing ?? 0) * [...w.text].length) / Math.max(m.measure(w.text), 0.01)));
  const size = Math.max(20, Math.min(o.min, Math.floor(widest)));
  return { size, lines: wrap(words, size, width, m) ?? words.map((w) => [w]) };
}

The last part is the rule I care about most: if nothing fits within the design's minimum, the minimum gives way. A smaller headline is a worse design; a headline cut off at the edge is a broken one.

A template then uses it like this:

const fit = fitLines(parseTitle(p.title, "upper"), metricsOf(p.font), {
  width: 820, maxLines: 7, max: 210, min: 60, maxHeight: 1080, lineHeight: 1.02, balanced: true,
});

Balancing lines

Greedy wrapping fills the first lines and leaves a short orphan at the end: "HOW TO PLAN A WEEK OF / MEALS". On a centred headline that looks wrong. Headlines are short, so I can afford to try every way of cutting the words into the same number of lines and keep the one whose line widths vary least:

function* partitions(words: Word[], n: number): Generator<Line[]> {
  if (n === 1) { yield [words]; return; }
  for (let cut = 1; cut <= words.length - n + 1; cut++) {
    for (const rest of partitions(words.slice(cut), n - 1)) yield [words.slice(0, cut), ...rest];
  }
}

The cost is the variance of line widths, and any option where a line overflows is skipped. Past 14 words I don't bother (the number of partitions grows quickly, and pin headlines are rarely that long).

Poster lines: each line its own size

Some styles imitate hand-lettered posters, where every line fills the width and short lines get bigger letters. For one line, the size that exactly fills the width has a closed form, because a line is "em times size plus fixed letter spacing":

export function sizeToFill(line: Line, width: number, m: Metrics): number {
  return Math.max(1, (width - lineFixed(line, m)) / Math.max(lineEm(line, m), 0.01));
}

The poster layout tries every cut into 2 to N lines, sizes each line to fill, scales everything down if the stack is too tall, and scores the result: bigger and fuller is better, but a line more than about 2.2 times the size of another is penalised, so one giant word doesn't dwarf the rest.

Drawing the lines in Satori

Once the lines and sizes are known, Satori only has to place them. Every line is a flex row and every word its own element, which has a nice side effect: single words can be styled. A word wrapped in *stars* in the headline gets a highlighter stroke, an italic or an accent colour, and because I know each word's width, the highlighter SVG is drawn exactly as wide as the word.

Takeaways

  • Average character widths fail on display fonts and capitals. Real advance widths come from four tables (head, hhea, hmtx, cmap) and a few dozen lines of parsing.
  • Treat missing glyphs as wide, keep a small safety margin for kerning, and fall back gracefully if a font can't be read.
  • Step the size down until the wrapped text fits the width, line count and height; if nothing fits, let the minimum size give way rather than overflow.
  • Headlines are short enough to brute-force line breaks for balance or poster-style sizing.
  • Knowing each word's width lets you style individual words precisely.

This is how every headline in PinCyborg's pin templates is sized.

Drafted with help from an AI assistant and checked against the real code.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.