Fast, accurate & comprehensive text measurement & layout
Fast, accurate & comprehensive text measurement & layout
Pure JavaScript/TypeScript library for multiline text measurement & layout. Fast, accurate & supports all the languages you didn't even know about. Allows rendering to DOM, Canvas, SVG and soon, server-side.
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).
npm install @chenglou/pretextClone the repo, run bun install, then bun start, and open /demos/index in your browser. On Windows, use bun run start:windows.
Alternatively, see them live at chenglou.me/pretext. Some more at somnai-dreams.github.io/pretext-demos
Pretext serves 2 use cases:
import { prepare, layout } from '@chenglou/pretext'
const prepared = prepare('AGI 春天到了. بدأت الرحلة 🚀', '16px Inter')
const { height, lineCount } = layout(prepared, 320, 20) // pure arithmetic. No DOM layout & reflow!prepare() does the one-time work: normalize whitespace, segment the text, apply glue rules, measure the segments with canvas, and return an opaque handle. layout() is the cheap hot path after that: pure arithmetic over cached widths. Do not rerun prepare() for the same text and configs; that'd defeat its precomputation. For example, on resize, only rerun layout().
If you want textarea-like text where ordinary spaces, \t tabs, and \n hard breaks stay visible, pass { whiteSpace: 'pre-wrap' } to prepare():
const prepared = prepare(textareaValue, '16px Inter', { whiteSpace: 'pre-wrap' })
const { height } = layout(prepared, textareaWidth, 20)Other prepare() options are { wordBreak: 'keep-all' } for CSS-like word-break: keep-all, and { letterSpacing: n } to match CSS letter-spacing (n is treated as a px value).
The returned height is the crucial last piece for unlocking web UIs:
Switch out prepare with prepareWithSegments, then:
layoutWithLines() gives you all the lines at a fixed width:import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
const prepared = prepareWithSegments('AGI 春天到了. بدأت الرحلة 🚀', '18px "Helvetica Neue"')
const { lines } = layoutWithLines(prepared, 320, 26) // 320px max width, 26px line height
for (let i = 0; i < lines.length; i++) ctx.fillText(lines[i].text, 0, i * 26)measureLineStats() and walkLineRanges() give you line counts, widths and cursors without building the text strings:import { measureLineStats, walkLineRanges } from '@chenglou/pretext'
const { lineCount, maxLineWidth } = measureLineStats(prepared, 320)
let maxW = 0
walkLineRanges(prepared, 320, line => { if (line.width > maxW) maxW = line.width })
// maxW is now the widest line — the tightest container width that still fits the text! This multiline "shrink wrap" has been missing from weblayoutNextLineRange() lets you route text one row at a time when width changes as you go. If you want the actual string too, materializeLineRange() turns that one range back into a full line:…This usage allows rendering to canvas, SVG, WebGL and (eventually) server-side. See the /demos/dynamic-layout demo for a richer example.
For hyphenation in manual layout, insert soft hyphens before prepare() / prepareWithSegments(). Pretext treats them as optional break points: unchosen soft hyphens stay invisible, while chosen breaks materialize as a trailing -. A soft hyphen at the end of the paragraph is consumed without painting a hyphen. For mixed-language or user-generated app text, prefer conservative, locale-aware insertion over aggressive pattern hyphenation. Automatic hyphenation is not built in today.
Very narrow SHY fallback remains approximate: Safari can overflow a prefix plus hyphen, while Chromium and Gecko may move part of the prefix to another line.
If your manual layout needs a small helper for rich-text inline flow, code spans, mentions, chips, and browser-like boundary whitespace collapse, there is a helper at @chenglou/pretext/rich-inline. It stays inline-only and white-space: normal-only on purpose:
import { materializeRichInlineLineRange, prepareRichInline, walkRichInlineLineRanges } from '@chenglou/pretext/rich-inline'
const prepared = prepareRichInline([
{ text: 'Ship ', font: '500 17px Inter' },
{ text: '@maya', font: '700 12px Inter', break: 'never', extraWidth: 22 },
{ text: "'s rich-note", font: '500 17px Inter' },
])
walkRichInlineLineRanges(prepared, 320, range => {
const line = materializeRichInlineLineRange(prepared, range)
// each fragment keeps its source item index, text slice, gapBefore, and cursors
})It is intentionally narrow:
extraWidth for pill chromebreak: 'never' for atomic items like chips and mentionswhite-space: normal onlyFragment and cursor itemIndex values refer to that original list, including when it contains empty items. A collapsed boundary space uses the first space's font and letter spacing; gapBefore can be zero or negative. Zero-width content can still occupy a line and carry a break opportunity.
Use-case 1 APIs:
…Use-case 2 APIs:
…Helper for rich-text inline flow:
…Other helpers:
clearCache(): void // clears Pretext's shared internal caches used by prepare() and prepareWithSegments(). Useful if your app cycles through many different fonts or text variants and you want to release the accumulated cache
setLocale(locale?: string): void // optional (by default we use the current locale). Sets locale for future prepare() and prepareWithSegments(). Internally, it also calls clearCache(). Setting a new locale doesn't affect existing prepare() and prepareWithSegments() states (no mutations to them)Notes:
PreparedText is the opaque fast-path handle. PreparedTextWithSegments is the richer manual-layout handle.LayoutCursor is a segment/grapheme cursor, not a raw string offset.layout() with an empty string returns { lineCount: 0, height: 0 }. Browsers still size an empty block to one line-height, so clamp with Math.max(1, lineCount) * lineHeight if you need that behavior.segLevels for custom bidi-aware rendering. Base direction and weak/neutral state restart at Unicode bidi paragraph separators in the normalized text. In pre-wrap, normalized newlines start fresh paragraphs; in normal, ASCII newlines collapse to spaces first. Tabs and U+2028 LINE SEPARATOR do not restart paragraph direction. This is not a full Unicode Bidirectional Algorithm implementation, and the line-breaking APIs do not read these levels.-.measureNaturalWidth() returns the widest forced line. Hard breaks still count.prepare() and prepareWithSegments() do horizontal-only work. lineHeight stays a layout-time input.Pretext doesn't try to be a full font rendering engine (yet?). It currently targets the common text setup:
white-space: normal and pre-wrapword-break: normal and keep-alloverflow-wrap: break-word. Very narrow widths can still break inside words and independent symbol runs, but only at grapheme boundaries.line-break: autoletter-spacing as a numeric pixel value passed to prepare() / prepareWithSegments()tab-size: 8{ wordBreak: 'keep-all' } is supported too. It behaves like you'd expect for CJK/Hangul and no-space mixed Latin/numeric/CJK text, while keeping the same overflow-wrap: break-word fallback for overlong runs.system-ui and -apple-system are unsafe for layout() accuracy on macOS. Use a named font. See the platform bug ledger for the Chrome and Firefox issues.lang, a generic font like sans-serif may select a different font from the one Pretext measures. Use a named font and check the result in your browser.Intl.Segmenter and Canvas 2D text measurement. Browsers or runtimes without Intl.Segmenter are currently unsupported.font shorthand, such as font-optical-sizing, font-feature-settings, and standalone font-variation-settings, are not modeled separately. Variable-font axes only help when the active axis is reflected in the canvas font string, for example via weight.See DEVELOPMENT.md for the dev setup and commands.
Sebastian Markbage first planted the seed with text-layout last decade. His design — canvas measureText for shaping, bidi from pdf.js, streaming line breaking — informed the architecture we kept pushing forward here.
Incremental prepare: prototypes, numbers and open decisions
system-ui: why it's inaccurate in each browser, and what supporting it would take
Support rich inline with `pre-wrap` whitespace preserve
Is there a supported fallback when `layout()` undercounts browser lines?
Rich-inline has a second line walker that keeps diverging from plain text layout
Native text layout emulation: offline engine ports, numbers and open decisions
Request: vertical-rtl
Bug: Markdown chat code box counts the tab that a soft-wrapped line ends on
Emoji width correction doesn't run inside Web Workers
Expose fontKerning option in prepare() — align measurement with rendering