Pretext:Cheng Louの15KBライブラリがテキストレイアウトを300倍高速化する仕組み
PretextはSVGテキストレイアウトをブラウザAPIより300倍高速にする小さなライブラリです。アーキテクチャの詳細解説とVectoSolveでの活用方法を紹介します。
Founder of VectoSolve
Self-taught developer, founder and sole developer of VectoSolve since 2024. He builds the conversion engine and the cutting, embroidery and 3D printing exports.
How this article was made: drafted with AI assistance, then edited and fact-checked before publication. About the author
A Midjourney Engineer Just Fixed a 30-Year-Old Web Problem
For three decades, every website on Earth has been lying to you about where text should go.
Every time a browser needs to figure out how tall a paragraph is, or where to break a line, it triggers something called layout reflow — one of the most expensive operations a browser can perform. According to Google's Chrome DevTools team, a single forced reflow can block the main thread for 10-100ms on mobile devices (source: web.dev). Multiply that by every text block on the page, and you're looking at seconds of wasted compute.
Cheng Lou, a senior engineer at Midjourney and the creator of React Motion (21,700+ GitHub stars), just released Pretext — a 15KB JavaScript library with zero dependencies that measures and positions multiline text using pure arithmetic. No DOM. No reflow. No lies.
The result? 300 to 600 times faster than what every browser does today.
The Cost of Layout Reflow — By the Numbers
Before diving into Pretext, let's understand why this matters with real data:
- Layout reflow is the #1 cause of jank on the web. Google's Lighthouse audit flags "Avoid forced reflow" as a critical performance issue affecting 23% of all websites tested (source: HTTP Archive Web Almanac 2024)
- 53% of mobile users abandon sites that take over 3 seconds to load (source: Google/SOASTA Research, Think with Google)
- A single
offsetHeightread after a DOM write forces a synchronous layout recalculation — blocking the entire main thread (source: Chrome DevTools docs) - Cumulative Layout Shift (CLS) — one of Google's Core Web Vitals — directly measures unexpected layout movements. Sites with poor CLS are penalized in search rankings. In 2024, only 51% of websites passed the CLS threshold of 0.1 (source: Chrome UX Report)
- The average web page contains ~800 DOM elements (source: HTTP Archive). Each forced reflow recalculates the geometry of every visible element in the worst case
These aren't theoretical numbers. This is real performance data from billions of page loads.
Who Is Cheng Lou?
If you've worked with React animations, you've probably used something Cheng Lou built. His track record:
- React Motion — The physics-based animation library that replaced CSS transitions for thousands of React apps (21,700+ stars on GitHub, 900K+ weekly npm downloads at peak)
- ReasonML at Facebook — Led the development of OCaml-inspired language that powered messenger.com
- Midjourney — Currently building the AI image generation platform with 16+ million users (per Midjourney's 2024 public stats)
Pretext isn't his first attempt at solving text layout. He previously built text-layout, which he eventually archived in favor of this cleaner, more focused solution.
Pro Tip: Pretext is explicitly designed to be AI-friendly. Cheng Lou's launch message: "throw your AI into making cool demos for it!" — meaning the API is simple enough that AI coding assistants can build with it immediately.
How Pretext Works — The Technical Breakthrough
Traditional text measurement in a browser works like this:
- Create an invisible DOM element
- Set its styles (font, size, width constraints)
- Insert the text
- Call
getBoundingClientRect()oroffsetHeight - The browser triggers a full layout reflow to compute the answer
- You get your measurement
- Repeat for every text block
Each reflow forces the browser to recalculate the position and size of every element on the page. For 500 text blocks, that's 500 reflows. According to Paul Irish (Chrome team), these forced synchronous layouts are one of the most common performance anti-patterns in web development (source: "What forces layout/reflow" — Paul Irish, GitHub).
Pretext skips all of that. Here's how:
import { prepareWithSegments, layoutWithLines } from "@chenglou/pretext";
// Step 1: Prepare text with font metrics using canvas
// canvas.measureText() accesses the browser's font engine
// WITHOUT entering the layout tree — zero reflow
const prepared = prepareWithSegments(text, "16px Inter");
// Step 2: Pure arithmetic layout
// Given a container width, compute line breaks and positions
const { lines } = layoutWithLines(prepared, 400, 24);
// lines[i].text — the text content of each line
// lines[i].width — the computed width of each line
// All computed with math — no DOM touched
The key insight: canvas.measureText() accesses the browser's font shaping engine (the same one used for DOM rendering) but without triggering layout reflow. It's a read-only window into the font engine. Pretext caches the character widths and then uses pure arithmetic to compute line breaks, justification, and total height.
Performance: The Numbers
| Operation | DOM Measurement | Pretext | Source |
|---|---|---|---|
| 500 text blocks | 15-30 ms + 500 reflows | 0.05 ms + 0 reflows | Pretext benchmarks |
| Speed ratio | 1x | 300-600x faster | Pretext README |
| Reflows triggered | 500 | 0 | — |
| Main thread blocking | Yes (synchronous) | No | web.dev |
| Dependencies | Full DOM | Canvas context only | — |
| Bundle size | N/A | 15KB (gzipped: ~5KB) | npm |
This isn't a marginal improvement. It's a fundamentally different approach.
A Full Year of Conversions for $49
Starter Annual: 25 conversions every month, $49 for the whole year. That is about $4.08 a month · Cancel anytime
Get the Annual DealWhy This Matters for SVG and Vector Design
If you've ever tried to create multiline text in SVG, you know the pain. SVG's <text> element doesn't support automatic line wrapping — this has been an open issue since the SVG 1.1 spec in 2003. The W3C SVG Working Group has discussed automatic text wrapping for over 20 years, and SVG 2.0 still doesn't fully solve it.
You have to manually position each line with <tspan> elements:
<!-- SVG multiline text — manual positioning required -->
<svg viewBox="0 0 400 200">
<text font-family="Inter" font-size="24">
<tspan x="0" y="30">This is the first line</tspan>
<tspan x="0" y="60">and this is the second</tspan>
<tspan x="0" y="90">manually positioned line</tspan>
</text>
</svg>
Where do you break lines? How do you justify text? How do you handle different languages with different character widths? Before Pretext, you either hardcoded positions or used the DOM (slow and unavailable on the server).
Pretext + opentype.js: The Pipeline
With Pretext for layout and opentype.js (800K+ monthly npm downloads) for font path generation, you can build a complete text-to-SVG pipeline:
- Pretext computes line breaks and positions (0.05ms for 500 blocks)
- opentype.js converts each line to SVG
<path>elements (font-independent vector outlines) - The output is a clean SVG with
<path>elements — no<text>tags, no font dependency
This is exactly what VectoSolve's Smart Text Layout tool does. Paste any text, set a container width, and get auto-wrapped SVG with path outlines — all processed in your browser.
Practical Use Cases
1. Cutting Machine Files (Cricut, Silhouette)
The craft cutting market is worth $3.8 billion globally (Grand View Research, 2024) and growing at 5.2% CAGR. Cutting machines need vector paths to follow, but they also need text positioned correctly across multiple lines.
Pretext computes the exact layout before converting text to path outlines — which is exactly what VectoSolve's Smart Text Layout and Text to SVG tool do with opentype.js for path generation.
2. Dynamic Logo Generation
Need to generate logos with text that wraps around shapes or fits into specific containers? Pretext computes where every character goes without touching the DOM. Combine this with AI logo generation for the visual elements, and you have a complete brand identity pipeline.
3. Print-Ready Vector Typography
The global signage market is valued at $38.2 billion (MarketsandMarkets, 2024). For large-format printing (banners, signage, vehicle wraps), text must be vectorized with exact positioning. Pretext handles the layout math, and tools like VectoSolve's image vectorizer convert the final design to clean, scalable SVG.
4. SVG Animation with Text
Animating text in SVG requires knowing exactly where each character is. Pretext provides character-level position data that you can feed into CSS animations or SMIL. Combined with AI SVG animation, you can create complex text animations without manual coordinate calculations.
5. Server-Side SVG Generation
Since Pretext doesn't need a DOM, it works in Node.js, Deno, and edge functions. According to the State of JS 2024 survey, server-side rendering adoption has grown to 72% among professional developers. Generate PDF invoices, certificates, or social media cards with perfectly laid-out text — all server-side, all fast.
The Dragon Demo: Pretext's Showcase
Pretext's most impressive demo is the dragon — an 80-segment creature that text flows around in real-time. As the dragon moves, Pretext recalculates the layout for every frame, wrapping text around the dragon's body as if it were a magazine layout with an irregular text wrap.
This used to require a full browser layout engine. With Pretext, it runs at 60fps because the text measurement is pure math. For context, 60fps means each frame budget is 16.67ms — and traditional DOM measurement alone would consume 15-30ms, leaving zero room for rendering.
Other demos on Pretext's demo page:
- Editorial Engine — Magazine-style multi-column text layout
- Rich Note — Rich text editing with custom layout control
- Bubbles — Text flowing around dynamic obstacles
Each demo showcases a different aspect of zero-reflow text layout.
Free SVG Tools for Crafters
Design Checker · Color Separator · Mat Preview · Offset Generator · Text to SVG
Check Your SVG FreeHow Does Pretext Compare to Existing Solutions?
| Feature | DOM Measurement | CSS Columns | Pretext |
|---|---|---|---|
| Speed | Slow (reflow) | Medium | 300-600x faster |
| Server-side | No (needs DOM) | No | Yes |
| Custom shapes | No | Limited | Yes |
| Character-level positions | No | No | Yes |
| SVG path output | No | No | Yes |
| Dependencies | Browser | Browser | Canvas context |
| Size | N/A | N/A | 15KB |
| Web Worker compatible | No | No | Yes |
Pretext fills a gap that no CSS feature or browser API addresses: fast, programmable, DOM-free text layout with character-level control.
Getting Started with Pretext
Install via npm or bun:
npm install @chenglou/pretext
# or
bun install @chenglou/pretext
Basic usage:
import { prepareWithSegments, layoutWithLines } from "@chenglou/pretext";
const prepared = prepareWithSegments("Your text here", "16px sans-serif");
const { lines } = layoutWithLines(prepared, 300, 24);
// lines — Array of { text, width, start, end }
// Each line has exact position data
Key API concepts:
prepareWithSegments(text, font)— Measures character widths using canvas (no reflow)layoutWithLines(prepared, maxWidth, lineHeight)— Computes line breaks and returns line datalayoutNextLine(prepared, cursor, maxWidth)— For variable-width layouts (text around shapes)- Output: Line-by-line data including
.text,.width, and cursor positions
What This Means for the Future of Web Typography
Pretext proves that accurate text layout doesn't require a browser engine. This opens doors that were previously closed:
Dynamic editorial layouts — Magazine-style text wrapping with text flowing around images, shapes, and interactive elements. Previously impossible at 60fps. The New York Times reported spending 6+ months building custom text wrapping for their Snow Fall interactive in 2012 — Pretext solves this in a few lines of code.
AI-powered design tools — When an AI generates a layout, it needs to know text dimensions instantly. DOM measurement is too slow for real-time AI iteration. Pretext makes it instant. With the AI design tools market projected to reach $4.6 billion by 2028 (MarketsandMarkets), fast text layout becomes infrastructure.
Cross-platform rendering — The same layout code works in browsers, on servers, and in edge functions. Generate an SVG on the server, render it in the browser, print it on paper — identical layout everywhere.
Accessible typography — With character-level position data, you can build custom reading aids, text-to-speech highlighting, and screen reader enhancements that know exactly where every word is. The WHO estimates 2.2 billion people have some form of vision impairment — better text tooling serves everyone.
A Full Year of Conversions for $49
Starter Annual: 25 conversions every month, $49 for the whole year. That is about $4.08 a month · Cancel anytime
Get the Annual DealTry Smart Text Layout Now
Want to see auto-wrapped text-to-SVG in action? VectoSolve's Smart Text Layout tool uses Pretext for lightning-fast line breaking and opentype.js for SVG path generation. Paste any text, set a container width, and download a cut-ready SVG — all processed in your browser.
For manual line-by-line control, try the Text to SVG Cut File tool — 18 curated fonts, adjustable spacing, and instant SVG download.
Pretext is open source on GitHub under the MIT license. Follow Cheng Lou on X/Twitter for updates.