pretext
Pure JavaScript/TypeScript library for multi-line text measurement and layout. Fast, accurate, language-aware, render-agnostic (DOM, Canvas, SVG, server-side). Side-steps DOM measurements (getBoundingClientRect, offsetHeight) which trigger layout reflow.
The library implements its own text measurement using the browser's font engine as ground truth. Measurements are pure arithmetic over precomputed widths. Highly AI-friendly: agents can verify "does this label fit?" without spinning up a headless browser.
The text rule
Never trigger DOM reflow for text measurement. Precompute heights and widths in pure arithmetic. Keep text layout deterministic and verifiable without a browser.
This rule applies whenever the project has:
- buttons / tags / chips with dynamic labels (verify they don't overflow)
- inputs with autosizing height
- virtualized lists or masonry layouts
- balanced-text heroes (binary-search a nicer wrap point)
- async text loads where layout shift would otherwise occur
- shrink-wrap text containers (tightest container width that fits the actual text content)
When one of those needs exact text dimensions before render, pretext is the implementation backbone: CSS alone cannot give them. The limits under "Don't reach for it when" still apply.
When to reach for it
Reach for pretext when:
- you need text height BEFORE rendering (preallocate space, prevent layout shift)
- you need shrink-wrap (CSS
width: min-content is wrong for multi-line; pretext gives the actual narrowest width that fits)
- you're building a virtualized list and need accurate per-item heights without rendering them
- you need balanced text wrapping (e.g., two-line headlines that don't have one orphan word)
- you need dev-time / agent-time verification that a label fits in a container at a given width
- you're rendering to Canvas, SVG, WebGL, or server-side (browsers' DOM measurement is unavailable)
Don't reach for it when:
- text is single-line and CSS
white-space: nowrap + text-overflow: ellipsis solves the problem
- container width is fluid and you're fine with whatever wrapping the browser produces
- the text is decorative and exact measurements don't drive any layout decision
Install (when adding to a project)
Check if already installed. Look for @chenglou/pretext in package.json dependencies. If found, report and exit.
Install.
npm install @chenglou/pretext
# or: bun add @chenglou/pretext
# or: pnpm add @chenglou/pretext
Add a measurement helper at src/lib/text-measure.ts (or your project's lib path):
import { prepare, layout, prepareWithSegments, measureLineStats, walkLineRanges, type LayoutCursor } from '@chenglou/pretext'
// Sync font + letterSpacing string with your CSS exactly.
// font follows canvas font shorthand: "500 16px Inter"
// letterSpacing in CSS px
export function measureTextHeight(text: string, font: string, maxWidth: number, lineHeight: number) {
const prepared = prepare(text, font)
return layout(prepared, maxWidth, lineHeight)
}
export function shrinkWrapWidth(text: string, font: string, maxWidth: number) {
const prepared = prepareWithSegments(text, font)
let widest = 0
walkLineRanges(prepared, maxWidth, line => {
if (line.width > widest) widest = line.width
})
return widest
}
export function fitsInOneLine(text: string, font: string, maxWidth: number) {
const prepared = prepareWithSegments(text, font)
const { lineCount } = measureLineStats(prepared, maxWidth)
return lineCount === 1
}
Sync the font and letter-spacing strings with the project's tokens. If references/tokens.md defines --text-body: 16px / 24px / 0em / 400, the pretext call must be prepare(text, '400 16px <font-family>') with letterSpacing: 0. If they drift, measurements drift.
Confirm setup. Tell the user pretext is installed and the helper is at src/lib/text-measure.ts.
Project rule fold-in (which references file gets which rule)
When a project that uses pretext has a design-system package, fold these rules into the matching references/*.md files that exist. State each rule abstractly, without citing pretext (the client split in the asbuilt skill's package format: encode rules, not suppliers):
references/tokens.md (typography section)
Add a rule near the type scale table:
Text dimensions are computed via a deterministic measurement helper, not via DOM reflow. Components that depend on text height or width must call the project's text-measure helper, not getBoundingClientRect or offsetHeight. Sync font, weight, size, line-height, and letter-spacing exactly between CSS tokens and the measurement helper.
references/components.md
For atoms with dynamic labels (button, tag, chip, input):
Label overflow check. Dynamic labels are verified at dev time / agent time using the text-measure helper. Buttons and tags must not silently wrap to two lines.
For autosizing inputs / textareas:
Autosizing height. Computed via measurement helper. Set the textarea height to the precomputed value before render.
references/primitives.md
For virtualized lists, masonry, or balanced-text primitives:
Item heights are precomputed via the measurement helper. Virtualization buffers are sized from precomputed heights, not from rendered measurements. Masonry placement uses precomputed heights to avoid layout thrash.
references/responsive.md
Shrink-wrap pattern. When a container should be the tightest width that fits multi-line text, use the measurement helper's shrink-wrap function rather than CSS min-content (which is wrong for multi-line). Set the container to the returned width.
references/animation.md
Layout-shift prevention on async text. When text loads asynchronously and triggers layout, precompute the final height via the measurement helper before the text inserts. Reserve space, then fade text in.
references/platform-mapping.md
Text measurement helper. Project includes @chenglou/pretext and a wrapper at src/lib/text-measure.ts exposing measureTextHeight, shrinkWrapWidth, fitsInOneLine. Components import from there, not from @chenglou/pretext directly, to keep font strings centralized.
Anti-patterns
getBoundingClientRect() for layout decisions. Triggers reflow. Use the measurement helper.
offsetHeight / offsetWidth for sizing. Same problem.
- Hidden DOM nodes used to measure text (the classic "render in an offscreen div, read its height"). Pretext makes this obsolete and avoids the reflow.
- Out-of-sync font strings. If CSS says
500 16px "Inter" and pretext gets called with 400 16px Inter, the measurements are wrong. Always centralize through the wrapper helper.
- Pretext for text that doesn't drive layout. If the text is decorative and you don't need its dimensions, don't measure it. Pretext's job is precision where precision matters.
- CSS
width: min-content for multi-line shrink-wrap. It picks the longest single word, not the longest wrapped line. Use shrinkWrapWidth().
Forward compatibility
When new pretext APIs land (server-side rendering, automatic hyphenation, etc.), update src/lib/text-measure.ts first, then update the project rules in references/*.md to reflect new capabilities. Don't add raw @chenglou/pretext imports scattered across components — the wrapper is the contract.
See also
- repo: https://github.com/chenglou/pretext
- live demos: https://chenglou.me/pretext/
- the underlying principle: pure-arithmetic text measurement is one of those infrastructure-level inversions that unlocks correctness in places web has been wrong about for years (virtualization, balanced text, shrink-wrap, dev-time verification)
1---2name: pretext3description: "Pretext by Cheng Lou. Pure JavaScript/TypeScript library for fast, accurate multi-line text measurement and layout without DOM reflow. Use when text dimensions drive a layout decision: button or label overflow checks, text height before render, shrink-wrap or balanced text, virtualized lists and masonry, input autosizing, or layout-shift prevention on async text loads."4author: Cheng Lou (https://github.com/chenglou/pretext)5metadata:6 source: https://skillmd.com/skills/tommylower/pretext7---89# pretext1011Pure JavaScript/TypeScript library for multi-line text measurement and layout. Fast, accurate, language-aware, render-agnostic (DOM, Canvas, SVG, server-side). Side-steps DOM measurements (`getBoundingClientRect`, `offsetHeight`) which trigger layout reflow.1213The library implements its own text measurement using the browser's font engine as ground truth. Measurements are pure arithmetic over precomputed widths. Highly AI-friendly: agents can verify "does this label fit?" without spinning up a headless browser.1415## The text rule1617> **Never trigger DOM reflow for text measurement. Precompute heights and widths in pure arithmetic. Keep text layout deterministic and verifiable without a browser.**1819This rule applies whenever the project has:20- buttons / tags / chips with dynamic labels (verify they don't overflow)21- inputs with autosizing height22- virtualized lists or masonry layouts23- balanced-text heroes (binary-search a nicer wrap point)24- async text loads where layout shift would otherwise occur25- shrink-wrap text containers (tightest container width that fits the actual text content)2627When one of those needs exact text dimensions before render, pretext is the implementation backbone: CSS alone cannot give them. The limits under "Don't reach for it when" still apply.2829## When to reach for it3031Reach for pretext when:32- you need text height BEFORE rendering (preallocate space, prevent layout shift)33- you need shrink-wrap (CSS `width: min-content` is wrong for multi-line; pretext gives the actual narrowest width that fits)34- you're building a virtualized list and need accurate per-item heights without rendering them35- you need balanced text wrapping (e.g., two-line headlines that don't have one orphan word)36- you need dev-time / agent-time verification that a label fits in a container at a given width37- you're rendering to Canvas, SVG, WebGL, or server-side (browsers' DOM measurement is unavailable)3839Don't reach for it when:40- text is single-line and CSS `white-space: nowrap` + `text-overflow: ellipsis` solves the problem41- container width is fluid and you're fine with whatever wrapping the browser produces42- the text is decorative and exact measurements don't drive any layout decision4344## Install (when adding to a project)45461. **Check if already installed.** Look for `@chenglou/pretext` in package.json dependencies. If found, report and exit.47482. **Install.**49 ```sh50 npm install @chenglou/pretext51 # or: bun add @chenglou/pretext52 # or: pnpm add @chenglou/pretext53 ```54553. **Add a measurement helper** at `src/lib/text-measure.ts` (or your project's lib path):56 ```ts57 import { prepare, layout, prepareWithSegments, measureLineStats, walkLineRanges, type LayoutCursor } from '@chenglou/pretext'5859 // Sync font + letterSpacing string with your CSS exactly.60 // font follows canvas font shorthand: "500 16px Inter"61 // letterSpacing in CSS px6263 export function measureTextHeight(text: string, font: string, maxWidth: number, lineHeight: number) {64 const prepared = prepare(text, font)65 return layout(prepared, maxWidth, lineHeight)66 }6768 export function shrinkWrapWidth(text: string, font: string, maxWidth: number) {69 const prepared = prepareWithSegments(text, font)70 let widest = 071 walkLineRanges(prepared, maxWidth, line => {72 if (line.width > widest) widest = line.width73 })74 return widest75 }7677 export function fitsInOneLine(text: string, font: string, maxWidth: number) {78 const prepared = prepareWithSegments(text, font)79 const { lineCount } = measureLineStats(prepared, maxWidth)80 return lineCount === 181 }82 ```83844. **Sync the font and letter-spacing strings with the project's tokens.** If `references/tokens.md` defines `--text-body: 16px / 24px / 0em / 400`, the pretext call must be `prepare(text, '400 16px <font-family>')` with `letterSpacing: 0`. If they drift, measurements drift.85865. **Confirm setup.** Tell the user pretext is installed and the helper is at `src/lib/text-measure.ts`.8788## Project rule fold-in (which references file gets which rule)8990When a project that uses pretext has a design-system package, fold these rules into the matching `references/*.md` files that exist. State each rule abstractly, without citing pretext (the client split in the `asbuilt` skill's package format: encode rules, not suppliers):9192### `references/tokens.md` (typography section)9394Add a rule near the type scale table:9596> **Text dimensions are computed via a deterministic measurement helper, not via DOM reflow.** Components that depend on text height or width must call the project's text-measure helper, not `getBoundingClientRect` or `offsetHeight`. Sync font, weight, size, line-height, and letter-spacing exactly between CSS tokens and the measurement helper.9798### `references/components.md`99100For atoms with dynamic labels (button, tag, chip, input):101102> **Label overflow check.** Dynamic labels are verified at dev time / agent time using the text-measure helper. Buttons and tags must not silently wrap to two lines.103104For autosizing inputs / textareas:105106> **Autosizing height.** Computed via measurement helper. Set the textarea height to the precomputed value before render.107108### `references/primitives.md`109110For virtualized lists, masonry, or balanced-text primitives:111112> **Item heights are precomputed via the measurement helper.** Virtualization buffers are sized from precomputed heights, not from rendered measurements. Masonry placement uses precomputed heights to avoid layout thrash.113114### `references/responsive.md`115116> **Shrink-wrap pattern.** When a container should be the tightest width that fits multi-line text, use the measurement helper's shrink-wrap function rather than CSS `min-content` (which is wrong for multi-line). Set the container to the returned width.117118### `references/animation.md`119120> **Layout-shift prevention on async text.** When text loads asynchronously and triggers layout, precompute the final height via the measurement helper before the text inserts. Reserve space, then fade text in.121122### `references/platform-mapping.md`123124> **Text measurement helper.** Project includes `@chenglou/pretext` and a wrapper at `src/lib/text-measure.ts` exposing `measureTextHeight`, `shrinkWrapWidth`, `fitsInOneLine`. Components import from there, not from `@chenglou/pretext` directly, to keep font strings centralized.125126## Anti-patterns127128- **`getBoundingClientRect()` for layout decisions.** Triggers reflow. Use the measurement helper.129- **`offsetHeight` / `offsetWidth` for sizing.** Same problem.130- **Hidden DOM nodes used to measure text** (the classic "render in an offscreen div, read its height"). Pretext makes this obsolete and avoids the reflow.131- **Out-of-sync font strings.** If CSS says `500 16px "Inter"` and pretext gets called with `400 16px Inter`, the measurements are wrong. Always centralize through the wrapper helper.132- **Pretext for text that doesn't drive layout.** If the text is decorative and you don't need its dimensions, don't measure it. Pretext's job is precision where precision matters.133- **CSS `width: min-content` for multi-line shrink-wrap.** It picks the longest single word, not the longest wrapped line. Use `shrinkWrapWidth()`.134135## Forward compatibility136137When new pretext APIs land (server-side rendering, automatic hyphenation, etc.), update `src/lib/text-measure.ts` first, then update the project rules in `references/*.md` to reflect new capabilities. Don't add raw `@chenglou/pretext` imports scattered across components — the wrapper is the contract.138139## See also140141- repo: https://github.com/chenglou/pretext142- live demos: https://chenglou.me/pretext/143- the underlying principle: pure-arithmetic text measurement is one of those infrastructure-level inversions that unlocks correctness in places web has been wrong about for years (virtualization, balanced text, shrink-wrap, dev-time verification)