Chenglou Pretext: The Story Behind the Fastest JavaScript Text Layout Engine

Apr 2, 2026

Every few years, someone in the JavaScript community challenges a constraint that everyone else accepted as permanent. Cheng Lou — known everywhere by his GitHub handle chenglou — has done it three times. His latest project, Pretext, might be his most impactful yet: a pure JavaScript text layout engine that computes line breaks and text height without ever touching the DOM.

This is the story of how chenglou created Pretext, why it exists, how it took off, and where it is heading.

Who Is Chenglou?

Cheng Lou is one of the most quietly influential engineers in the JavaScript ecosystem. He does not chase hype or build for clout. He identifies fundamental constraints that the entire industry has accepted as given — and then builds elegant solutions that sidestep them entirely.

React Core Team at Facebook

Chenglou's career in open source began on the React core team at Facebook (now Meta). Working alongside the creators of React, he gained deep insight into how UI frameworks handle rendering, state, and layout. This experience shaped his approach to every project that followed: understand the underlying model, find where it breaks down, and build something better.

react-motion — Rethinking Animation

Chenglou's first major open source hit was react-motion, which now has over 21,000 GitHub stars. At the time, every animation library used CSS timing functions — ease-in, ease-out, linear curves. Chenglou rejected this entirely. He argued that UI animations should be modeled as physics simulations — springs with stiffness and damping — rather than predefined curves.

The result was animations that felt natural and responsive. When a user interrupted an animation (by clicking again, scrolling, or navigating), react-motion's spring system adapted smoothly instead of snapping or glitching. It became the gold standard for React animation and influenced every animation library that came after it.

ReasonML and ReScript — Bringing Type Safety to the Web

Next, chenglou tackled JavaScript's type system. Rather than patching JavaScript with gradual typing (like TypeScript or Flow), he brought an entirely different language family to the web: OCaml. The result was ReasonML, later evolved into ReScript — a language with ML-grade type safety that compiles to readable JavaScript.

ReScript proved that you could have both the safety of a strict type system and the ergonomics of a JavaScript-like syntax. It built a passionate community and influenced how the broader ecosystem thinks about type safety and compilation.

The Pattern

Each of chenglou's projects follows the same pattern:

  1. Identify a constraint everyone accepts as given
  2. Reject the premise rather than work around it
  3. Build a userland solution that is fundamentally better, not just incrementally faster

Animation should use physics, not timing curves. Types should be sound, not gradual. And text measurement should be pure computation, not DOM access. That last insight is what led to Pretext.

Why Chenglou Created Pretext

The Problem at Midjourney

Today, chenglou works at Midjourney, where a remarkably small team of about 5 engineers serves millions of users. The UI is built on Bun and vanilla React — lean, fast, and stripped of unnecessary abstractions.

But there was a bottleneck that no framework could solve: text measurement.

Midjourney streams AI-generated content to users in real time. As tokens arrive, the text grows, and the UI needs to know how tall each text block is — for scrolling, for layout, for keeping the interface responsive. The traditional approach is to put the text in the DOM and ask the browser for its dimensions.

This triggers layout reflow — a synchronous, blocking operation where the browser recalculates the position and size of every affected element. When you are streaming tokens into hundreds of text blocks, reflow can cost 30 milliseconds or more per frame. At 60fps, you have 16.6ms per frame total. The math does not work.

The Insight

Chenglou's insight was radical: the browser does not need to own text measurement.

Line breaking is not magic. It is arithmetic. If you know the width of each word (or each grapheme cluster), you can walk through the text, track a running total, and insert line breaks when the total exceeds the container width. The height is just the number of lines multiplied by the line height.

The browser does this calculation internally during reflow. But it also does thousands of other things — recalculating cascading styles, resolving layout constraints, painting pixels. All chenglou needed was the text measurement part, isolated and fast.

So he built it.

How Pretext Works

Pretext splits text measurement into two phases:

Phase 1: Prepare

import { prepare } from 'pretext';

const ctx = prepare({
  fontFamily: 'Inter',
  fontSize: 16,
  lineHeight: 1.5,
});

The prepare() function does the expensive work once: it segments the text using Intl.Segmenter for Unicode-aware word boundaries, measures each segment via Canvas measureText(), and caches the results. This takes 0.1–1ms — comparable to a single DOM measurement.

Phase 2: Layout

const result = ctx.layout('Your text content here', {
  width: 300,
});

console.log(result.height);    // exact pixel height
console.log(result.lines);     // number of lines

The layout() function is where Pretext shines. It walks the cached segment widths, tracks a running total, and inserts breaks when width is exceeded. No DOM. No reflow. No side effects. Pure arithmetic.

Each layout() call takes approximately 0.0002ms — that is 600 times faster than a DOM measurement. You can call it thousands of times per frame without any performance impact.

The Key Insight: Reusability

The prepared context is reusable. Once you have called prepare() for a text+font combination, you can compute layouts at any width — mobile, tablet, desktop — with just arithmetic. Three widths, three layout() calls, zero DOM operations.

Why Pretext Matters

Breaking a 30-Year-Old Assumption

For three decades, web developers accepted that text measurement requires the DOM. Every framework, every library, every hack — they all ultimately fell back to creating a hidden element, injecting text, and reading dimensions. Pretext proves this assumption was never necessary.

Enabling New Categories of Applications

