The End of Layout Thrashing: Unpacking chenglou/pretext
How a pure-TypeScript engine bypasses the DOM to turn multi-line text measurement into a blazing-fast math problem.
- Pretext eliminates layout thrashing by moving text measurement entirely out of the DOM.
- It uses the Canvas API as a read-only database to cache font metrics before applying pure math for line breaks.
- The two-phase architecture unlocks massive speedups that enable real-time responsive typography for dynamic AI interfaces.
The Reflow Trap
Web UI performance has a fundamental bottleneck. Measuring text dynamically forces the browser to recalculate the entire page layout. Developers have long accepted this synchronous reflow as a painful cost of doing business.
Building 120fps masonry grids or perfectly shrink-wrapped chat bubbles is nearly impossible with standard DOM methods. Every time you ask the browser for a bounding box, the rendering engine halts to do the math. Pretext was built to bypass this roadblock entirely.
Pretext side-steps the need for DOM measurements (e.g. `getBoundingClientRect`, `offsetHeight`), which trigger layout reflow, one of the most expensive operations in the browser. It implements its own text measurement logic, using the browsers' own font engine as ground truth (very AI-friendly iteration method).
The Canvas Escape Hatch
Pretext extracts font metrics using `OffscreenCanvas` and `Intl.Segmenter` without ever touching the DOM. It treats the browser font engine as a read-only database. Once the metrics are extracted, the library handles all subsequent line-breaking and wrapping via hyper-fast JavaScript arrays.
| Feature | Standard DOM | Raw Canvas API | Pretext |
|---|---|---|---|
| Triggers Reflow | Yes | No | No |
| Speed | Slow | Fast | Extremely Fast |
| Multi-line Support | Native | Manual | Built-in |
| Bidi/Emoji Support | Native | Poor | Built-in |
Splitting the Pipeline
The architecture breaks down into two distinct phases. The `prepare()` phase does the heavy lifting by segmenting text and caching widths. The `layout()` phase is the hot path that uses pure arithmetic to calculate line breaks when a container resizes.
The Linguistic Rabbit Hole
Text layout is notoriously complex. A single character can hide incredible nuance. Pretext implements Kinsoku Shori for Japanese punctuation rules and handles bidirectional Arabic and Hebrew text seamlessly.
It even includes hard-coded mathematical offsets to fix Safari and Chrome emoji rendering bugs on macOS. This level of detail proves that Pretext gives you the speed of canvas with the accuracy of the DOM.
A New UI Primitive
This mathematical approach to text unlocks new capabilities in userland. Pretext is already integrated into tldraw for high-performance rendering. It is also the ideal layout engine for AI agents streaming massive blocks of dynamic text.