What is Pretext

A library for front-end text metrics: width, line breaks, and height decoupled from DOM layout, using measurements consistent with the browser.

Why it exists

Often we measure text with hidden nodes or APIs like getBoundingClientRect and offsetHeight. Those reads can trigger reflow—expensive in lists, animation, or high-frequency updates.

Pretext uses canvas text measurement plus its own line-breaking pipeline. prepare() builds a reusable handle; layout() and related APIs answer height or per-line strings with arithmetic—no need to mount the text in the DOM.

Core flow

  • prepare(text, font): normalize whitespace, segment, measure—returns an opaque handle (heavier, run once).
  • layout(prepared, maxWidth, lineHeight): line count and total height (cheap hot path).

Need each line’s string (e.g. for Canvas)? Use prepareWithSegments with layoutWithLines. Need different widths per line (e.g. around a float)? Use layoutNextLine in a loop.

Typical use cases

  • Chat or feed virtualization: know row height before paint, fewer jumps and bad caches.
  • Canvas / WebGL labels: draw with line.text and line.width.
  • Design or CI checks that labels don’t wrap—without a full layout engine.

Learn more

Install: npm install @chenglou/pretext. Upstream README and source live on GitHub; the author also hosts demos elsewhere.

Community resource Cactusinhand/pretext-builder on GitHub: quick start, a layout-pattern cheat sheet, and practical notes such as waiting for document.fonts.ready (third-party, not an official Pretext repo).

For limitations (font names, white-space behavior, etc.), see Caveats. For the full API, see the API reference.