Build virtual lists that know item heights before rendering, preventing layout shifts.
Create masonry layouts and prevent scroll-jumping when new content loads.
Render text to Canvas or SVG without DOM access, or in server-side environments.
Implement custom rich-text editors and complex typography layouts with precise text dimensions.
Pretext is a JavaScript and TypeScript library that solves a fundamental problem in web development: measuring how much space a block of text will occupy before actually rendering it on screen. In a browser, the standard way to know a text element's height is to insert it into the page and measure it with methods like getBoundingClientRect. This approach forces the browser to recalculate the entire page layout, an expensive operation called \"layout reflow.\" Pretext bypasses this entirely by implementing its own text measurement logic in pure JavaScript, using the HTML Canvas API under the hood to sample character widths from the real font, then doing all subsequent calculations in pure arithmetic with no DOM involvement. The library handles the genuinely hard parts of text layout: word wrapping across languages (including Arabic, Chinese, Japanese, and emoji), correct line-breaking rules, whitespace normalization, letter spacing, and hard line breaks. You call prepare() once on a piece of text to do the expensive font measurement, then call layout() repeatedly with different container widths, for example, as a user resizes a window, at negligible cost. This matters practically for building virtual lists (where you need to know an item's height before rendering it to avoid guesswork), masonry layouts, preventing scroll-jumping when new content loads, flow text around floating images, and rendering text to Canvas, SVG, or server-side environments where the DOM is unavailable. You would use Pretext when building anything where you need precise text dimensions without a layout reflow penalty, custom rich-text editors, data-heavy dashboards, complex typography layouts, or any performance-sensitive UI with many text elements. The library is written in TypeScript, installable via npm, and has zero DOM dependencies for its core measurement path.
Generated 2026-05-18 · Model: sonnet-4-6 · Verify against the repo before relying on details.