← All open source projects

Pretext

chenglou/pretext

Pretext is a TypeScript library for fast multiline text measurement and layout without repeated DOM measurements.

Forks 2,692
Author chenglou
Language TypeScript
License MIT
Synced 2026-06-10

What it is

Pretext is a young TypeScript library for measuring and laying out multiline text. It addresses a painful interface problem: finding paragraph height, line breaks, and text placement without repeated DOM measurements such as getBoundingClientRect or offsetHeight, which can trigger expensive layout recalculation.

The repository was created in 2026, so it is a fresh project rather than a mature standard. Still, the problem it targets is very practical: virtual lists, editors, canvas/SVG rendering, message previews, and complex interfaces often run into text-measurement costs.

What is inside

The library separates text preparation from fast layout calculation. prepare normalizes whitespace, segments text, and measures pieces in advance, while layout cheaply recomputes lines and height for a given width. That model is especially useful during resize: the expensive preparation does not need to be repeated every time.

Measuring a paragraph without DOM layout

This example shows the main model: prepare text once, then quickly compute height and line count for a given width.

Language: TypeScript
import { prepare, layout } from "@chenglou/pretext";

const prepared = prepare("AGI spring. بدأت الرحلة 🚀", "16px Inter");
const result = layout(prepared, 320, 20);

console.log(result.height, result.lineCount);

Where it is useful

Pretext can be useful in editors, chats, whiteboards, design tools, canvas applications, and anywhere text must be laid out manually or measured before real rendering. Multi-script support matters because line breaking and segmentation vary strongly between languages.

Limitations

The main limitation is project youth and the complexity of the domain. Browser typography has many edge cases: fonts, emoji, bidirectional text, wrapping, white-space behavior, and engine differences. Pretext looks promising, but critical interfaces should test it with their own languages, fonts, and sizes.