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
121 changes: 89 additions & 32 deletions src/web/EditorView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import { CaretMover, type LineGeometry } from './input/CaretMover';
import { InputHost } from './input/InputHost';
import { overlapOf, watchViewport } from './input/keyboardInset';
import { keyCommand } from './input/keys';
import { type Box, PointerHost } from './input/PointerHost';
import { lineUnit } from './input/units';
import { WebInputSession } from './input/WebInputSession';
import { ensureInjected, ensureLanguage, onRegistered } from './loader';
import { probeKey, probing, registerView, requestPump } from './pump';
Expand Down Expand Up @@ -245,12 +247,19 @@ export class EditorView {
caretX: (line, column) => this.pointIn(this.lineEl(line), column).x,
columnAt: (line, row, x) => this.columnAt(line, row, x),
};
private readonly onClickEvent = (e: MouseEvent) => this.click(e);
private readonly pointer: PointerHost;
// A press on the text or the line numbers keeps the focus, so a click in a focused editor never blurs it.
private readonly onMouseDownEvent = (e: MouseEvent) => {
const target = e.target as Node;
const inside = this.textLayer.contains(target) || this.gutter.contains(target);
if (e.button === 0 && inside) e.preventDefault();
const s = this.scroller;
const r = s.getBoundingClientRect();
// The scroller's own area past short content, never its scrollbars.
const beside =
target === s && e.clientX < r.left + s.clientWidth && e.clientY < r.top + s.clientHeight;
const inside = this.textLayer.contains(target) || this.gutter.contains(target) || beside;
if (e.button !== 0 || !inside) return;
e.preventDefault();
this.pointer.press(e);
};

