|
| 1 | +--- |
| 2 | +title: Text Measurement with Pretext |
| 3 | +--- |
| 4 | + |
| 5 | +[Pretext](https://github.com/chenglou/pretext) is a text measurement and layout library from Cheng Lou. TanStack Virtual still owns scrolling, range calculation, item positioning, and scroll-to behavior; Pretext can own the text-height estimate for rows whose height is mostly determined by wrapped text. |
| 6 | + |
| 7 | +This is useful for chat logs, AI streams, activity feeds, comments, changelogs, notifications, and other text-heavy timelines where DOM measurement creates visible correction work. |
| 8 | + |
| 9 | +## When to use it |
| 10 | + |
| 11 | +Use Pretext when each virtual row's height can be derived from: |
| 12 | + |
| 13 | +- Text content |
| 14 | +- The exact canvas font string used by the rendered text |
| 15 | +- The available content width |
| 16 | +- The rendered line-height |
| 17 | +- Matching whitespace, word-break, and letter-spacing settings |
| 18 | + |
| 19 | +Do not make Pretext responsible for rows whose height depends on images, embeds, block markdown, loaded components, or arbitrary CSS layout. For those rows, use `measureElement`, call `resizeItem` when the extra content resolves, or split the text-only and non-text portions into separate sizing paths. |
| 20 | + |
| 21 | +## Install |
| 22 | + |
| 23 | +```sh |
| 24 | +npm install @chenglou/pretext |
| 25 | +``` |
| 26 | + |
| 27 | +## Basic pattern |
| 28 | + |
| 29 | +Cache `prepare()` by text and text-style inputs. Run `layout()` for the current width. When the width, font, line-height, or text options change, reset Virtual's measurements so offsets are recalculated from the new estimates. |
| 30 | + |
| 31 | +```tsx |
| 32 | +import { clearCache, layout, prepare } from '@chenglou/pretext' |
| 33 | +import { useVirtualizer } from '@tanstack/react-virtual' |
| 34 | + |
| 35 | +const font = '14px Arial' |
| 36 | +const lineHeight = 20 |
| 37 | +const preparedCache = new Map<string, ReturnType<typeof prepare>>() |
| 38 | + |
| 39 | +function getPrepared(row: { id: string; text: string }) { |
| 40 | + const key = `${row.id}:${font}:${row.text}` |
| 41 | + const cached = preparedCache.get(key) |
| 42 | + |
| 43 | + if (cached) { |
| 44 | + return cached |
| 45 | + } |
| 46 | + |
| 47 | + const prepared = prepare(row.text, font, { |
| 48 | + whiteSpace: 'pre-wrap', |
| 49 | + letterSpacing: 0, |
| 50 | + }) |
| 51 | + preparedCache.set(key, prepared) |
| 52 | + return prepared |
| 53 | +} |
| 54 | + |
| 55 | +function estimateRowHeight(row: { id: string; text: string }, contentWidth: number) { |
| 56 | + const text = layout(getPrepared(row), contentWidth, lineHeight) |
| 57 | + const textHeight = Math.max(lineHeight, text.height) |
| 58 | + |
| 59 | + return textHeight + 24 |
| 60 | +} |
| 61 | + |
| 62 | +function Messages({ rows }: { rows: Array<{ id: string; text: string }> }) { |
| 63 | + const parentRef = React.useRef<HTMLDivElement>(null) |
| 64 | + const [width, setWidth] = React.useState(640) |
| 65 | + |
| 66 | + React.useLayoutEffect(() => { |
| 67 | + const element = parentRef.current |
| 68 | + |
| 69 | + if (!element) { |
| 70 | + return |
| 71 | + } |
| 72 | + |
| 73 | + const update = () => setWidth(element.clientWidth) |
| 74 | + const observer = new ResizeObserver(update) |
| 75 | + |
| 76 | + update() |
| 77 | + observer.observe(element) |
| 78 | + |
| 79 | + return () => observer.disconnect() |
| 80 | + }, []) |
| 81 | + |
| 82 | + const virtualizer = useVirtualizer({ |
| 83 | + count: rows.length, |
| 84 | + getItemKey: (index) => rows[index]!.id, |
| 85 | + getScrollElement: () => parentRef.current, |
| 86 | + estimateSize: (index) => estimateRowHeight(rows[index]!, width - 32), |
| 87 | + }) |
| 88 | + |
| 89 | + React.useLayoutEffect(() => { |
| 90 | + virtualizer.measure() |
| 91 | + }, [virtualizer, width]) |
| 92 | + |
| 93 | + React.useEffect(() => { |
| 94 | + document.fonts.ready.then(() => { |
| 95 | + preparedCache.clear() |
| 96 | + clearCache() |
| 97 | + virtualizer.measure() |
| 98 | + }) |
| 99 | + }, [virtualizer]) |
| 100 | + |
| 101 | + return <div ref={parentRef}>{/* render virtual rows */}</div> |
| 102 | +} |
| 103 | +``` |
| 104 | + |
| 105 | +## Robustness checklist |
| 106 | + |
| 107 | +- Match CSS and Pretext inputs exactly. `font`, `line-height`, `letter-spacing`, `white-space`, and `word-break` must agree with the rendered row. |
| 108 | +- Prefer named fonts. System font aliases can map differently between CSS and canvas, especially on macOS. |
| 109 | +- Wait for fonts before trusting cached measurements. After `document.fonts.ready`, clear your prepared-text cache, call Pretext's `clearCache()`, and call `virtualizer.measure()`. |
| 110 | +- Rerun `layout()`, not `prepare()`, on resize. `prepare()` is the expensive per-text setup; `layout()` is the cheap width-dependent path. |
| 111 | +- Clamp empty text if your UI renders empty rows as one line. Pretext returns zero height for an empty string. |
| 112 | +- Use one sizing owner per row. Do not call `measureElement` for the same row that you also size with `resizeItem` or Pretext estimates unless you deliberately want DOM measurement to override the text estimate. |
| 113 | +- Keep a fallback for unsupported runtimes. Pretext currently needs `Intl.Segmenter` and Canvas 2D text measurement. |
| 114 | +- Use `resizeItem(index, size)` when you know a row's final size outside render, such as after markdown preprocessing, image metadata loading, or a controlled expand/collapse transition. |
| 115 | + |
| 116 | +See the React Pretext example for a complete chat-style implementation: [React Pretext](./framework/react/examples/pretext). |
0 commit comments