From bbda286d0bbdb82e17e04b10323f129e964b2825 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 18 Nov 2026 18:07:42 +0100 Subject: [PATCH 1/5] perf(core): stop rebuilding row starts below the view on every key Every edit marked the row starts dirty from the edited line, and the content height then rebuilt them to the end of the document: 20 ms of handler time over 60 keys on a 10k-line file at 8x CPU throttle. The layout now keeps a running row total and extends the row starts only as far as a lookup needs. --- cpp/core/src/layout.cpp | 23 +++++++++++++++++++---- cpp/core/src/layout.hpp | 6 +++++- tests/vectors/layout.json | 1 + 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/cpp/core/src/layout.cpp b/cpp/core/src/layout.cpp index b121bc7..8adaea8 100644 --- a/cpp/core/src/layout.cpp +++ b/cpp/core/src/layout.cpp @@ -24,10 +24,10 @@ int32_t Layout::row_start(int32_t line) const { } int32_t Layout::line_at_row(int32_t row) const { - ensure(line_count_); - int32_t r = std::clamp(row, 0, std::max(starts_[line_count_] - 1, 0)); + int32_t r = std::clamp(row, 0, std::max(total_ - 1, 0)); + ensure_row(r); int32_t lo = 0; - int32_t hi = line_count_ - 1; + int32_t hi = std::min(clean_lines_ - 1, line_count_ - 1); while (lo < hi) { int32_t mid = static_cast((static_cast(lo) + static_cast(hi) + 1) >> 1); if (starts_[mid] <= r) { @@ -50,6 +50,7 @@ int32_t Layout::set_rows(int32_t line, int32_t count) { int32_t old = rows_[line]; if (old != count) { rows_[line] = count; + total_ += count - old; clean_lines_ = std::min(clean_lines_, line + 1); } return old; @@ -70,11 +71,15 @@ void Layout::set_gaps(const std::vector &items) { if (in_map(line) && gaps_[line] != count) dirty = std::min(dirty, line); } if (dirty == line_count_) return; - for (int32_t line : gap_lines_) gaps_[line] = 0; + for (int32_t line : gap_lines_) { + total_ -= gaps_[line]; + gaps_[line] = 0; + } gap_lines_.clear(); for (const auto &[line, count] : next) { if (in_map(line) && count > 0) { gaps_[line] = count; + total_ += count; gap_lines_.push_back(line); } } @@ -87,6 +92,8 @@ void Layout::replace_lines(int32_t first, int32_t old_count, int32_t new_count) new_count = std::max(new_count, 0); int32_t tail = line_count_ - first - old_count; int32_t next = line_count_ - old_count + new_count; + for (int32_t i = first; i < first + old_count; i++) total_ -= rows_[i] + gaps_[i]; + total_ += new_count; if (static_cast(next) > rows_.size()) { size_t size = std::max(static_cast(next), rows_.size() * 2); rows_.resize(size, 1); @@ -123,6 +130,8 @@ void Layout::replace_lines(int32_t first, int32_t old_count, int32_t new_count) void Layout::reset_rows() { std::fill(rows_.begin(), rows_.begin() + line_count_, 1); + total_ = line_count_; + for (int32_t line : gap_lines_) total_ += gaps_[line]; clean_lines_ = 0; } @@ -132,6 +141,7 @@ void Layout::reset(int32_t line_count) { rows_.assign(size, 1); gaps_.assign(size, 0); gap_lines_.clear(); + total_ = line_count_; clean_lines_ = 0; } @@ -263,4 +273,9 @@ void Layout::ensure(int32_t up_to) const { } } +void Layout::ensure_row(int32_t row) const { + ensure(0); + while (clean_lines_ <= line_count_ && starts_[clean_lines_ - 1] <= row) ensure(clean_lines_); +} + } // namespace codepad diff --git a/cpp/core/src/layout.hpp b/cpp/core/src/layout.hpp index b3854bb..d191da1 100644 --- a/cpp/core/src/layout.hpp +++ b/cpp/core/src/layout.hpp @@ -24,7 +24,7 @@ class Layout { int32_t widest_line = 0; int32_t line_count() const { return line_count_; } - int32_t total_rows() const { return row_start(line_count_); } + int32_t total_rows() const { return total_; } // Zero for a line outside the map. int32_t rows(int32_t line) const; int32_t gap_rows(int32_t line) const; @@ -79,6 +79,8 @@ class Layout { private: void ensure(int32_t up_to) const; + // Extends the prefix sums only until one passes row. + void ensure_row(int32_t row) const; cp_layout_config config_{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int32_t scroll_x_ = 0; @@ -87,6 +89,8 @@ class Layout { std::vector rows_ = std::vector(16, 1); std::vector gaps_ = std::vector(16, 0); std::vector gap_lines_; + // Rows plus gap rows of every line, kept by every write of rows_ or gaps_. + int32_t total_ = 1; // Prefix sums of rows plus gaps, valid below clean_lines_. mutable std::vector starts_ = std::vector(17, 0); mutable int32_t clean_lines_ = 0; diff --git a/tests/vectors/layout.json b/tests/vectors/layout.json index 21e6ffa..d34e43d 100644 --- a/tests/vectors/layout.json +++ b/tests/vectors/layout.json @@ -10,6 +10,7 @@ { "name": "a new decoration set replaces the gaps", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 2, "rows": 2 }], "expect": { "totalRows": 22 } }, { "op": "decorate", "items": [{ "kind": "gap", "line": 5, "rows": 1 }] }], "expect": { "totalRows": 21, "rowStart": { "3": 3, "6": 7 }, "isGapRow": { "3": false, "6": true } } }, { "name": "deleting a gap's line at the end and undoing keeps the rows in range", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 19, "rows": 2 }] }, { "op": "scrollTo", "x": 0, "y": 1000, "expect": { "scroll": [0, 170], "totalRows": 22 } }, { "op": "replace", "start": 29, "end": 39, "text": "", "expect": { "lineCount": 15, "gapRows": {}, "totalRows": 15, "scroll": [0, 100], "isGapRow": { "14": false, "15": false } } }, { "op": "undo" }], "expect": { "lineCount": 20, "gapRows": {}, "totalRows": 20, "scroll": [0, 100], "maxScroll": [0, 150] } }, { "name": "setText drops the gaps and keeps the scroll in range", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 0, "rows": 2 }] }, { "op": "scrollTo", "x": 0, "y": 1000, "expect": { "scroll": [0, 170], "totalRows": 22 } }, { "op": "setText", "text": "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny\ny" }], "expect": { "lineCount": 20, "gapRows": {}, "totalRows": 20, "scroll": [0, 150], "maxScroll": [0, 150] } }, + { "name": "resetting the rows keeps the gap rows in the total", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 3, "rows": 2 }] }, { "op": "measure", "pairs": [[5, 3]], "expect": { "totalRows": 24 } }, { "op": "resetRows" }], "expect": { "totalRows": 22, "maxScroll": [0, 170], "rowStart": { "4": 6, "6": 8 } } }, { "name": "an edit makes fresh one-row lines and moves gap lines with their text", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 10, "rows": 2 }] }, { "op": "measure", "pairs": [[5, 3], [12, 2]] }, { "op": "replace", "start": 10, "end": 10, "text": "y\ny\n" }], "expect": { "lineCount": 22, "gapRows": { "12": 2 }, "rowStart": { "5": 5, "8": 8, "12": 12, "13": 15, "14": 16, "15": 18 }, "totalRows": 25 } }, { "name": "rows map to the view through the insets", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [8, 4, 6, 2], "gutter": 10, "padding": 3, "wrap": false, "expect": { "content": [82, 200], "maxScroll": [0, 162], "lineTop": { "0": 8, "3": 38 }, "visible": [0, 3] } }, { "op": "scrollTo", "x": 0, "y": 25 }], "expect": { "lineTop": { "3": 13 }, "visible": [2, 6] } }, { "name": "layout reports only a text area width change", "text": "x\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }, { "op": "layout", "rowHeight": 10, "width": 100, "height": 80, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": false } }, { "op": "layout", "rowHeight": 10, "width": 100, "height": 80, "insets": [0, 0, 4, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }, { "op": "layout", "rowHeight": 10, "width": 120, "height": 80, "insets": [0, 0, 4, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }] }, From 7d98a2ec3729b78c1e686e9710a689ac4fae4cdd Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 18 Nov 2026 18:21:15 +0100 Subject: [PATCH 2/5] perf(web): write the scroll only on an axis the draw moved A scroll write makes the browser lay the page out at once. syncScroll wrote both axes whenever a reveal moved either one, 18 ms over 60 keys of a 300-line file at 8x CPU throttle. It now leaves an axis alone when it matches the position the draw last read or wrote. --- src/web/EditorView.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index c6b6b51..5b474cc 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -209,6 +209,8 @@ export class EditorView { private placedAt = ''; private baseline = 0; private drawnWindow = { first: 0, last: -1 }; + // The scroller's position as the draw last read or wrote it. + private readonly shownScroll = { x: 0, y: 0 }; private drawnGaps: GapRect[] = []; private reportedGaps = '[]'; private readonly selectionLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); @@ -1498,14 +1500,26 @@ export class EditorView { // The scroll the core draws at: the editor's own, or with scrolling off where the page shows the editor. private scrollPosition(): [number, number] { - if (this.o.scrollEnabled) return [this.scroller.scrollLeft, this.scroller.scrollTop]; + this.shownScroll.x = this.scroller.scrollLeft; + if (this.o.scrollEnabled) { + this.shownScroll.y = this.scroller.scrollTop; + return [this.shownScroll.x, this.shownScroll.y]; + } const top = this.root.getBoundingClientRect().top; - return [this.scroller.scrollLeft, Math.max(0, Math.round(-top))]; + return [this.shownScroll.x, Math.max(0, Math.round(-top))]; } + // A scroll write lays the page out at once, so an axis the draw did not move is left alone. private syncScroll(): void { - if (this.o.scrollEnabled) this.scroller.scrollTop = this.layout.scrollY; - this.scroller.scrollLeft = this.layout.scrollX; + const { scrollX: x, scrollY: y } = this.layout; + if (this.o.scrollEnabled && y !== this.shownScroll.y) { + this.scroller.scrollTop = y; + this.shownScroll.y = y; + } + if (x !== this.shownScroll.x) { + this.scroller.scrollLeft = x; + this.shownScroll.x = x; + } } private snapshotInfo(snapshot: number): { revision: number; basedOn: number } { From 34f64ba3b4b6be0ebc76a8a316f54235a25d0e96 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 18 Nov 2026 18:21:33 +0100 Subject: [PATCH 3/5] perf(web): repaint an edited line in place when its runs keep styles A typed letter rebuilt every span of its line, so the forced layout that measures the line's width redid the whole line: prepare took 102 ms over 60 keys of a 300-line file at 8x CPU throttle. A line whose runs keep their count and styles now only gets new text in the nodes that changed. --- src/web/EditorView.ts | 54 ++++++++++++++++++++++++++++++---------- tests/web/render.e2e.mjs | 31 +++++++++++++++++++++++ 2 files changed, 72 insertions(+), 13 deletions(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 5b474cc..eddaab1 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -23,7 +23,7 @@ import { WebInputSession } from './input/WebInputSession'; import { ensureInjected, ensureLanguage, onRegistered } from './loader'; import { probeKey, probing, registerView, requestPump } from './pump'; import { firstEndingAfter, SearchController } from './search'; -import { type CssTheme, cssTheme } from './theme'; +import { type CssTheme, type CssTokenStyle, cssTheme } from './theme'; export type ViewOptions = { theme: Theme; @@ -125,6 +125,10 @@ type Entry = { // One layer's marks on a line, in a box placed where the line is, kept while the line and its marks stay the same. type LineMarks = { line: number; desc: string; box: HTMLElement }; +// One run of a painted line: key is empty for bare text, else the span's resolved style. +type PaintRun = { key: string; text: string; style: CssTokenStyle | null }; +type PaintedRun = { key: string; node: Text | HTMLSpanElement }; + // An underline's part on one line, as columns of that line. type LineUnderline = { d: Extract; a: number; b: number }; @@ -211,6 +215,8 @@ export class EditorView { private drawnWindow = { first: 0, last: -1 }; // The scroller's position as the draw last read or wrote it. private readonly shownScroll = { x: 0, y: 0 }; + // Each line element's runs as last painted. + private readonly painted = new WeakMap(); private drawnGaps: GapRect[] = []; private reportedGaps = '[]'; private readonly selectionLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); @@ -1756,31 +1762,53 @@ export class EditorView { return div('position:absolute;direction:ltr;'); } - // Fills a line element with its text, one span per styled run. + // Fills a line element with its text, one span per styled run. Runs that keep their styles only get new text. private paint(el: HTMLDivElement, text: string, spans: Int32Array | null): void { el.style.whiteSpace = this.o.softWrap ? 'pre-wrap' : 'pre'; el.style.overflowWrap = this.o.softWrap ? 'anywhere' : 'normal'; - el.replaceChildren(); + const runs: PaintRun[] = []; let at = 0; if (spans) { for (let i = 0; i + 2 < spans.length; i += 3) { const start = Math.max(at, spans[i] as number); const end = Math.min(text.length, spans[i + 1] as number); if (end <= start) continue; - if (start > at) el.append(text.slice(at, start)); + if (start > at) runs.push({ key: '', text: text.slice(at, start), style: null }); const style = this.css.token(styleName(this.m, spans[i + 2] as number)); - const span = document.createElement('span'); - span.textContent = text.slice(start, end); - if (style) { - span.style.color = style.color; - if (style.bold) span.style.fontWeight = 'bold'; - if (style.italic) span.style.fontStyle = 'italic'; - } - el.append(span); + const key = style ? `s ${style.color} ${style.bold ? 1 : 0}${style.italic ? 1 : 0}` : 's'; + runs.push({ key, text: text.slice(start, end), style }); at = end; } } - if (at < text.length) el.append(text.slice(at)); + if (at < text.length) runs.push({ key: '', text: text.slice(at), style: null }); + const old = this.painted.get(el); + if (old && old.length === runs.length && old.every((r, i) => r.key === runs[i]?.key)) { + for (let i = 0; i < runs.length; i++) { + const node = (old[i] as PaintedRun).node; + const value = (runs[i] as PaintRun).text; + if (node.textContent !== value) node.textContent = value; + } + return; + } + const painted: PaintedRun[] = []; + el.replaceChildren(); + for (const run of runs) { + let node: Text | HTMLSpanElement; + if (run.key === '') { + node = document.createTextNode(run.text); + } else { + node = document.createElement('span'); + node.textContent = run.text; + if (run.style) { + node.style.color = run.style.color; + if (run.style.bold) node.style.fontWeight = 'bold'; + if (run.style.italic) node.style.fontStyle = 'italic'; + } + } + el.append(node); + painted.push({ key: run.key, node }); + } + this.painted.set(el, painted); } // Moves the cache along an edit and keeps the edited line's spans shifted until the parse catches up. diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index e24a56d..e5071ce 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -454,6 +454,37 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('a typed letter keeps the span elements of its line when the spans keep their styles', async () => { + const { page } = await open(); + await page.evaluate(() => window.codepad.ensureLanguage('python')); + await editor(page, 'a', 'def a():\n return b\n'); + await page.evaluate(async () => { + window.views.a.setLanguage('python'); + await window.codepad.until(() => window.views.a.core.snapshot !== 0); + }); + await clickAt(page, 'a', 1, 12); + await page.evaluate(() => { + window.keptSpans = [...document.querySelectorAll('#a [data-line="1"] span')]; + }); + await page.keyboard.type('x'); + const kept = await page.evaluate(async () => { + const v = window.views.a; + await window.codepad.until(() => v.core.snapshot !== 0 && v.core.revision > 0); + await window.codepad.frames(3); + const now = [...document.querySelectorAll('#a [data-line="1"] span')]; + return { + count: [window.keptSpans.length, now.length], + same: now.every((s, i) => s === window.keptSpans[i]), + last: now.at(-1)?.textContent, + }; + }); + assert.equal(await textOf(page, 'a'), 'def a():\n return bx\n'); + assert.deepEqual(kept.count, [2, 2]); + assert.equal(kept.last, 'bx'); + assert.equal(kept.same, true); + await page.close(); + }); + test('typing past the right edge keeps the caret in view without soft wrap', async () => { const { page } = await open(); await editor(page, 'a', 'x'); From ba16028b67dcdfa6bbb52214dcb23fb7801ee87b Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 18 Nov 2026 18:29:21 +0100 Subject: [PATCH 4/5] fix(web): split long lines into text nodes so Safari keeps up A minified file is one line, and with no language it was one text node of the whole line. WebKit spends time on a Range in proportion to its node, so every caret and selection rect cost about 0.35 s a key on a 2M-character line. Runs longer than 4096 units now split into text nodes, after a space or punctuation when one is near the limit, and the same line draws in about 100 ms, as in Chromium. --- src/web/EditorView.ts | 41 +++++++++++++--------- src/web/__tests__/chunks.test.ts | 28 +++++++++++++++ src/web/chunks.ts | 50 +++++++++++++++++++++++++++ tests/web/render.e2e.mjs | 58 ++++++++++++++++++++++++++++++++ 4 files changed, 161 insertions(+), 16 deletions(-) create mode 100644 src/web/__tests__/chunks.test.ts create mode 100644 src/web/chunks.ts diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index eddaab1..76d779a 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -10,6 +10,7 @@ import type { Suggestions, Theme, } from '../types'; +import { chunksOf } from './chunks'; import { EditorCore, type MoveUnit, type WebChange } from './core/EditorCore'; import { Layout } from './core/Layout'; import type { CoreModule } from './core/module'; @@ -127,7 +128,7 @@ type LineMarks = { line: number; desc: string; box: HTMLElement }; // One run of a painted line: key is empty for bare text, else the span's resolved style. type PaintRun = { key: string; text: string; style: CssTokenStyle | null }; -type PaintedRun = { key: string; node: Text | HTMLSpanElement }; +type PaintedRun = { key: string; parts: Text[] }; // An underline's part on one line, as columns of that line. type LineUnderline = { d: Extract; a: number; b: number }; @@ -1781,33 +1782,41 @@ export class EditorView { } } if (at < text.length) runs.push({ key: '', text: text.slice(at), style: null }); + const pieces = runs.map((run) => chunksOf(run.text)); const old = this.painted.get(el); - if (old && old.length === runs.length && old.every((r, i) => r.key === runs[i]?.key)) { + const same = + old !== undefined && + old.length === runs.length && + old.every((r, i) => r.key === runs[i]?.key && r.parts.length === pieces[i]?.length); + if (same) { for (let i = 0; i < runs.length; i++) { - const node = (old[i] as PaintedRun).node; - const value = (runs[i] as PaintRun).text; - if (node.textContent !== value) node.textContent = value; + const parts = (old[i] as PaintedRun).parts; + const values = pieces[i] as string[]; + for (let j = 0; j < parts.length; j++) { + const part = parts[j] as Text; + if (part.data !== values[j]) part.data = values[j] as string; + } } return; } const painted: PaintedRun[] = []; el.replaceChildren(); - for (const run of runs) { - let node: Text | HTMLSpanElement; + runs.forEach((run, i) => { + const parts = (pieces[i] as string[]).map((piece) => document.createTextNode(piece)); if (run.key === '') { - node = document.createTextNode(run.text); + el.append(...parts); } else { - node = document.createElement('span'); - node.textContent = run.text; + const span = document.createElement('span'); + span.append(...parts); if (run.style) { - node.style.color = run.style.color; - if (run.style.bold) node.style.fontWeight = 'bold'; - if (run.style.italic) node.style.fontStyle = 'italic'; + span.style.color = run.style.color; + if (run.style.bold) span.style.fontWeight = 'bold'; + if (run.style.italic) span.style.fontStyle = 'italic'; } + el.append(span); } - el.append(node); - painted.push({ key: run.key, node }); - } + painted.push({ key: run.key, parts }); + }); this.painted.set(el, painted); } diff --git a/src/web/__tests__/chunks.test.ts b/src/web/__tests__/chunks.test.ts new file mode 100644 index 0000000..88c300d --- /dev/null +++ b/src/web/__tests__/chunks.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, test } from '@jest/globals'; +import { chunkBreaks, TEXT_CHUNK } from '../chunks'; + +describe('chunkBreaks', () => { + test('a 10000-letter run with no break splits at 4096 and 8192', () => { + expect(TEXT_CHUNK).toBe(4096); + expect(chunkBreaks('a'.repeat(10000), TEXT_CHUNK)).toEqual([4096, 8192]); + }); + + test('a space within 256 units before the limit takes the split', () => { + const text = `${'a'.repeat(4000)} ${'a'.repeat(6000)}`; + expect(chunkBreaks(text, TEXT_CHUNK)).toEqual([4001, 8097]); + }); + + test('a break more than 256 units before the limit is not used', () => { + const text = `${'a'.repeat(3800)};${'a'.repeat(1000)}`; + expect(chunkBreaks(text, TEXT_CHUNK)).toEqual([4096]); + }); + + test('a surrogate pair at the limit stays whole', () => { + const text = `${'a'.repeat(4095)}\u{1F600}${'a'.repeat(100)}`; + expect(chunkBreaks(text, TEXT_CHUNK)).toEqual([4095]); + }); + + test('a run at or under the limit is not split', () => { + expect(chunkBreaks('a'.repeat(4096), TEXT_CHUNK)).toEqual([]); + }); +}); diff --git a/src/web/chunks.ts b/src/web/chunks.ts new file mode 100644 index 0000000..7c9a750 --- /dev/null +++ b/src/web/chunks.ts @@ -0,0 +1,50 @@ +// Longest text node a line holds: WebKit spends time on a Range in proportion to its node's length. +export const TEXT_CHUNK = 4096; +// How far before the limit a split looks for a space or punctuation, so a word is not cut in two. +const LOOK_BACK = 256; + +function isBreak(code: number): boolean { + return ( + code === 9 || + (code >= 32 && code <= 47) || + (code >= 58 && code <= 64) || + (code >= 91 && code <= 96) || + (code >= 123 && code <= 126) + ); +} + +// The offsets where a run splits, each after a break character when one is close enough to the limit. +export function chunkBreaks(text: string, limit: number): number[] { + const out: number[] = []; + let start = 0; + while (text.length - start > limit) { + const cut = start + limit; + let split = -1; + for (let i = cut; i > Math.max(start, cut - LOOK_BACK); i--) { + if (isBreak(text.charCodeAt(i - 1))) { + split = i; + break; + } + } + if (split < 0) { + const last = text.charCodeAt(cut - 1); + split = last >= 0xd800 && last <= 0xdbff ? cut - 1 : cut; + } + out.push(split); + start = split; + } + return out; +} + +// The run cut at its chunk breaks. +export function chunksOf(text: string): string[] { + if (text.length <= TEXT_CHUNK) return [text]; + const parts: string[] = []; + let at = 0; + for (const split of chunkBreaks(text, TEXT_CHUNK)) { + parts.push(text.slice(at, split)); + at = split; + } + parts.push(text.slice(at)); + return parts; +} diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index e5071ce..d9417e8 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -485,6 +485,64 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('no text node of a 2M-character line is longer than TEXT_CHUNK', async () => { + const { page } = await open(); + await editor(page, 'a', 'a=b(c,d);'.repeat(222223)); + const { longest, total } = await page.evaluate(() => { + const el = document.querySelector('#a [data-line="0"]'); + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + let longest = 0; + let total = 0; + for (let n = walker.nextNode(); n; n = walker.nextNode()) { + longest = Math.max(longest, n.data.length); + total += n.data.length; + } + return { longest, total }; + }); + assert.equal(total, 2000007); + assert.ok(longest <= 4096, `longest text node ${longest}`); + await page.close(); + }); + + test('a click and a selection across a chunk edge land on the right columns', async () => { + const { page } = await open(); + await editor(page, 'a', 'a=b(c,d);'.repeat(1200), { softWrap: true }); + const edge = await page.evaluate(async () => { + const v = window.views.a; + const edge = document.querySelector('#a [data-line="0"]').firstChild.data.length; + v.apply(() => v.core.setSelection(edge, edge)); + v.revealSelection(); + await window.codepad.frames(3); + return edge; + }); + assert.ok(edge < 10800, `one text node holds ${edge} units`); + await clickAt(page, 'a', 0, edge + 2); + assert.equal(await page.evaluate(() => window.views.a.core.selection.head), edge + 2); + await clickAt(page, 'a', 0, edge - 2); + assert.equal(await page.evaluate(() => window.views.a.core.selection.head), edge - 2); + const { painted, expected } = await page.evaluate(async (edge) => { + const v = window.views.a; + v.apply(() => v.core.setSelection(edge - 3, edge + 3)); + await window.codepad.frames(2); + const widths = [...document.querySelectorAll('#a [data-selection] > div')].map( + (d) => d.getBoundingClientRect().width, + ); + const range = document.createRange(); + const first = document.querySelector('#a [data-line="0"]').firstChild; + range.setStart(first, 0); + range.setEnd(first, 6); + return { + painted: widths.reduce((a, b) => a + b, 0), + expected: range.getBoundingClientRect().width, + }; + }, edge); + assert.ok( + Math.abs(painted - expected) < 2, + `selection ${painted} px, six columns ${expected} px`, + ); + await page.close(); + }); + test('typing past the right edge keeps the caret in view without soft wrap', async () => { const { page } = await open(); await editor(page, 'a', 'x'); From 99f63553cc15b7b4f2b01197b25a96b3ab0ae3bd Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 22:47:51 +0100 Subject: [PATCH 5/5] test(web): allow a pixel per piece when a selection crosses a chunk edge On Linux CI, WebKit painted a six-column selection across two text nodes as 53 px against 51 px for the same columns measured in one range, because each piece's rect rounds out to whole pixels. The check now allows one pixel for every painted piece. --- tests/web/render.e2e.mjs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index d9417e8..305c302 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -520,7 +520,7 @@ for (const engine of [chromium, webkit]) { assert.equal(await page.evaluate(() => window.views.a.core.selection.head), edge + 2); await clickAt(page, 'a', 0, edge - 2); assert.equal(await page.evaluate(() => window.views.a.core.selection.head), edge - 2); - const { painted, expected } = await page.evaluate(async (edge) => { + const { painted, pieces, expected } = await page.evaluate(async (edge) => { const v = window.views.a; v.apply(() => v.core.setSelection(edge - 3, edge + 3)); await window.codepad.frames(2); @@ -533,12 +533,14 @@ for (const engine of [chromium, webkit]) { range.setEnd(first, 6); return { painted: widths.reduce((a, b) => a + b, 0), + pieces: widths.length, expected: range.getBoundingClientRect().width, }; }, edge); + // WebKit on Linux rounds each piece's rect out to whole pixels, so every piece may add one. assert.ok( - Math.abs(painted - expected) < 2, - `selection ${painted} px, six columns ${expected} px`, + Math.abs(painted - expected) < 1 + pieces, + `selection ${painted} px in ${pieces} pieces, six columns ${expected} px`, ); await page.close(); });