Feature proposal: idempotent api
Today you call prepare(text, font), keep the handle it returns, and call layout(handle, width, lineHeight) on every resize. That handle is a cache the app has to carry: store it next to the text, drop it when the text, font or options change, and drop all of them after a web font loads. Forget one and you silently get the old text's height.
The proposal is an idempotent call: one that takes the text itself, leaves no handle in the app, and returns the same answer every time it gets the same inputs:
layoutText(text, font, width, lineHeight) // what layout(prepare(text, font), width, lineHeight) returns
prepare() and layout(handle) would stay, as the explicit fast path and the warm-up.
There's a working prototype for all three sets of APIs (heights, lines, rich inline) on branch idempotent-all-apis (compare): eight commits on main at 4a2387fa (#501, 2026-10-11), nothing merged. It merges with main as of #502 without a conflict, and bun test and bun run check pass on the merge. Nothing is decided: this is the first item on the API-discussion list in TODO.md, built out so it can be considered. Every export is an addition and no existing call changes its result, so none of it has to land before a release unless README is to lead with it. If you'd use one of these forms, the last section has what I'd like to know.
Terms
- Handle: what
prepare(),prepareWithSegments()orprepareRichInline()returns. - Two-step call: today's API:
prepare()thenlayout(handle), or the same pair for lines or rich inline. - Handle path:
layout(handle),layoutWithLines(handle)ormeasureRichInlineStats(handle)on a handle the app kept. The baseline for a "times" below unless another is named. - Seen text: text whose words the per-font width cache already holds. New text: text no call has had.
- New width: a width other than the one the last call for that text used.
- Live texts: the texts an app holds at once, each with its handle or its key.
- Unit: a UTF-16 code unit.
- Chat message: a slice of the bench's prose at chat lengths (a quarter 5-19 units, half 20-100, a quarter 101-400; the Latin ones average 95), not real chat text. Interface labels: Chromium's translated UI strings in 35 languages.
- The three sets of APIs: heights (
prepare,layout), lines (prepareWithSegments,layoutWithLines,walkLineRanges,measureLineStats,measureNaturalWidth,layoutNextLine,layoutNextLineRange,materializeLineRange) and rich inline (prepareRichInlineand the functions that take its handle). - Engine profile: the Blink (Chromium), WebKit or Gecko behaviour Pretext picks from the user agent, plus the one for an unknown engine.
- Stand-in Canvas: the harness's offline replacement for
measureText, used to run every profile outside a browser. It is one made-up font: at 16px a character is 8px and a space 4px, less a made-up kerning between neighbours, whatever the font's name. It tests the rules in each profile, not fonts. "Offline" below means on it. - Safari 27's WebKit: the system WebKit that installed Safari runs, in the harness's own host app (build 22625.1.29.11.27).
Summary
- It works, in three forms. Each gave exactly the two-step call's answer in every comparison outside two stale states listed under the limits (a keyed call right after
<html lang>changes; the one call between a web font's load andclearCache()). That's 12.5 million comparisons per engine profile offline, about 100,000 per browser with real Canvas, and a second round written to break it, with its own generator and seeds, which found the second of those states and no other difference. - Compose:
layout(prepare(text, font), width, lineHeight), with the handle dropped. Needs nothing new. 3-9 µs per chat message per call on seen text (an analysis of the text and a cache lookup per segment, no Canvas call), 39-172 timeslayout(handle). Fine for a screenful a frame, too slow to resize a long list. - One call with a width:
layoutText(),layoutTextWithLines(),measureRichInline(). Keeps nothing per text (it fills the per-font width cache, asprepare()does). On seen text it costs what composing costs. On new text at 320px it's 1.2-2.1 times as fast in Firefox and Safari 27's WebKit, by kind of text, and level in Chrome but for interface labels (1.2 times), because knowing the width lets it skip Canvas questions thatprepare()has to ask. - Keyed by an object of the app's:
layoutFor(message, message.text, font, width, lineHeight). The library keeps the handle for that object in aWeakMap. Of the three it's the only one near handle speed: on a new width 1-18 ns overlayout(handle)up to 1,000 live texts and about twice it at 100,000, and a tenth to four tenths of it when the width hasn't changed. But it needs one lasting object per text, and it puts an app object into the library's bookkeeping. - A store keyed by the string alone would be the nicest call to write, and it isn't proposed: nothing in the call says when an entry can go, and each rule tried for bounding the store breaks a use Pretext is for (table under Left out).
- Size: +227 lines of library code, about +0.75 kB minified and gzipped on each entry point. The existing calls return what they did and the bench called none slower. One commit changes what a
prepare()handle holds: it's 48-72 bytes bigger and keeps its text alive (open decision 4). - Decided before this: today's API stays and alternatives are additions; a new option or export needs an app or a person who needs it (
RESEARCH.md, Caching And API Design). - Open: whether to ship the one-call family, the keyed family, both or neither; whether every line function takes a
prepare()handle either way; names (Open decisions).
Caveats for every number here.
- One Mac (Apple M5 Max, 18 cores), device pixel ratio 2, the harness's pinned Chrome 154.0.8037.98, Firefox 157.0.1 and Safari 27's WebKit. Nothing was run on Windows, Android or iOS.
- The offline comparisons use the stand-in Canvas. The browser ones use fonts installed on that Mac at 11-17px (Helvetica Neue, PingFang TC, Geeza Pro, Thonburi, a
system-uilist and the chat demo's fonts), no web font. - In Chrome a context's width for a string can depend on what it measured before (
PLATFORM_BUGS.md, "a Canvas remembers what it measured"), and the one call asks Canvas fewer questions thanprepare()does. The browser comparisons found no difference; the fonts that effect is recorded in (Amiri, Noto Naskh Arabic) weren't among them. - Timings are from 2026-10-11, the fastest of 7 rounds after 2 warm-up rounds, in background windows, the timed run the only browser job on a machine at a 1-minute load of 4.6-6.4 from other work. The same code in main's build and the branch's read up to 10% apart on
layout(handle)and up to a third apart on the rows that prepare or build lines, so read a difference under 10% in the keyed columns, and under about 25% elsewhere, as nothing. - Memory was read in V8 and JavaScriptCore shells, not in a browser. The figures for a store keyed by the string come from an earlier run on a busy machine.
The three forms
Today, for comparison:
type Row = { text: string; prepared: PreparedText | null }
function heightOf(row: Row, width: number): number {
row.prepared ??= prepare(row.text, FONT)
return layout(row.prepared, width, LINE_HEIGHT).height
}
// wherever an input changes:
function edit(row: Row, text: string): void { row.text = text; row.prepared = null }
// after a web font loads:
clearCache()
for (const row of rows) row.prepared = null
The same thing in each form. After a web font loads, each needs clearCache() and nothing else.
// 1. Compose: works on main today
const heightOf = (m: Message, width: number) => layout(prepare(m.text, FONT), width, LINE_HEIGHT).height
// 2. One call with a width: new, keeps no handle
const heightOf = (m: Message, width: number) => layoutText(m.text, FONT, width, LINE_HEIGHT).height
// 3. Keyed: new, the library keeps the handle for `m` and lets it go when `m` is collected
const heightOf = (m: Message, width: number) => layoutFor(m, m.text, FONT, width, LINE_HEIGHT).height
README says not to write the first: "Do not rerun prepare() for the same text, font and options; that'd defeat its precomputation." Composing reruns it on purpose and pays the price in the tables below.
The new exports (names are placeholders):
// main entry
layoutText(text: string, font: string, maxWidth: number, lineHeight: number, options?: PrepareOptions): LayoutResult
layoutTextWithLines(text: string, font: string, maxWidth: number, lineHeight: number, options?: PrepareOptions): LayoutLinesResult
layoutFor(key: object, text: string, font: string, maxWidth: number, lineHeight: number, options?: PrepareOptions): LayoutResult
prepareFor(key: object, text: string, font: string, options?: PrepareOptions): PreparedText
// rich-inline entry
measureRichInline(items: Array<RichInlineItem | RichInlineBox>, maxWidth: number, options?: RichInlineOptions): RichInlineStats
prepareRichInlineFor(key: object, items: Array<RichInlineItem | RichInlineBox>, options?: RichInlineOptions): PreparedRichInline
measureRichInlineFor(key: object, items: Array<RichInlineItem | RichInlineBox>, maxWidth: number, options?: RichInlineOptions): RichInlineStats
Two changes ride along. The handle change: every line function takes a prepare() handle, which is what lets one prepareFor() serve all of them. That moves a line drawn on 2026-10-06 (#449): the four line functions that return no text take a prepare() handle, and layoutWithLines(), layoutNextLine() and materializeLineRange(), which return text, need a prepareWithSegments() one, so that a prepare() handle pays for nothing layout() doesn't read. And PrepareOptions gains minWidth, which isn't part of this proposal (Left out, below).
What works for which set of APIs
Composing, on main today:
layout(prepare(text, font), w, lh) // heights
layoutWithLines(prepareWithSegments(text, font), w, lh) // lines, same for the other line functions
measureRichInlineStats(prepareRichInline(items), w) // rich inline, same for the walks
Times are for Latin chat messages, seen text, against the handle path.
| heights | lines | rich inline | |
|---|---|---|---|
| Compose | 3.2-8.6 µs a call, 39-172 times the handle path | 3.6-9.9 µs, 13-23 times | 4.1-12.8 µs, 33-147 times |
| One call with a width | layoutText(). Level with composing |
layoutTextWithLines(): every line at one width. Level with composing |
measureRichInline(): line count and widest line only. Level with composing |
| Keyed | layoutFor(). New width: 1.0-1.5 times the handle path up to 1,000 live texts, about 2 times at 100,000. Unchanged width: 4-37 ns, 0.1-0.4 times |
prepareFor() handed to any line function. Handle-path speed once the key's lines were asked for; a preparation and its first line text together cost 1.3-1.7 times layoutWithLines(prepareWithSegments()) |
prepareRichInlineFor() handed to any rich function, and measureRichInlineFor(). Items array rebuilt every call, new width: 1.3-1.65 times the handle path; unchanged width: 0.25-0.6 times |
What can't be one call: anything with a width per line or several widths (the line streams layoutNextLine(), layoutNextLineRange() and layoutNextRichInlineLineRange(), a shrink-wrap search). Those take a handle, made where the lines are laid out or fetched by key. Two more aren't built: a rich paragraph's painted lines as one call (about ten more lines), and a plain-text one call for the line count and widest line, what measureLineStats() and measureNaturalWidth() give from a handle. That last is what the demos' five composed calls ask for (a label's natural width); today's nearest is the rich one, measureRichInline([{ text, font }], Infinity).maxLineWidth.
How the one call saves work
prepare() doesn't know the width, so for a word that might have to be cut between its letters it asks Canvas where the cuts would fall, the word's cut positions. (WebKit's profile measures every prefix of every word; from 80px up Gecko's does too and Blink's measures letter pairs; under 80px those two measure each letter alone, which every word shares.) A line is only ever cut inside a stretch of text with no break opportunity in it, nearly always one word, when that stretch starts the line and is wider than it. layoutText() knows its one width, so it asks only about the words wider than that. Below, that's the one-width rule; the comment in src/prepare.ts on the branch cites where each engine does this.
This is an open item on TODO.md's API list: "an option that tells prepare() a text is never cut inside a word, or the least width it is laid out at". It was left open when the rule for a word cut between letters landed (#435, 2026-10-05): labels that never wrap that way still pay the Blink profile's questions about letter pairs and the Gecko profile's prefix fit. The one call is that option with nothing for the caller to promise, since the width is in the call.
measureText calls for the same new texts at 320px (labels at 200px), two-step then one call:
| Chrome 154 | Firefox 157 | Safari 27's WebKit | |
|---|---|---|---|
| 120 Latin chat messages | 1,407 → 1,368 | 1,762 → 1,217 | 4,488 → 1,283 |
| 600 interface labels | 5,323 → 3,438 | 5,711 → 3,226 | 11,071 → 3,298 |
| 120 Thai | 1,188 → 910 | 1,362 → 929 | 2,052 → 1,070 |
| 120 mixed scripts | 2,845 → 2,565 | 2,839 → 2,283 | 5,396 → 2,471 |
| 116 Arabic | 2,262 → 2,204 | 2,260 → 2,202 | 5,926 → 2,245 |
| 120 CJK | 2,644 → 2,644 | 2,697 → 2,452 | 2,755 → 2,455 |
The saving isn't everywhere. Nothing is skipped in letter-spaced text, in text with a soft hyphen or a zero-width space the browser doesn't break after (zero-width-glue in README), or in pre-wrap text with a space, a tab or a line break; under the Chromium profile in text with two kana in a row or any character in U+2018-U+301F or U+FF08-U+FF60 (Blink's own quick test for punctuation it may kern: CJK and fullwidth punctuation and U+3000, but also curly quotes and apostrophes, the ellipsis and arrows; 28 of the 120 Latin chat messages above); under the Gecko profile in text with U+3000; or in a rich paragraph with a box, extraWidth, letter spacing or an item with break: 'never'. There the one call asks everything prepare() asks: it's no faster, and the answer is still the same.
It also shrinks as the width narrows (at a width under most words there's nothing to skip), and it's put off rather than removed where prepare() follows: the one call caches a word's width without its cut positions, so the first prepare() of the same words asks for them, as does a one call at a narrower width.
In rich inline the stretch with no break in it is often several pieces: a word can be in two styles, so the runs between two break opportunities cross items. The one call sums those runs over the finished paragraph, and where a run wider than the width holds a word it skipped, it prepares the paragraph again in full (a text has the same check, for a word with a control character inside). That check does real work: with it removed, 104-200 of 20,504 rich comparisons differ per profile.
Does it give the same answer
Every comparison is a new form's result against the two-step call made by main's build on the same input in the same state. For lines that's everything the line functions return, both streams included, at a width that changes per line.
- The checked-in harness cases the library can express, up to 4,000 units (72,031 of 72,471), plus the bench's texts: 76,782 inputs (68,990 texts, 7,792 rich paragraphs), each at 11 widths (0, 1, a third, half, three quarters, once and 1.5 times its own width, 37.3, 120, 333, Infinity), offline. 12,470,462 comparisons in each of the four profiles, 0 differ. An input counts once per width and form, and 2.5 million of them are
minWidthhandles. - A fuzz aimed at the one-width rule: 6,000 random texts in each of the Chromium, WebKit and Gecko profiles (words joined by spaces, control characters, zero-width spaces, no-break characters such as NBSP and the word joiner, punctuation, CJK and kana), each also cut at random places into up to four items in three fonts, at widths exactly at, 0.01px under and 0.01px over the width of a segment and of runs of two to five. About 860,000 comparisons per profile, 0 differ. The one call asked Canvas less than
prepare()in 24%, 54% and 63% of its heights (Chromium, WebKit, Gecko); in the rest the two take the same path. - Sequences on keyed entries: one key taken through a changed text and back, font, each option, each field of an item, a box put in and taken out, items added and removed,
clearCache(),setLocale(), the page language. 847,990 comparisons per profile, 0 differ, with one stated exception (the<html lang>state below). - Real Canvas, in the three browsers: 896 texts of six kinds and 547 rich paragraphs at seven widths, 99,624 comparisons per browser, 0 differ. Keyed sequences,
setLocale()and web fonts didn't run in a browser. - A second round, written to break it, with its own generator and seeds: odd keys (frozen, sealed, a Proxy, a function, no prototype), inputs changed in place and put back, widths of NaN, -0 and Infinity, a preparation that throws, ids through a
Map. 2.49 million comparisons per profile, 0 differ. One set was kept apart: between a web font's load andclearCache()the one call differed from main's two-step call in 202-938 of 4,500 comparisons, by profile (the font-load state below). Then in the browsers at widths within 1e-9px to 0.3px of a word's width, over 975 texts and 397 paragraphs: about 200,000 per browser, 0 differ, with the one call asking Canvas less thanprepare()at 57-72% of the text widths. - The comparisons can fail, with one hole: six copies of the branch, each with one rule removed, went through the same scripts. Five show 90 to 39,708 differences. The sixth, the kana rule below, shows none in 3.45 million offline comparisons and none in the second round: 12 fuzz comparisons and its unit test are what hold it.
One thing found while building it: the one-width rule needs a word's width to be final when it decides to skip. Chrome's kerning between two kana (#497) is added afterwards, so in a test font whose kana are 16px wide and whose pair うえ is laid out 1px wider than it measures (32px measured, 33px laid out), layoutText('うえ', font, 32.5, 20, { wordBreak: 'keep-all' }) gave 1 line where layout(prepare()) gives 2. The prototype now skips nothing in text with two kana in a row under the Chromium profile, with a unit test. That's the cautious fix, where a second check of the widened words would do.
That is the one call's standing cost. The rule is tied to every correction that changes a word's width after it's measured, and the list above of text it skips nothing in is the list of those so far. Each engine fix of that kind, as #497 was, has to be checked against it, and the harness's own inputs didn't reach this one. #313 parked its edit window partly for the same kind of coupling.
Cost
A "new width" differs from the call before. The run's conditions and noise are under the caveats above.
Heights, chat messages (ns per call unless marked; in brackets, times layout(handle)):
| browser | live texts | layout(handle) |
layoutFor(), new width |
layoutFor(), same width |
layout(prepare()), seen |
layoutText(), seen |
|---|---|---|---|---|---|---|
| Chrome 154 | 10 | 39 | 44 (1.12x) | 4.7 (0.12x) | 3.17 µs (81x) | 3.09 µs (79x) |
| Chrome 154 | 1,000 | 56 | 73 (1.29x) | 13.5 (0.24x) | 6.04 µs (107x) | 5.92 µs (105x) |
| Chrome 154 | 100,000 | 60 | 131 (2.17x) | 26 (0.43x) | 6.57 µs (109x) | 6.54 µs (109x) |
| Firefox 157 | 10 | 38 | 56 (1.46x) | 13.0 (0.34x) | 6.63 µs (172x) | 6.29 µs (163x) |
| Firefox 157 | 1,000 | 75 | 92 (1.24x) | 16.7 (0.22x) | 8.55 µs (114x) | 8.29 µs (111x) |
| Firefox 157 | 100,000 | 86 | 183 (2.13x) | 26 (0.30x) | 8.57 µs (100x) | 7.88 µs (92x) |
| Safari 27's WebKit | 10 | 46 | 47 (1.01x) | 4.4 (0.09x) | 3.44 µs (74x) | 3.18 µs (69x) |
| Safari 27's WebKit | 1,000 | 66 | 72 (1.08x) | 10.4 (0.16x) | 4.78 µs (72x) | 4.39 µs (66x) |
| Safari 27's WebKit | 100,000 | 139 | 245 (1.77x) | 37 (0.26x) | 5.48 µs (39x) | 4.85 µs (35x) |
For texts of 2,000 units the keyed call is 1.00-1.10 times the handle path on a new width (the lookup disappears under the line walk) and 9-17 ns at an unchanged one, against about 1-1.5 µs for layout(handle).
Rich inline, chat messages as three items: measureRichInlineFor(key, items) with the items built anew every call is 17-43 ns over measureRichInlineStats(handle) up to 1,000 live paragraphs and 64-130 ns over at 100,000. Building the three items is 7-11 ns of that. At an unchanged width it's 0.25-0.6 times the handle path.
New text (µs per text at 320px, labels at 200px; median of 8 batches, each form on batches of its own. One batch of chat messages differs from the next by 2-3 times, so for the chat rows read a difference under about 30% as nothing; batches of labels differ by about a fifth):
| Chrome 154 | Firefox 157 | Safari 27's WebKit | |
|---|---|---|---|
chat messages: layout(prepare()) → layoutText() |
21.8 → 20.5 | 24.3 → 17.6 (1.4x) | 37.9 → 19.1 (2.0x) |
chat messages: layoutWithLines(prepareWithSegments()) → layoutTextWithLines() |
25.2 → 25.2 | 27.7 → 18.5 (1.5x) | 44.4 → 24.4 (1.8x) |
three items: measureRichInlineStats(prepareRichInline()) → measureRichInline() |
27.1 → 30.0 | 40.7 → 20.8 (2.0x) | 41.8 → 29.2 (1.4x) |
interface labels: layout(prepare()) → layoutText() |
75.9 → 61.7 (1.2x) | 33.9 → 27.7 (1.2x) | 62.5 → 29.9 (2.1x) |
the chat demo's paragraphs: measureRichInlineStats(prepareRichInline()) → measureRichInline() |
16.2 → 16.8 | 19.2 → 16.4 | 29.4 → 23.2 (1.3x) |
chat messages: layout(prepare()) → layoutFor() with a new key |
21.8 → 29.7 | 24.3 → 26.4 | 37.9 → 48.0 |
The last row is inside that noise (main's own layout(prepare()) on other batches read 22.0, 29.5 and 40.0): a keyed call with a new key makes exactly prepare()'s Canvas calls.
Throughput. Composing and the one call pay a preparation per call. On seen text 30 texts a frame is 0.1-0.4 ms and 1,000 is 3-13 ms. A resize of 100,000 rows is 0.5-0.9 s for heights, where handles take 6-14 ms and keys 13-25 ms, and 0.7-1.3 s for rich inline against 11-26 ms and 18-37 ms. A frame of new text costs a first preparation in any form, 18-44 µs a chat message in the table above. The price grows with the text: a 2,000-unit text is 76-156 µs a call where layout(handle) is 1-1.5 µs, and one text of 100,000 units is 4 ms (Latin) to 14 ms (CJK, Thai) a call (#313's update), so long text still wants a handle per paragraph (README, #362).
Memory. A keyed text entry is 140-159 bytes over its handle, a keyed paragraph entry 380-540 bytes over its handle (most of it the copy of its items' fields). For 100,000 chat messages the entries add 14-16 MB to the 156-159 MB the handles take with or without keys (149-154 MB on main: the handle change is the difference). The one call and composing keep nothing per text. What they fill is the per-font width cache, at most 10-17 MB after 100,000 chat messages were first prepared (earlier run, the library's own tables counted in).
Size. +227 lines of library code (+415 with comments). Main entry 42,395 → 43,124 bytes minified and gzipped, rich-inline entry 46,570 → 47,329.
The existing API. bun harness bench against main: 192 entries, 191 within noise, and the one called slower (Firefox, new Arabic text) read within noise when timed again alone, twice. A row within noise says nothing of a change under its band: 2-10% on seen text, 3-12% on the line rows, 6-34% on new text. Offline, no existing call changes its lines and each handle is main's plus two fields. bun harness check and gate weren't run on the branch.
Where each form is weaker than a handle
All three:
- A reply that streams in. Each new version of the text prepares the whole text again, as with handles today. That's the incremental-prepare question (#313; #153 asked for an append call), not this one, and README's answer stands: a handle per paragraph or block (#362). A key per block reuses what didn't change and leaves what nothing uses to the collector. A textarea's paragraphs are strings split anew on every edit, with no object to key on.
- A web font that loads later. No form sees it;
clearCache()is still the call. With keys that one call is all of it (every key prepares again at its next call); with handles the app also drops its handles. The same goes for a device pixel ratio that changes (#418) and forsetLocale().
Compose and the one call can't carry a big resize (Throughput, above). The one call also:
- Between a web font's load and
clearCache(), it can leave a word cached with the old font's width and the new font's cut positions, and its answer can then differ from the two-step call's (202-938 of 4,500 comparisons, by profile).clearCache()ends it, and main can reach the same kind of state today through a rich-inline item withbreak: 'never'.
Keyed:
- It needs one lasting object per text. Objects made anew every frame never find their entry, so every call prepares, at composing's price. Ids work through a
Mapof key objects the app keeps and deletes from. - One key is one text in one style. The same key asked about two fonts in turn prepares on every call. Use a key per style, or a handle.
- A range is read against whatever the key holds now. Every use passes the text, font and options again. Two call sites that disagree (
pre-wrapon the walk, left out onmaterializeLineRange()) get another preparation's text with no error, and make the key prepare on every call. A kept handle can't do that, since its options are in it. - Its speed assumes the same string object each call. The timings pass the string the key's entry already holds, which compares at once. An equal string made anew every frame (a template, a slice) is compared unit by unit first: 0.2-0.4 ns a unit in an earlier run, so 20-40 ns for a 95-unit message on a call that costs 4-37 ns at an unchanged width.
- The page language. Composing and the one call read
<html lang>on every call, asprepare()does. A keyed call that finds its entry doesn't, so right after<html lang>changes and before any text is prepared under the new language, it can give the old language's answer (0-140 of 29,172 comparisons, by profile). That's weaker than composing, not than a handle: a kept handle never follows the language. An app that sets a locale withsetLocale()has no gap. Closing it for the rest is a DOM read per call, 2-6 ns. Not built. - A handle from
prepareFor()belongs to the entry. After an edit orclearCache()the entry holds another one, so fetch it where it's used rather than keeping it across frames. - After
clearCache()a key that's never asked again keeps its old handle until the key is collected, and there's no call to let one key go. The frame afterclearCache()costs a preparation per live key, as with handles. - Keyed lines analyze the text twice the first time line text is asked for after each preparation (the two together cost 1.3-1.7 times
layoutWithLines(prepareWithSegments())). One changed line in the entry lookup, preparing with the segments' text where the key's last handle had it, would end that for every preparation after a key's first, so for an edit or a streamed reply; a new key's first paint would still pay it. Not done. - "The same items" is their fields, not their identity, since apps rebuild the items array every frame or change items in place: five comparisons per item. An item added at the end prepares the whole paragraph again, because two things about the old last item depend on what follows it: whether its trailing space is dropped, and in Chrome whether its closing fullwidth mark loses half an em.
- A preparation that throws leaves the key's entry as it was.
Left out
The string as the key, layout(text, font, width, lineHeight) over a hidden store. It works, and in Chrome and Safari 27's WebKit it's as fast as the keyed form when the app passes the same string objects (in Firefox it read 1.2-2.4 times slower even then). Three problems:
- A text that changes every frame leaves an entry per version. A reply streamed to 3,991 units in 997 frames left 997 entries, about 21 MB by estimate. Keyed by an object it's one entry replaced in place.
- Its cost depends on how the app made the string. The same string object looks up in 4-16 ns at any length. A string built this frame (a template, a slice,
JSON.parse) is hashed in full first: about 0.3 ns per unit in Chrome and WebKit, 1.1 ns in Firefox, so 2.1-2.6 µs for a 2,000-unit message in Firefox, more than that message's whole layout. - Nothing in the call says when an entry can go, and each rule tried fails:
| rule | how it fails |
|---|---|
| a byte limit, oldest entry out first | more live texts than the limit: every call prepares again and pays for the miss on top (+11-14% in Chrome and WebKit). The step from under to over the limit is a 40-140 times jump per call |
| a sweep at the end of each frame | a virtualized list lays out what's visible, then needs every row's height at the next resize, and the sweep has dropped them. The library also can't see where a frame ends |
WeakRef to the handle |
nothing else holds the handle: one collection emptied 20,000 of 20,000 entries in V8 and in JavaScriptCore |
FinalizationRegistry |
watches objects, never strings |
| the order of calls within a frame | one row inserted at the top shifts every place, so every text after it prepares again |
It's also the store apps write for themselves, which is where it works: the app knows its frame and its live set.
RESEARCH.md records the same for hidden stores (Dead Ends, Caching, State And API Designs; the study is rebuild/research/IDEMPOTENT-API.md on branch rebuild-20260916): eviction by turnover dropped live entries whenever the working set more than doubled within a pass, release per pass rebuilt everything when a view laid out only its visible rows between resizes, and pass ends inferred from task timing broke once a pass spanned tasks. Two generations turned over at an explicit endPass() rebuilt nothing, but held up to three times the live entries under churn and never shrank, and endPass() is an API of its own.
An earlier keyed prototype (2026-09-26) is recorded there as 1.1-1.5 times slower heights, nothing faster, and wrong lines across differing options. The cost matches up to 1,000 live texts. The wrong lines are still reachable: they were a line range walked under one set of options and materialized under another, which is the keyed limit above. What's new is something faster: with the last width's line count kept on the entry, a frame at an unchanged width costs the lookup alone.
Stateless layout was parked there too, to reopen "if from-scratch layout gets much cheaper". Composing was 16.8 µs a message in Chrome then (126-character messages on a busy machine, before #340 and #344 made analysis cheaper); it's 3.2-6.6 µs now on 95-unit ones. The bar that entry sets, 10,000 messages a frame, is 1.6 µs.
minWidth, prepare(text, font, { minWidth }): the one call's saving kept on a handle. It's the least-width option from TODO.md's API list, built: at its width and wider, 846,774 comparisons per profile for heights and as many for lines, 0 differ. Below that width nothing checks, so a height can come out too small with no error. It's in the branch only because the keyed commit compares it, and it isn't part of this proposal. What it alone would serve is a handle laid out at many widths above a known least one, such as a column with a CSS min-width.
What's in the branch
Eight commits, each with unit tests; bun test and bun run check pass at the tip. The comparison and timing scripts aren't on the branch yet.
| commit | what | library code lines |
|---|---|---|
| 9d15a956 | the handle change: every line function takes a prepare() handle |
+18 |
| 0d863fc1 | layoutText() |
+45 |
| a0af2ff9 | prepare(text, font, { minWidth }) |
+1 |
| 75477281 | layoutFor(), prepareFor() |
+63 |
| 5657b625 | prepareRichInlineFor(), measureRichInlineFor() |
+78 |
| 159da7ed | tests: every line function takes the handle prepareFor() keeps |
0 |
| 15da76e4 | layoutTextWithLines() |
+5 |
| 2416b08a | measureRichInline() |
+17 |
On the first commit: a prepare() handle, which on main keeps no string, now keeps the text it analyzed, and builds its segments' strings from it the first time a function asks for line text, with no Canvas call. That's 48-72 bytes more per handle where the app keeps the text anyway; where the app drops the text after preparing, the handle now keeps it alive, 210-250 bytes more for a 95-unit message. Building the strings analyzes the text a second time, so layoutWithLines(prepare(text)) costs 1.34-1.62 times layoutWithLines(prepareWithSegments(text)) on seen text. Writing the strings onto the handle is the one place a handle changes after it's returned. (An earlier try at one handle type kept every segment's string and cost 1.5-2.1 times the heap per handle.)
For a text's heights, the keyed form is also about a dozen lines an app can write itself today (for line text it keeps a prepareWithSegments() handle instead; the rich-inline one, which compares each item's fields, is about thirty):
const entries = new WeakMap<object, { text: string; font: string; epoch: number; prepared: PreparedText }>()
let epoch = 0 // add 1 wherever you call clearCache() or setLocale()
function prepareFor(key: object, text: string, font: string): PreparedText {
const e = entries.get(key)
if (e !== undefined && e.text === text && e.font === font && e.epoch === epoch) return e.prepared
const prepared = prepare(text, font) // before the entry changes, so a throw leaves it as it was
entries.set(key, { text, font, epoch, prepared })
return prepared
}
The library's version adds that clearCache() and setLocale() move the epoch themselves, that the options are compared too, and the kept line count.
Open decisions
- Say what composing costs in README, and ship nothing new? It needs no export. README's rule against rerunning
prepare()would get the price beside it (3-9 µs for a chat message seen before, about a hundredlayout()calls) and where that's fine: a screenful a frame, or text laid out once, as in #18. - The one-call family?
layoutText,layoutTextWithLines,measureRichInline: three exports, 67 lines of their own (85 with the handle change they were built on). For: it's the shapeTODO.md's API list describes (layout that takes the text itself, withprepare()as an optional warm-up), it keeps nothing per text, so there's no entry to bound or invalidate, and on new text in Firefox and Safari 27's WebKit it asks Canvas least. Against: on seen text it costs what composing costs, which needs no export; the saving is put off to the firstprepare()of the same text; and the one-width rule is one more thing every engine fix has to keep exact. If it ships, does README lead with it? That's the one reason to land it before a release. - The keyed family? It's the only one of the three fast enough to resize thousands of rows. But its key is an object of the app's, and the project's rule so far is immediate mode, where nothing relies on object identity (
RESEARCH.md, Caching And API Design). Options: ship two exports (prepareFor,prepareRichInlineFor: about 140 lines with the handle change), ship four (with the kept line counts: 159), or show the dozen lines above in README and ship nothing. - The handle change (9d15a956): with the keyed family, alone, or not. It reopens the 2026-10-06 decision (#449) that the three line functions that return text keep needing a
prepareWithSegments()handle, and bends the rule thatprepare()pays for nothinglayout()doesn't read. What it buys: oneprepareFor()serves every line function, so keyed lines need it; composing and the one call don't. What it costs: 48-72 bytes on everyprepare()handle, the text kept alive, and the second analysis above. minWidth, the openTODO.mditem: leave its saving to the one call, or keep the option for handles laid out at many widths.- Names. All placeholders.
- If keyed ships: read
<html lang>on every keyed call (2-6 ns on a call that costs 4-37 ns at an unchanged width), or keep the stated gap? Prepare with segments where the key's last handle had them? A call that lets one key go? - If the one call ships: a rich one call that returns lines, a plain one for the line count and widest line, and whether
layoutTextWithLines()should give source offsets, since its lines' cursors point into a handle the app never holds.
Not done or not checked: bun harness check and gate on the branch; bench rows for the new calls; memory read in a browser; README and changelog text; a second read of the engine citations behind the one-width rule; the new calls in a worker and in a host with no Canvas (they prepare, so README's notes for prepare() should hold); a keyed call made again for the same key from inside a line walk's callback; what the handle made and dropped per composing call costs in collections (the timings are the fastest of 7 rounds, which a collection wouldn't be in); phone browsers.
If you'd use this
A new export needs someone who needs it. What's already written, in each form:
- Composed: #18 lays out 100,000 different sentences once each. The demos compose in five places, each the natural width of a short text,
measureNaturalWidth(prepare(text, font)). Apps in the wild wrap the composed call under this proposal's signature. - Keyed by an object of the app's: apps keep
WeakMaps on the message object that hold the height at the last width, and React hooks keep the handle inuseMemoon text, font and options. - Keyed by the string:
Maps from text to handle, one never emptied until unmount, one capped at 2,000 entries, anddynamic-layout.tsamong the demos.
If that's you, it'd help to know:
- which form you'd reach for;
- how many texts are live at once, and whether you lay all of them out on a resize or only what's visible;
- whether you already have one lasting object per text (a message, a row), or build new ones every frame;
- whether you wrap
prepare()in a cache of your own today, and what it's keyed on.
Related threads
| # | state | relevance |
|---|---|---|
| #313 | open | Incremental prepare, for text that changes |
| #153 | closed, not planned | A request for an append call for streamed text |
| #18 | open | 100,000 different sentences, each prepared and laid out once: the composed call on new text |
| #449 | merged | Which line functions take a prepare() handle (2026-10-06); the handle change here moves that line |
| #435 | merged | The rule for a word cut between letters; it left open the option that the one call's saving answers |
| #418 | open | Emoji widths go stale when the device pixel ratio changes: one more clearCache() after which an app drops its handles today |
| #362 | merged | README's handle per paragraph for long text edited live |
Sharing a few concrete data points for the four questions under "If you'd use this" from VCPChat (https://github.com/lioensky/VCPChat ), an open-source Electron + Vanilla-JS multi-agent desktop client. Full disclosure upfront: our Pretext integration is currently a mix of active hot paths and half-wired caches, which actually highlights several of the failure modes you noted in the issue:
1. Which form we'd reach for
- The one-call
layoutText(text, font, width, lineHeight): In our Web Worker markdown compiler (modules/renderer/renderWorkerRuntime.js:49-57), we currently run the composed call for plain-text messages without block/inline markup:
(Right now the main thread only stashes that number onestimatedHeight = layout(prepare(job.text, font), width, lineHeight).height; // ... finally { clearCache(); }contentDiv.dataset.vcpEstimatedHeightatmessageRenderer.js:3725to skip main-thread warm-up and hasn't wired it into scroll-range sizing yet; once we do, a statelesslayoutText()with the one-width skip rule fits a worker job better than creating and immediately clearing a handle.) - The keyed
layoutFor(key, ...)/prepareFor(key, ...)(with the9d15a956unified handle): For our two paths that actively consume layout results across frames:- Desktop widget auto-resizing (
Desktopmodules/core/widgetManager.js:429-439), where we compareestimateHeightagainstcurrentHeightand return early ifMath.abs(estimatedHeight - currentHeight) < 2to skip togglingdisplay: inline-blockand readingscrollWidth/scrollHeight. - Our Cadenza lyric stage (
Musicmodules/music-stage/modes/cadenza-manager.js:22-53, adapted from Folia), which callsprepareWithSegments+layoutWithLinesand also readsprepared.widthsandprepared.breakableFitAdvancesdirectly to compute glyph-range widths for collision-avoiding lyric fragments.
- Desktop widget auto-resizing (
2. How many texts are live at once, and what happens on resize
- Widgets / Notes / Memo cards: Roughly 20–500 items at once. On resize,
pretextBridge.recalculateAll(newWidth)iterates over the cachedPreparedTextMap and re-runslayout()(though in Notes and Memo today those cached heights are only warmed, not yet read back into masonry layout). - Main Chat (
modules/messageRenderer.js:4116-4183): Typically hundreds to ~2,000 messages in a long topic. Messages with collapsible tool cards, tables, math, or scripts skip Pretext (L4126-4128). Pure-text messages warm the cache through a single per-windowrequestIdleCallbackqueue draining whiledeadline.timeRemaining() > 1(commit b70a3be7—previously each message queued its own idle callback, so ~40 callbacks each readingclientWidthran ahead of batched history insertion and contributed to a ~0.4s open delay alongside main-process metadatalstatscans).
3. Lasting object per text vs. rebuilt every frame
- Lyric stage (
stage-lyric-performance.js:223-260): Each parsedlineobject persists across playback frames; we currently cache compiled layouts in an 8-entryMapkeyed on thelineobject itself (cache.get(line)), paired with manualconfigEpochandfontEpochcounters. - Chat & Widgets: Each item has a lasting
widgetDataobject or outer<article class="message-item">shell element (which stays in the DOM even when its inner.md-contentsubtree is evicted offscreen), so keying aWeakMapon the model or shell element would be very natural.
4. How we wrap prepare() today (and a real footgun we hit)
In modules/renderer/pretext-bridge.js:19-27 (plus an unwired bridge in ScriptoriumModules/scriptorium-pretext-bridge.js), we wrote three parallel Maps (preparedCache, heightCache, textSnapshot), wired manual pretextBridge.evict(messageId) calls into cleanupMessageDomResources / removeMessageById (messageRenderer.js:2344, 2356), and called clearAll() in setChatFonts().
- Real footgun from maintaining string-keyed
Maps by hand: in one secondary view (RAGmodules/RAG_Observer.js:2404), a contributor passed"rag-chat-" + Date.now()as the cache ID, silently turning theMapinto an append-only leak for that window's lifetime. Moving handle lifetime toWeakMap-backedlayoutFor/prepareFor(withclearCache()bumping an internalepoch) would eliminate both that class of leak and our manual eviction plumbing.
(Small tangent on #312's Tall rooms 60px back-and-forth reload thrashing & #489's Chromium scroll_anchor.cc interaction, in case a DOM-side comparison is useful: in modules/renderer/offscreenDomWindow.js, where we evict offscreen .md-content subtrees via replaceChildren() and lock measured pixel heights onto the outer <article> shell, separating warmMargin = 1500 from coldMargin = 3000 gave us a 1500px hysteresis band so small back-and-forth scrolls don't thrash between evict and wake; and in compensate() (L37-43) we record the first visible item's getBoundingClientRect().top before a batch and only apply root.scrollTop += delta when Math.abs(delta) > 0.5 so we don't double-compensate on top of Chromium's automatic scroll anchoring. The clear trade-offs on our side are that each batch leaves up to 0.5px of sub-pixel rounding unadjusted, every message still needs one initial DOM layout to measure its shell, and onResize() (L190-213) has to progressively wake cold shells back into the DOM at batchSize = 3 per animation frame because locked heights go stale—whereas #312 computing exact chunk heights purely in Pretext avoids touching the DOM on resize altogether.)