npm@chenglou/pretextv0.0.3
npmIntermediate

@chenglou/pretext

Fast multiline text measurement and layout without DOM reflow

text-layoutcanvasperformancetypographyvirtualizationmeasurement
The Problem

Measuring text height in the browser requires querying the DOM โ€” calling getBoundingClientRect() or reading offsetHeight forces the browser to perform a full layout reflow, one of the most expensive operations possible. In virtualised lists, dynamic text containers, or layouts where text flows around obstacles, you may need thousands of these measurements per frame. DOM-based measurement makes that cost prohibitive.

Mental Model

Pretext separates the expensive part (measuring character widths via Canvas) from the cheap part (computing line breaks via arithmetic). Call prepare() once per text string โ€” it measures every segment with Canvas and caches the results. Then call layout() as many times as you like at any width, entirely in arithmetic, with no DOM access at all. Prepare once, layout many times.

60-second start

Install @chenglou/pretext

npm install @chenglou/pretext
import { prepare, layout } from '@chenglou/pretext';

Use it when

Use pretext when you need to know text dimensions before rendering โ€” virtualised scrolling lists where you must know item heights upfront, text flowing around images or arbitrary obstacles, dynamic subtitle/caption positioning, detecting content overflow at build time, or any animation that requires text metrics on every frame.

Skip it when

Pretext only measures plain text โ€” it cannot handle HTML markup, inline images, or mixed rich content. For simple cases where you measure a single element once on mount, the browser's built-in ResizeObserver or getBoundingClientRect is simpler and sufficient. Pretext's two-phase API adds conceptual overhead that is only justified when measurements are frequent or happen before render.

Alternatives
ResizeObserverBuilt-in browser API that notifies you when an element changes size โ€” simpler when you just need to react to size changes after render rather than predict them before
canvas measureTextThe raw Canvas API that pretext uses internally โ€” reach for it directly for one-off measurements, but you lose pretext's caching, line-break logic, and multilingual handling
opentype.jsParses font files for full glyph path access โ€” use it when you need to render text to SVG paths or manipulate letterforms, not just measure layout

Ready to explore the full API?

See every class, function, and relationship in an interactive graph.