Skip to content

Pretext

TypeScript

TypeScript library for multiline text measurement and layout without DOM reflow.

31k stars MIT View on GitHub
Start the Grand Tour
Cheng Lou Creator @chenglou

Currently at Midjourney. Not a newcomer to problems at the intersection of browser constraints and developer experience. His library react-motion (21,700+ stars) replaced the dominant CSS animation approach with physics-based spring animations. Spent several years at Meta working on ReasonML and ReScript, bringing ML-family type systems to the JavaScript ecosystem. His 2016 React Europe talk, "On the Spectrum of Abstraction," laid out a thesis he has returned to since: reducing expressivity through the right constraints yields more capability, not less.

Two phases, one insight:

prepare(text, options) runs once per unique text string and font configuration. Calls Intl.Segmenter for script-aware segmentation, measures each segment via Canvas measureText(), and stores widths in a two-level cache keyed by font string and segment.

layout(preparedText, containerWidth) is pure arithmetic. Walks the cached widths, applies the greedy line-breaking algorithm, and returns line break positions and character offsets. No DOM. No Canvas calls. No side effects.

FileSizeRole
layout.ts24KBPublic API surface
line-break.ts31KBCore greedy line-breaking algorithm
analysis.ts27KBUnicode script analysis
measurement.ts7KBCanvas measurement and width cache
bidi.ts6KBBidirectional text (Arabic, Hebrew)
layout.test.ts36KBTest suite
test-data.ts5KBGround-truth test fixtures

The test suite is larger than the implementation. That is not an accident — browser behavior around text is inconsistent enough that the tests document a set of known browser discrepancies as much as they verify correctness.

Origin Story Read how Pretext came to be and the decisions that shaped its architecture.

Keyboard Shortcuts