Is there a supported fallback when `layout()` undercounts browser lines?
Hi — I'm using Pretext in a paginated document editor, where layout().lineCount feeds directly into the height we reserve for a paragraph or table cell.
I've run into a case where Pretext returns fewer lines than Chrome. Overcounting is usually tolerable for pagination because it just leaves some extra space, but undercounting makes later content look like it still fits and can leave the rendered page overflowing.
I know Pretext isn't trying to reproduce every detail of native layout, and I'm not suggesting that layout() should start reading the DOM. The problem for us is that the result doesn't tell a caller when it has underestimated, so there is no safe fallback unless we already know which text patterns are risky.
Reproduction
I rechecked this on main at 2e5e2bd on 2026-09-17, using installed Chrome on macOS at DPR 2:
text {测试内容.csjg.ysjcxxnr.ypbh}
font 16px "Songti SC", "PingFang SC", serif
lineHeight 20.96
whiteSpace normal
direction ltr
At both widths below, Chrome lays the text out over three lines while Pretext returns two:
| width | Chrome | Pretext main |
|---|---|---|
| 120px | {测试内 / 容.csjg.ysjcxxnr.yp / bh} |
{测试内容.csjg. / ysjcxxnr.ypbh} |
| 135px | {测试内 / 容.csjg.ysjcxxnr.ypbh / } |
{测试内容.csjg. / ysjcxxnr.ypbh} |
Browser side:
<!doctype html>
<html lang="en">
<div id="text" style="width:120px;font:16px/20.96px 'Songti SC','PingFang SC',serif;white-space:normal;word-break:normal;overflow-wrap:break-word">{测试内容.csjg.ysjcxxnr.ypbh}</div>
<script>
console.log(document.querySelector('#text').getBoundingClientRect().height)
// 62.8828125px on my machine: three line boxes
</script>
Pretext side:
import { prepare, layout } from '@chenglou/pretext'
const text = '{测试内容.csjg.ysjcxxnr.ypbh}'
const font = '16px "Songti SC", "PingFang SC", serif'
const prepared = prepare(text, font)
layout(prepared, 120, 20.96) // { lineCount: 2, height: 41.92 }
layout(prepared, 135, 20.96) // { lineCount: 2, height: 41.92 }
The native block height was 62.8828125px at both widths. I also added these two cases temporarily to the repository's wrapping runner with height and lineCount required; both fail against current main in the same way.
The brace case may well be fixable as another line-breaking rule. My broader question is what a correctness-sensitive caller should do when the next native mismatch hasn't been identified yet.
Would a native verification path make sense?
TODO.md currently asks:
Is a slower diagnostic verification mode useful enough to support without changing
layout()?
For pagination, it would be useful if that slower path could return a result we can actually use, rather than only report that the model disagrees with the browser.
For example, it could be an opt-in browser-backed helper, kept completely separate from prepare() and layout(), that verifies one result under an explicit DOM/CSS contract and returns native line ranges when they differ. Another possible shape would be an adapter where the caller supplies the native observation and Pretext handles mapping it back to its range model.
I don't think a general Canvas-only promise that the returned line count is always an upper bound is realistic, especially given the limits described in #321. If native verification doesn't belong in this package either, a documented answer along the lines of "lineCount is a point estimate; callers that cannot tolerate undercounting should do X" would still help. I haven't found an X that doesn't require rebuilding quite a lot of layout plumbing.
What we do today
We currently run a narrow DOM Range probe for text patterns we already know can be risky. It builds an equivalent hidden text block, extracts native line boxes and source offsets, and replaces both the height and break positions when they disagree with Pretext.
That only works when the probe can faithfully reproduce the inline context: no atomic items or extra widths, compatible hard-break handling, and uniform typography. When native probing isn't available, our fallback for plain text is an intentionally loose grapheme-level bound. It avoids undercounting, but it also causes early page breaks and large blank areas.
This came from a real paginated table overflow, not a fuzz-only mismatch. I previously reported #225 and #274; both concrete cases were fixed and let us remove narrower workarounds. This issue is about whether there can be a supported escape hatch for the mismatches we haven't isolated yet.
Happy to provide more production-derived cases or help narrow down an API if this is something you'd consider supporting.
sorry for the slow answer. two parts: the cases you filed, then the fallback.
the cases. you tested main at 2e5e2bd. about a week later #340 replaced Pretext's own line-break rules with ports of each browser's line breaker and its data, and that's what fixes these. the old rules allowed a break after csjg.. no browser breaks between a . and a letter, so 容.csjg.ysjcxxnr.ypbh} is one unbreakable word that's wider than the box: the browser moves it to its own line and cuts it where it overflows (overflow-wrap: break-word). main does the same now:
| width | Chrome | Pretext main |
|---|---|---|
| 120px | {测试内 / 容.csjg.ysjcxxnr.yp / bh} |
same, 3 lines |
| 135px | {测试内 / 容.csjg.ysjcxxnr.ypbh / } |
same, 3 lines |
same in Firefox and in Safari's WebKit. both are in the test cases as filed reports, and table cells of that shape went into the real-usage sample I score against, so they stay fixed. it's on main only: nothing after 0.0.9 is on npm yet.
the fallback. honest answer: there isn't a supported one. lineCount is a prediction, it can be off in either direction, and nothing in the result says when. there's no upper-bound mode, and like you I don't think a Canvas-only one is realistic.
what I can say:
- there are far fewer unknowns than when you filed. before #340 the break rules were my approximation of the browsers'. now they're the browsers' own rules and tables, so in Chrome most of what's left is widths that Canvas reports differently from the page, not where a line may break.
- one of the Chrome width gaps closed with #408: fonts that kern against the space (Arial, Times New Roman, Roboto) measured slightly wide, so a paragraph could take a line more than Chrome gives it. that's your tolerable direction, but it was still wrong.
prepare()andlayout()won't read the DOM, so a native check can't live in them. a separate opt-in helper that verifies one result against the browser isn't planned for now: it's a potentially heavy API to carry, so I'd rather wait and see how many people need it.- until then your
Rangeprobe is the right fallback. I'd point it at what you're about to commit to a page, comparing the painted paragraph's height withlayout()'s after the fact and paginating again on a mismatch, rather than at text patterns you already know are risky, since the next mismatch won't be one of those.
and yes to more production cases. the ones you've sent (#225, #274, this one) all ended up as test cases, and that's what actually moves this.
Here are three more cases from our paginated editor, for regression testing. With the older version we used, they produced too few lines or different line breaks, affecting table heights and page splits.
I rechecked them on 2026-10-13 at main@848f5501, on macOS with Chrome 152, DPR 2 and lang="en".
The DOM used white-space: pre-wrap; overflow-wrap: break-word; word-break: normal, with no padding or borders. The Pretext side used prepareWithSegments(..., { whiteSpace: 'pre-wrap' }) and layoutWithLines().
Line counts and the text on each line matched Chrome at all 20 widths:
| Text | CSS font / line height | Widths (px) | Result |
|---|---|---|---|
试验后/试验 |
24px "Songti SC", "PingFang SC", serif / 28px |
24, 30, 36, 42, 48, 54, 60, 72, 96 | 9/9 matched; at 60px: ["试验","后/试","验"] |
输出电压(Vdc) |
12px "Songti SC" / 15.72px |
30.3125, 42.3125, 48, 60, 72 | 5/5 matched; at 42.3125px: ["输出电","压","(Vdc",")"] |
{重复区-分组.rise_type} |
16px Arial / 20.96px |
56, 60, 64, 68, 72, 76 | 6/6 matched; at 64px: ["{重复区-","分","组.rise_t","ype}"] |
While investigating a 14pt CJK line-end issue in our paginated editor, I reduced it to this case where a fractional font size produces one line too few.
Checked main@0e6b75fb on macOS 15.7.3, first in embedded Chromium 152, then in headed Google Chrome 155.0.8059.41. Both were tested at DPR 1 and 2 (CDP emulation), with the same results.
Both sides use the system Songti SC font (actual face: STSongti-SC-Bold), 700 18.6667px "Songti SC", content width 261.25px, line-height 26px, and pre-wrap / overflow-wrap: break-word / word-break: normal.
史 repeated 14 times |
Characters per line | Height |
|---|---|---|
| Pretext | 14 (one line) | 26px |
| DOM | 13 / 1 (two lines) | 52px |
The whole-run Canvas width is 261.23984px and the DOM width is 261.3125px, on opposite sides of the 261.25px container width. Integer-size controls at 18px/252px and 19px/266px give one line on both sides; so does widening the fractional-size case to 261.5px.
The fractional size comes from converting the document's 14pt size to CSS px; rounding to a whole pixel changes the original font size. The expected result at 261.25px is 13 / 1, matching the DOM. If this is a known limitation, could you confirm its applicable conditions?
Please verify in a headed browser. In headless mode on the same Google Chrome version here, the DOM natural width is 261.25px and both sides give one line, so the mismatch does not reproduce (CDP DPR 1/2).
Minimal reproduction
import { prepareWithSegments, layoutWithLines } from '../src/layout.ts';
const text = '史'.repeat(14);
const font = '700 18.6667px "Songti SC"'; // 14pt resolved to CSS px.
const width = 261.25;
const lineHeight = 26;
await document.fonts.load(font, text);
await document.fonts.ready;
const prepared = prepareWithSegments(text, font, { whiteSpace: 'pre-wrap' });
const pretext = layoutWithLines(prepared, width, lineHeight);
const el = document.createElement('div');
el.style.cssText = `display:block;width:${width}px;font:${font};line-height:${lineHeight}px;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;margin:0;padding:0;border:0`;
el.textContent = text;
document.body.append(el);
const bands: { top: number; text: string }[] = [];
for (let i = 0; i < text.length; i++) {
const range = document.createRange();
range.setStart(el.firstChild!, i); range.setEnd(el.firstChild!, i + 1);
const rects = [...range.getClientRects()];
if (rects.length !== 1 || rects[0].height <= 0) throw new Error('Unreliable character rect');
let band = bands.find(b => Math.abs(b.top - rects[0].top) < .5);
if (!band) { band = { top: rects[0].top, text: '' }; bands.push(band); }
band.text += text[i];
}
const dom = { width: el.getBoundingClientRect().width, height: el.getBoundingClientRect().height,
lines: bands.map(b => b.text) };
el.style.width = '2000px';
const range = document.createRange(); range.selectNodeContents(el);
const domNaturalWidth = range.getBoundingClientRect().width;
const canvas = new OffscreenCanvas(1, 1).getContext('2d')!; canvas.font = font;
const result = { dpr: devicePixelRatio, font, width,
pretext: { lineCount: pretext.lineCount, height: pretext.height, lines: pretext.lines.map(l => l.text) },
dom, naturalWidth: { canvas: canvas.measureText(text).width, dom: domNaturalWidth } };
el.remove();
console.log(result);