Pretext is a pure JavaScript/TypeScript library for multiline text measurement and layout that avoids expensive DOM operations.
The problem Pretext solves is the performance cost of measuring text through DOM APIs like getBoundingClientRect, which trigger layout reflow. Instead, it implements its own text measurement logic using the browser's font engine as ground truth. The library separates work into two phases: prepare() performs one-time normalization, segmentation, and canvas-based measurement to cache segment widths, while layout() runs the cheap hot path using pure arithmetic over those cached values. This approach supports all languages and allows rendering to DOM, Canvas, SVG, and eventually server-side.
Pretext suits projects that need accurate text dimensions without DOM measurement overhead, particularly those building custom layouts, virtualization systems, or dynamic text rendering. It excels for preventing layout shift when text loads, enabling proper scroll anchoring, and supporting development-time verification that text fits within UI constraints. The library offers two main use cases: measuring paragraph height directly without touching the DOM, or manually laying out lines with fine-grained control via functions like layoutWithLines() and layoutNextLineRange(). For manual layout scenarios requiring hyphenation, users can insert soft hyphens before preparation, and the library treats them as optional break points. A separate helper module at @chenglou/pretext/rich-inline provides utilities for inline-only rich text with code spans, mentions, and chips while maintaining normal whitespace behavior.
The project maintains active development with regular updates to its codebase and documentation. The repository includes working demonstrations accessible both locally and online, with additional community-contributed examples available. The maintainer actively responds to issues and accepts contributions, indicating ongoing engagement with the project's direction and user needs.