Support rich inline with `pre-wrap` whitespace preserve
Rich inline allows mixed formatted content, but it explicitly says that pre-wrap is not supported.
Is there a reason we can't support whitespace preservation? I'm working on a Canva style editor and I have a need for rich inline with whitespace.
Just noting that there's a related pr open in https://github.com/chenglou/pretext/pull/193
Makes sense for an editor, and it's not a hard no. Preserved spaces and tabs across styled pieces hang and wrap in ways I'd need to check against real browsers before promising anything. Keeping this open while I decide whether to support it.
Thanks for clarifying. We have run into the same issue in a production editor: the paragraph is rendered with white-space: pre-wrap, but marks and font changes split it into multiple styled pieces. If the rich-inline path collapses consecutive spaces at those boundaries, the measurement can end up one line short and throw off pagination.
We currently carry a downstream patch that adds prepareRichInline(items, { whiteSpace: "pre-wrap" }). We will not reopen an implementation PR based on that patch. If useful, we can provide a minimal reproduction from the editor and native line-break observations from the browsers in whatever format works best for you.
This is up as #381: prepareRichInline(items, { whiteSpace: 'pre-wrap' }), one setting for the paragraph, the same call shape as your downstream patch. It's stacked on #379 (keep-all), so it lands after that one.
Every item except an atomic one (a chip) keeps its spaces, tabs and newlines now. Spaces at the end of a line hang past it even when a mark or font change splits the run, so a paragraph split into styled pieces shouldn't come out a line short anymore. Tab stops count from the line's start, not from the piece, and a newline ends its line, with a blank line getting a fragment of its own. Paint each line with white-space: pre.
I checked it against Chrome, Firefox and Safari on paragraphs split into styled spans, each next to the same text in one node. What's still off:
- a tab inside a span whose font isn't the paragraph's, like inline code in prose: Chrome and Firefox count the stops in the paragraph's font, which the items don't carry;
extraWidthon a span that breaks across lines is charged on every piece, and a padded span that starts or ends right at a newline or at trailing spaces can wrap differently, since each browser fits the padding there its own way.
@ChuanfengZhang if you still have that minimal repro from the editor, I'd take it. Anything the PR branch gets wrong goes straight into the test cases.
Thanks. Here are two groups of small cases based on our editor's inputs and item shapes. All seven regression cases match Chrome on #381 at cf94d49. The width sweep also found three threshold mismatches, included below.
- Preserved spaces across styled items: this is the original problem we reported, where collapsing spaces could make a paragraph one line short and affect pagination. With eight spaces in
AAAA BBBB, all four item splits give['AAAA ', 'BBBB']at 100px, keeping every space. - Trailing spaces after an image-sized atomic item: a 71px image item followed by three spaces, ten spaces or three bold spaces stays on one line at 73px, with the spaces preserved. Our downstream pre-wrap implementation used to put them on a second line, so the editor still has a post-processing step that merges a trailing spaces-only line back into the preceding line. It also handles ordinary text before the spaces and leaves explicit hard breaks intact.
Run this in a browser page with <html lang="en">, using a package built from the #381 branch. lineTexts() returns the materialized fragments' text for each line:
import { prepareWithSegments, measureNaturalWidth } from '@chenglou/pretext';
import {
prepareRichInline,
walkRichInlineLineRanges,
materializeRichInlineLineRange,
} from '@chenglou/pretext/rich-inline';
const font = '16px Arial';
const bold = '700 16px Arial';
const spaces = ' '.repeat(8);
function lineTexts(items, maxWidth) {
const prepared = prepareRichInline(items, { whiteSpace: 'pre-wrap' });
const lines = [];
walkRichInlineLineRanges(prepared, maxWidth, range => {
const line = materializeRichInlineLineRange(prepared, range);
lines.push(line.fragments.map(fragment => fragment.text).join(''));
});
return lines;
}
const spaceCases = [
[{ text: `AAAA${spaces}BBBB`, font: bold }],
[{ text: 'AAAA ', font }, { text: ' BBBB', font: bold }],
[{ text: 'AAAA', font }, { text: spaces, font: bold }, { text: 'BBBB', font }],
[{ text: 'AAAA ', font }, { text: ' BBBB', font: bold }],
];
for (const [index, items] of spaceCases.entries()) {
console.log('spaces', index, lineTexts(items, 100));
// Library and DOM: ['AAAA ', 'BBBB'].
}
const nbspWidth = measureNaturalWidth(prepareWithSegments('\u00A0', font));
const image = {
text: '\u00A0', font, break: 'never', extraWidth: 71 - nbspWidth,
};
const imageCases = [
[image, { text: ' ', font }],
[image, { text: ' ', font }],
[image, { text: ' ', font: bold }],
];
for (const [index, items] of imageCases.entries()) {
console.log('image', index, lineTexts(items, 73));
// One line: NBSP followed by all the trailing spaces.
}
// Remaining thresholds: one line in the DOM, two in the branch.
for (const [index, width] of [[0, 127.5], [1, 124], [3, 124]]) {
console.log('threshold', index, width, lineTexts(spaceCases[index], width));
}
The DOM reference uses the same fonts and content width, with white-space: pre-wrap; overflow-wrap: break-word; word-break: normal. Each text item is a span in its specified font, populated through textContent. The image stand-in is an empty inline-block, 71px wide and 31.04px high, followed immediately by the spaces span; the NBSP is only the library-side placeholder.
At the three thresholds, we measured different Canvas and DOM natural widths but haven't identified the cause, so we aren't counting those as resolved.
The original recordings used headed Chrome 154 / DPR 2. An independent run in Chrome 152 / DPR 2 gave the same results. We haven't independently checked these cases in Firefox or Safari.
Landed in #381: prepareRichInline(items, { whiteSpace: 'pre-wrap' }). Tabs inside a span whose font isn't the paragraph's, and padding on spans that wrap, are the known gaps (#382).
Thanks, this is really useful. Your seven cases pass here too, so the editor's step that merges a trailing spaces-only line back into the line before it shouldn't be needed with #381 anymore.
The three thresholds are kerning. Arial kerns A against a space, and Chrome's layout keeps that kerning across the space, but Chrome's Canvas shapes word by word, so measureText never reports it, not even for 'AAAA ' measured whole. In Chrome at DPR 2, bold AAAA + 8 spaces + BBBB is 127.41px in the DOM and 128px from Canvas, and your regular/bold splits are 123.59px against 124.47px, so 127.5 and 124 fall right in those gaps. The same text in one node misses the same way with plain prepare(), so it isn't specific to rich inline or pre-wrap. It's a known Canvas limit I can't fix on my side until Canvas can give a whole run's width. Until then, Chrome can put a line break a fraction of a pixel early in fonts that kern spaces, such as Arial and Times New Roman.
Thanks for checking these cases and explaining the kerning difference. We’ll validate #381 in the editor before removing the trailing-space workaround.
a correction to what I said above about the three thresholds (127.5 and 124px). I called it a Canvas limit I couldn't fix on my side. that was wrong, and it's fixed in #408.
Chrome's Canvas still doesn't report the kerning between A and the space when it measures them, but prepare() can ask for it another way, once per font and then per first and last character of a word, and it puts the answer on the space. all three of your cases are one line now, with Chrome's widths exactly: 127.41px for bold AAAA + 8 spaces + BBBB, and 123.59px for both regular/bold splits (Chrome 154, DPR 2). plain prepare() gets the same fix.
so it wasn't unfixable, it was a speed trade: a font that kerns the space (Arial, Times New Roman, Roboto) costs some extra Canvas calls the first times prepare() sees it, and a font that doesn't pays one question.
also, since nobody said it here: rich pre-wrap (#381) and this fix are on main only. nothing after 0.0.9 is on npm yet.
Thanks @chenglou
When do you plan to release it?
@mordechaim this has now been released with v1.0.0
Btw I expect v1.0.0 to be pretty excellent. Give it a try!