pretext
Pretext – DOM-Free Text Measurement & Layout
Pretext is a pure-JavaScript/TypeScript library that measures and lays out multiline text without touching the DOM. It uses the browser's own font engine (via canvas measureText) as ground truth, then does all line-breaking and height calculation in pure arithmetic. Supports rendering to DOM, Canvas, SVG, and (eventually) server-side.
Why This Matters
DOM-based text measurement (getBoundingClientRect, offsetHeight) triggers layout reflow — one of the most expensive operations in a browser. Every call forces the engine to recalculate styles and geometry for potentially the entire document. In a virtualized list with 10,000 rows, that means 10,000 reflows just to get row heights.
Pretext replaces that with a two-phase approach: one prepare() call does text analysis, segmentation, glue rules, and canvas measurement (the expensive part, done once), then layout() computes height from cached widths using pure math (the cheap part, called on every resize). This is 300-600x faster than DOM measurement, and it eliminates layout thrashing entirely.
The result is pixel-perfect across browsers (7680/7680 on Chrome, Safari, and Firefox accuracy sweeps), supports all languages including emoji, mixed-bidi, CJK, Thai, Arabic, Khmer, Myanmar, Urdu, and more.
Installation
npm install @chenglou/pretext