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/src/web/EditorView.ts b/src/web/EditorView.ts index c6b6b51..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'; @@ -23,7 +24,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 +126,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; parts: Text[] }; + // An underline's part on one line, as columns of that line. type LineUnderline = { d: Extract; a: number; b: number }; @@ -209,6 +214,10 @@ 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 }; + // 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;'); @@ -1498,14 +1507,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 } { @@ -1742,31 +1763,61 @@ 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 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) runs.push({ key: '', text: text.slice(at), style: null }); + const pieces = runs.map((run) => chunksOf(run.text)); + const old = this.painted.get(el); + 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 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(); + runs.forEach((run, i) => { + const parts = (pieces[i] as string[]).map((piece) => document.createTextNode(piece)); + if (run.key === '') { + el.append(...parts); + } else { 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'; + span.append(...parts); + if (run.style) { + 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); - at = end; } - } - if (at < text.length) el.append(text.slice(at)); + painted.push({ key: run.key, parts }); + }); + 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/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/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 } }] }, diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index e24a56d..305c302 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -454,6 +454,97 @@ 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('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, 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); + 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), + 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) < 1 + pieces, + `selection ${painted} px in ${pieces} pieces, 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');