Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions cpp/core/src/layout.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<int32_t>((static_cast<uint32_t>(lo) + static_cast<uint32_t>(hi) + 1) >> 1);
if (starts_[mid] <= r) {
Expand All @@ -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;
Expand All @@ -70,11 +71,15 @@ void Layout::set_gaps(const std::vector<cp_decoration> &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);
}
}
Expand All @@ -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<size_t>(next) > rows_.size()) {
size_t size = std::max(static_cast<size_t>(next), rows_.size() * 2);
rows_.resize(size, 1);
Expand Down Expand Up @@ -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;
}

Expand All @@ -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;
}

Expand Down Expand Up @@ -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
6 changes: 5 additions & 1 deletion cpp/core/src/layout.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -87,6 +89,8 @@ class Layout {
std::vector<int32_t> rows_ = std::vector<int32_t>(16, 1);
std::vector<int32_t> gaps_ = std::vector<int32_t>(16, 0);
std::vector<int32_t> 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<int32_t> starts_ = std::vector<int32_t>(17, 0);
mutable int32_t clean_lines_ = 0;
Expand Down
83 changes: 67 additions & 16 deletions src/web/EditorView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
Expand Down Expand Up @@ -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<Decoration, { kind: 'underline' }>; a: number; b: number };

Expand Down Expand Up @@ -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<HTMLDivElement, PaintedRun[]>();
private drawnGaps: GapRect[] = [];
private reportedGaps = '[]';
private readonly selectionLayer = div('position:absolute;left:0;top:0;pointer-events:none;');
Expand Down Expand Up @@ -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 } {
Expand Down Expand Up @@ -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.
Expand Down
28 changes: 28 additions & 0 deletions src/web/__tests__/chunks.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
});
50 changes: 50 additions & 0 deletions src/web/chunks.ts
Original file line number Diff line number Diff line change
@@ -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;
}
1 change: 1 addition & 0 deletions tests/vectors/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 } }] },
Expand Down
Loading
Loading