HubLensTypeScriptchenglou/pretext
// archived 2026-04-11
chenglou

pretext

Frontend#TypeScript#JavaScript#Layout#Canvas#Performance
View on GitHub
84

// summary

Pretext is a JavaScript/TypeScript library that provides fast, accurate multiline text measurement and layout without relying on expensive DOM reflow operations. By implementing its own measurement logic using the browser's font engine as a ground truth, it enables efficient text handling for various rendering targets like Canvas and SVG. The library offers both high-level APIs for simple height calculations and low-level tools for manual, complex text layout scenarios.

// technical analysis

Pretext is a high-performance JavaScript/TypeScript library designed to handle multiline text measurement and layout without relying on expensive DOM reflows. By implementing its own measurement logic using the browser's font engine as a ground truth, it enables developers to perform complex text calculations, such as virtualization and custom layout engines, with pure arithmetic. This design choice prioritizes speed and accuracy, effectively solving the performance bottlenecks associated with traditional browser-based text measurement.

// key highlights

01
Eliminates costly DOM layout reflows by performing text measurement through pure arithmetic and cached canvas-based metrics.
02
Supports advanced layout scenarios like text virtualization, masonry, and custom flexbox-like implementations without browser-side hacks.
03
Provides a streaming, iterator-based API for manual line layout, allowing for complex text wrapping around dynamic elements like floated images.
04
Includes a specialized rich-text inline flow helper that manages boundary whitespace collapse and atomic items like chips or mentions.
05
Offers a two-phase architecture that separates expensive one-time text preparation from the high-speed, hot-path layout calculations.
06
Enables accurate development-time verification of text overflow and layout behavior, facilitating AI-friendly iteration cycles.

// use cases

01
Calculating paragraph height and line counts without triggering browser layout reflows.
02
Performing manual text layout for custom rendering in Canvas, SVG, or WebGL environments.
03
Enabling advanced UI features like virtualization, masonry layouts, and dynamic text wrapping around elements.

// getting started

To begin using Pretext, install the package via npm using 'npm install @chenglou/pretext'. Import the 'prepare' and 'layout' functions to analyze text and calculate dimensions, or use 'prepareWithSegments' for more granular control over line-by-line rendering. You can explore the library's capabilities by cloning the repository and running the provided demo scripts.