constructor(host: HTMLElement, m: CoreModule, text = '') {
Expand Down Expand Up @@ -296,17 +305,32 @@ export class EditorView {
this.perform(() => (undo ? this.core.undo() : this.core.redo()));
},
});
this.scroller.addEventListener('click', this.onClickEvent);
this.pointer = new PointerHost(this.scroller, {
offsetAt: (x, y, clamp) => this.offsetAt(x, y, clamp),
selection: () => this.core.selection,
select: (anchor, head) => this.apply(() => this.core.setSelection(anchor, head)),
wordAt: (offset) => this.core.wordAt(offset),
lineUnit: (offset) => lineUnit(this.core, offset),
inGap: (y) => this.inGap(y),
focus: () => this.focus(),
stopLineScroll: () => {
this.lineScroll = null;
},
visibleBox: () => this.visibleBox(),
autoscroll: (dx, dy) => this.autoscroll(dx, dy),
dragEnded: () => {
if (!this.destroyed) this.input.write(this.session.sync());
},
});
this.scroller.addEventListener('mousedown', this.onMouseDownEvent);
blinkStyle();
this.content.append(this.gutter, this.textLayer);
this.scroller.append(this.content);
this.root.append(this.scroller);
host.append(this.root);
this.scroller.addEventListener('scroll', this.onScrollEvent, { passive: true });
// A user scroll ends an animated scrollToLine, as a touch does on native.
// A wheel ends an animated scrollToLine, as a press does in the pointer host.
this.scroller.addEventListener('wheel', this.stopLineScrollEvent, { passive: true });
this.scroller.addEventListener('touchstart', this.stopLineScrollEvent, { passive: true });
this.resize =
typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => this.invalidate());
this.resize?.observe(this.scroller);
Expand Down Expand Up @@ -393,7 +417,8 @@ export class EditorView {
const moved = s.anchor !== this.lastSelection.anchor || s.head !== this.lastSelection.head;
if (moved) this.lastSelection = s;
if (moved && !this.movingVertically) this.mover.reset();
if (outside) this.input.write(this.session.sync());
// A drag writes the textarea once, when it ends.
if (outside && !this.pointer.dragging) this.input.write(this.session.sync());
this.invalidate();
// Listeners run last, so one that throws leaves the editor and the textarea in step.
for (const change of changes) this.safely(() => this.o.onChange?.(change));
Expand All @@ -414,10 +439,42 @@ export class EditorView {
return !this.destroyed && this.input.focused;
}

// The document offset under a page point, or null outside the drawn text.
offsetAt(clientX: number, clientY: number): number | null {
// The document offset under a page point, or null outside the drawn text. With clamp, a point outside the visible box maps to its edge.
offsetAt(clientX: number, clientY: number, clamp = false): number | null {
if (this.destroyed) return null;
return this.textOffsetAt(clientX, clientY) ?? this.offsetBeside(clientX, clientY);
let x = clientX;
let y = clientY;
if (clamp) {
const box = this.visibleBox();
x = Math.min(Math.max(x, box.left), box.right - 1);
y = Math.min(Math.max(y, box.top), box.bottom - 1);
}
return this.textOffsetAt(x, y) ?? this.offsetBeside(x, y, clamp);
}

// The part of the editor the page shows, right of the line numbers and inside the scrollbars.
private visibleBox(): Box {
const r = this.scroller.getBoundingClientRect();
const left = this.o.lineNumbers ? this.gutter.getBoundingClientRect().right : r.left;
const page = document.documentElement;
return {
left: Math.max(left, 0),
top: Math.max(r.top, 0),
right: Math.min(r.left + this.scroller.clientWidth, page.clientWidth),
bottom: Math.min(r.top + this.scroller.clientHeight, page.clientHeight),
};
}

// One autoscroll step of a held drag: the editor's own scroll, or the page's with scrolling off. True when it moved.
private autoscroll(dx: number, dy: number): boolean {
const s = this.scroller;
const x = s.scrollLeft;
const y = this.scrollNow();
if (dx && !this.o.softWrap) s.scrollLeft = x + dx;
if (dy) this.scrollTo(y + dy);
const moved = s.scrollLeft !== x || this.scrollNow() !== y;
if (moved) this.invalidate();
return moved;
}

// The offset of the drawn text under a page point, or null when the point is not on a line.
Expand Down Expand Up @@ -446,22 +503,30 @@ export class EditorView {
return this.core.lineStart(line) + Math.min(column, this.core.line(line).length);
}

// A point beside the text, past a line's end or in the space below the last line, finds the drawn line by height.
private offsetBeside(clientX: number, clientY: number): number | null {
let below = true;
// A point beside a row, or below the last line, finds the drawn row by height. With clamp, past every drawn line takes the nearest one.
private offsetBeside(clientX: number, clientY: number, clamp: boolean): number | null {
let top: { line: number; r: DOMRect } | null = null;
let bottom: { line: number; r: DOMRect } | null = null;
for (const [line, entry] of this.cache) {
if (!this.attached.has(line)) continue;
const r = entry.el.getBoundingClientRect();
if (clientY >= r.bottom) continue;
below = false;
if (clientY < r.top) continue;
const range = document.createRange();
const [node, offset] = textPoint(entry.el, entry.text.length);
range.setStart(node, offset);
const end = range.getBoundingClientRect().right;
return this.core.lineStart(line) + (clientX >= end ? entry.text.length : 0);
if (clientY >= r.top && clientY < r.bottom) return this.besideRow(line, r, clientX, clientY);
if (!top || line < top.line) top = { line, r };
if (!bottom || line > bottom.line) bottom = { line, r };
}
return below ? this.core.length : null;
if (!top || !bottom || clientY >= bottom.r.bottom) {
if (!clamp || !bottom || bottom.line === this.core.lineCount - 1) return this.core.length;
return this.besideRow(bottom.line, bottom.r, clientX, bottom.r.bottom - 1);
}
if (clamp && clientY < top.r.top) return this.besideRow(top.line, top.r, clientX, top.r.top);
return null;
}

// The column nearest x on the row of a drawn line under y.
private besideRow(line: number, r: DOMRect, clientX: number, clientY: number): number {
const rows = Math.max(1, Math.round(r.height / this.rowHeight));
const row = Math.min(rows - 1, Math.max(0, Math.floor((clientY - r.top) / this.rowHeight)));
return this.core.lineStart(line) + this.columnAt(line, row, clientX - r.left);
}

// A keyboard edit or caret move shows the caret, a selection the page wrote back does not.
Expand Down Expand Up @@ -644,14 +709,6 @@ export class EditorView {
}
}

// A click places the caret and focuses the textarea inside the event, which iOS needs to show its keyboard.
private click(e: MouseEvent): void {
if (this.inGap(e.clientY)) return;
const offset = this.offsetAt(e.clientX, e.clientY);
if (offset !== null) this.apply(() => this.core.setSelection(offset, offset));
this.focus();
}

// The caret, composing underline and selection, every read before every write so the page lays out once.
private drawInput(): void {
const box = this.textLayer.getBoundingClientRect();
Expand Down Expand Up @@ -1303,6 +1360,7 @@ export class EditorView {
draw(): void {
if (this.destroyed) return;
if (this.lineScroll) this.stepLineScroll();
if (this.pointer.step()) requestPump();
if (this.core.snapshotCount !== this.seenSnapshots) {
this.seenSnapshots = this.core.snapshotCount;
this.dirty = true;
Expand Down Expand Up @@ -1362,15 +1420,14 @@ export class EditorView {
this.unregister();
this.offRegistered();
this.input.destroy();
this.scroller.removeEventListener('click', this.onClickEvent);
this.pointer.destroy();
this.scroller.removeEventListener('mousedown', this.onMouseDownEvent);
this.listenToPage(false);
this.offViewport();
this.resize?.disconnect();
document.fonts?.removeEventListener?.('loadingdone', this.remeasureEvent);
this.scroller.removeEventListener('scroll', this.onScrollEvent);
this.scroller.removeEventListener('wheel', this.stopLineScrollEvent);
this.scroller.removeEventListener('touchstart', this.stopLineScrollEvent);
this.root.remove();
if (this.frameInts) this.m._free(this.frameInts);
if (this.frameText) this.m._free(this.frameText);
Expand Down
30 changes: 30 additions & 0 deletions src/web/__tests__/units.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, test } from '@jest/globals';
import { extendUnits, type LineSource, lineUnit } from '../input/units';

// Lines of 'ab\ncd\r\nef': starts 0, 3, 7.
const doc: LineSource = {
length: 9,
lineCount: 3,
lineAt: (offset) => (offset < 3 ? 0 : offset < 7 ? 1 : 2),
lineStart: (line) => [0, 3, 7][line] as number,
lineEnd: (line) => [2, 5, 9][line] as number,
};

describe('extendUnits', () => {
test('a head after the anchor word ends at the end of its word', () => {
expect(extendUnits({ start: 4, end: 7 }, { start: 12, end: 15 })).toEqual([4, 15]);
expect(extendUnits({ start: 4, end: 7 }, { start: 4, end: 7 })).toEqual([4, 7]);
});

test('a head before the anchor word ends at its start and keeps the anchor word', () => {
expect(extendUnits({ start: 4, end: 7 }, { start: 0, end: 3 })).toEqual([7, 0]);
});
});

describe('lineUnit', () => {
test('lineUnit takes the newline except on the last line', () => {
expect(lineUnit(doc, 1)).toEqual({ start: 0, end: 3 });
expect(lineUnit(doc, 5)).toEqual({ start: 3, end: 7 });
expect(lineUnit(doc, 8)).toEqual({ start: 7, end: 9 });
});
});
9 changes: 9 additions & 0 deletions src/web/core/EditorCore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Decoration } from '../../types';
import type { Span } from '../input/units';
import { type CoreModule, type Heap, heapOf, withCString } from './module';

export type Selection = { anchor: number; head: number };
Expand Down Expand Up @@ -326,6 +327,14 @@ export class EditorCore {
this.m._cp_editor_select_word_at(this.handle, clampUnsigned(offset));
}

// The word around the offset, as a double click selects it.
wordAt(offset: number): Span {
const out = this.heap.output(8);
this.m._cp_doc_word_at(this.handle, clampUnsigned(offset), out, out + 4);
const span = this.heap.readInts(out, 2);
return { start: (span[0] as number) >>> 0, end: (span[1] as number) >>> 0 };
}

// The bracket at the caret and its partner. A snapshot at the document's revision skips strings and comments.
bracketMatch(snapshot: number): [number, number] | null {
const out = this.heap.output(8);
Expand Down
1 change: 1 addition & 0 deletions src/web/core/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export interface CoreModule {
_cp_doc_line_start(ed: Ptr, line: number): number;
_cp_doc_line_end(ed: Ptr, line: number): number;
_cp_doc_line_at(ed: Ptr, offset: number): number;
_cp_doc_word_at(ed: Ptr, offset: number, start: Ptr, end: Ptr): void;
_cp_doc_copy(ed: Ptr, start: number, end: number, out: Ptr, cap: number): number;
// Structs come back through a pointer passed first.
_cp_doc_position(out: Ptr, ed: Ptr, offset: number): void;
Expand Down
Loading