What is this?
Pretext is a pure JavaScript/TypeScript library for multiline text measurement and layout — fast and accurate, including for languages you may not even know about.
Is this a library I pull into my own code, or a standalone app?
A library you import into your JavaScript or TypeScript code, not an app to run. Its output can go to DOM, Canvas, SVG and — soon — server-side rendering.
How do I see it in action locally?
Clone the repo, run bun install then bun start and open /demos/index in your browser (on Windows: bun run start:windows). Live demos also run at chenglou.me/pretext.
Which browsers and runtimes can actually run it?
Anything with Intl.Segmenter and Canvas 2D text measurement; browsers or runtimes without Intl.Segmenter are currently unsupported, so older browsers are out.
Will its line breaks always match what the browser renders?
Not always. system-ui and -apple-system are unsafe for layout() accuracy on macOS, so use a named font; emoji next to punctuation can also wrap differently.
How does it measure text without touching the DOM?
It side-steps DOM measurements like getBoundingClientRect and offsetHeight, which trigger layout reflow, and instead runs its own measurement logic using the browsers' own font engine as ground truth.
Is it only for measuring height, or can it lay out lines too?
Both. prepare() does the one-time work and layout() is the cheap hot path returning a paragraph's height; switch to prepareWithSegments() with layoutWithLines() or layoutNextLineRange() to lay out the lines yourself.
What do developers actually do with that measured height?
It unlocks virtualization and occlusion without guesstimates, masonry and JS-driven flexbox-like layouts, browser-free checks that button labels don't overflow, and re-anchoring scroll to prevent layout shift when text loads.
Can I tweak how it wraps text, say for CJK or letter-spacing?
Yes: prepare() takes { whiteSpace: 'pre-wrap' } to keep spaces, tabs and hard breaks visible, { wordBreak: 'keep-all' } for CJK-style keeping, and { letterSpacing: n } to match CSS letter-spacing in px.
What are similar projects?
kugiri, GSAP, anime, MathJax, classnames, source-han-sans, pixijs, pele
Which topics is it in?
rich-text, unicode, text, layout, cjk, fonts, dom, typography, npm-package, canvas, virtualization, webgl