When text measurement becomes free (essentially zero-cost), applications that were previously impractical become straightforward:

  • Virtual scrolling with thousands of variable-height text items — no need to mount each one to measure it
  • Real-time text reflow around moving objects at 60fps — impossible when each reflow costs 30ms
  • Server-side text layout — Node.js, Deno, and Bun have no DOM, but they can run Pretext
  • Web Worker text measurement — offload layout computation to a background thread
  • Creative typography — text flowing around irregular shapes, ASCII art, generative layouts

Zero Dependencies, Framework Agnostic

Pretext is ~15KB gzipped with zero dependencies. It works with React, Vue, Svelte, Angular, Solid, or vanilla JavaScript. It runs in browsers, Node.js, Deno, Bun, Cloudflare Workers, and Web Workers. There is nothing to configure and nothing that can conflict with your stack.

Explosive Growth

When chenglou released Pretext, the response was immediate and explosive. The repository rocketed to 18,500+ GitHub stars in a matter of weeks — a growth curve that reflects how deeply the problem resonated with developers.

chenglou/pretext star history chart

Developers who had been fighting DOM measurement for years recognized what Pretext meant. Within days, the community started building things that nobody thought were possible in a browser.

tldraw Integration

tldraw integrating Pretext for instant canvas text measurement

The team at tldraw — one of the most popular collaborative whiteboard tools — integrated Pretext for instant text measurement. When you resize a text box in tldraw, the text reflows smoothly without any DOM measurement. No flicker, no jank.

Watch the demo →

Wes Bos — Words on Your Face

Blog post text mapped onto facial features via webcam

Wes Bos, one of the most well-known JavaScript educators, mapped Pretext text layout onto facial features via webcam. A blog post, except the words are on your face. It went viral and introduced Pretext to a massive audience.

Watch the demo →

3D Object Text Wrap

Text wrapping around a 3D gaussian splat object

Robin combined Pretext with WebGL to wrap text around a 3D gaussian splat object in real time. This uses Pretext's variable-width line support — each line can have a different available width, enabling text to flow around any shape.

Watch the demo →

Umbrella Text Reflow

Text dynamically reflows around a moving umbrella shape

j an built text that dynamically reflows around a moving umbrella shape. As the umbrella moves, the text wraps around it in real time — an effect that would be impossible with traditional DOM measurement.

Watch the demo →

TypeBeat — A Text Drum Machine

A drum machine made entirely out of text

Alexander Chen built a drum machine made entirely out of text, combining Pretext with Gemini. Each character becomes a percussive element. Sound on.

Watch the demo →

Knuth-Plass Line Breaking

Knuth-Plass optimized paragraph line breaking

Chenglou himself implemented the classic Knuth-Plass algorithm with Pretext — the same optimal line-breaking algorithm used by TeX and LaTeX, now running in JavaScript in real time. It reduces "rivers" of whitespace and makes long paragraphs significantly more readable.

Watch the demo →

Browse all 25+ community demos →

What Developers Are Saying

"Pretext is a genuine breakthrough. We've been fighting DOM measurement for years in tldraw — this just makes it disappear." — tldraw team

"60fps text reflow without a single DOM read. I kept checking if it was cheating somehow. It's not." — Andrea Giammarchi (@WebReflection)

"I got a 3D text wrap demo working in an afternoon. With DOM measurement, I wouldn't even know where to start." — Robin (@solarise_webdev)

"The prepare/layout API is so clean. One context, infinite layouts. This is how text measurement should have always worked." — Community developer

"Knuth-Plass line breaking in the browser, running in real time. I never thought I'd see the day." — Typography enthusiast

The Future of Pretext

Pretext has already proven that DOM-free text measurement works. But the project is still in its early days, and the potential directions are exciting:

Richer Layout Primitives

The current API covers line breaking and height calculation — the most common needs. Future versions could expand into more advanced layout primitives: paragraph-level optimization (Knuth-Plass is already a proof of concept), hanging punctuation, optical margin alignment, and multi-column layout. Each of these is pure arithmetic once you have the segment widths, which Pretext already computes.

Deeper Ecosystem Integration

tldraw's integration is just the beginning. Any application that deals with text layout — code editors, design tools, document viewers, presentation software, game engines — could benefit from Pretext. As the library matures, expect to see integrations with major frameworks and tools.

Creative and Artistic Applications

The community showcases have already shown that fast text measurement unlocks creative possibilities that nobody anticipated. Text wrapped around 3D objects, mapped onto faces, flowing around animated obstacles — these are just the first experiments. When measurement is free, typography becomes a creative medium, not just a rendering problem.

Server-Side and Edge Computing

As more applications move computation to the edge (Cloudflare Workers, Vercel Edge Functions, Deno Deploy), the ability to measure text without a DOM becomes increasingly valuable. Pretext can compute text layouts on the server, enabling pre-calculated layouts that eliminate layout shift on the client entirely.

The Broader Impact

Chenglou's track record suggests that Pretext will influence the ecosystem far beyond its direct usage. Just as react-motion changed how developers think about animation, and ReasonML changed how they think about types, Pretext is changing how they think about text. The idea that text measurement is "just arithmetic" — once you internalize it, you cannot go back.

Try Pretext Today

Chenglou built Pretext to solve a real problem at a real company. The community turned it into something much bigger. Whether you are building a chat interface, a virtual scrolling list, a creative typography experiment, or something nobody has thought of yet — Pretext gives you text measurement that is fast enough to get out of your way.

npm install pretext
Pretext.js Team

Pretext.js Team

Chenglou Pretext: The Story Behind the Fastest JavaScript Text Layout Engine | Blog