From a904b8fe544c89f93a15ea1b05dd3bd8ffafb25f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 18 Nov 2026 18:50:22 +0100 Subject: [PATCH] feat(web): select with the mouse by drag, multi-click and Shift+click The web editor only placed the caret on a click, so a mouse could not select text, and a click left of a wrapped line's second row put the caret on the line's first column. A drag now selects, a double click selects a word and a triple click a line with its newline, each extending by that unit while the button is held, and Shift+click extends from the anchor. A drag held past the editor's edge scrolls it, or the page when scrolling is off, and a point beside a row maps to that row's nearest column. --- src/web/EditorView.ts | 121 +++++++++++----- src/web/__tests__/units.test.ts | 30 ++++ src/web/core/EditorCore.ts | 9 ++ src/web/core/module.ts | 1 + src/web/input/PointerHost.ts | 172 +++++++++++++++++++++++ src/web/input/units.ts | 23 +++ tests/web/render.e2e.mjs | 241 +++++++++++++++++++++++++++++++- 7 files changed, 563 insertions(+), 34 deletions(-) create mode 100644 src/web/__tests__/units.test.ts create mode 100644 src/web/input/PointerHost.ts create mode 100644 src/web/input/units.ts diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 76d779a..d107289 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -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'; @@ -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 = '') { @@ -296,7 +305,23 @@ 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); @@ -304,9 +329,8 @@ export class EditorView { 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); @@ -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)); @@ -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. @@ -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. @@ -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(); @@ -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; @@ -1362,7 +1420,7 @@ 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(); @@ -1370,7 +1428,6 @@ export class EditorView { 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); diff --git a/src/web/__tests__/units.test.ts b/src/web/__tests__/units.test.ts new file mode 100644 index 0000000..3b69e1a --- /dev/null +++ b/src/web/__tests__/units.test.ts @@ -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 }); + }); +}); diff --git a/src/web/core/EditorCore.ts b/src/web/core/EditorCore.ts index 4d6232a..06f781e 100644 --- a/src/web/core/EditorCore.ts +++ b/src/web/core/EditorCore.ts @@ -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 }; @@ -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); diff --git a/src/web/core/module.ts b/src/web/core/module.ts index 9d437dc..0e01197 100644 --- a/src/web/core/module.ts +++ b/src/web/core/module.ts @@ -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; diff --git a/src/web/input/PointerHost.ts b/src/web/input/PointerHost.ts new file mode 100644 index 0000000..3fd05c5 --- /dev/null +++ b/src/web/input/PointerHost.ts @@ -0,0 +1,172 @@ +import { requestPump } from '../pump'; +import { extendUnits, type Span } from './units'; + +// How far a touch may move, in pixels, and still count as a tap. +const TAP_SLOP = 8; +// The largest autoscroll step, in pixels a frame. +const AUTOSCROLL_MAX = 40; + +export type Box = { left: number; top: number; right: number; bottom: number }; + +export type PointerHooks = { + offsetAt(x: number, y: number, clamp: boolean): number | null; + selection(): { anchor: number; head: number }; + select(anchor: number, head: number): void; + wordAt(offset: number): Span; + lineUnit(offset: number): Span; + inGap(y: number): boolean; + focus(): void; + stopLineScroll(): void; + // The part of the editor the page shows, where a held drag starts to autoscroll. + visibleBox(): Box; + // Scrolls by the step, true when anything moved. + autoscroll(dx: number, dy: number): boolean; + dragEnded(): void; +}; + +type Drag = { unit: 'char' | 'word' | 'line'; anchor: Span; x: number; y: number }; + +// The mouse selects by drag, double and triple click and Shift+click. A touch or pen tap places the caret. +export class PointerHost { + private drag: Drag | null = null; + // The pointer of the last press, read by the mousedown that follows it. + private pointerType = ''; + private pointerId = -1; + private tap: { id: number; x: number; y: number } | null = null; + + constructor( + private readonly scroller: HTMLElement, + private readonly hooks: PointerHooks, + ) { + scroller.addEventListener('pointerdown', this.down); + scroller.addEventListener('pointermove', this.move); + scroller.addEventListener('pointerup', this.up); + scroller.addEventListener('pointercancel', this.cancel); + scroller.addEventListener('lostpointercapture', this.cancel); + } + + get dragging(): boolean { + return this.drag !== null; + } + + // A mouse press on the text, from mousedown, whose detail is the click count. + press(e: MouseEvent): void { + if ((this.pointerType && this.pointerType !== 'mouse') || e.button !== 0) return; + if (this.drag) this.end(); + if (this.hooks.inGap(e.clientY)) return; + const offset = this.hooks.offsetAt(e.clientX, e.clientY, false); + if (offset === null) { + this.hooks.focus(); + return; + } + const count = e.detail >= 3 ? 3 : e.detail === 2 ? 2 : 1; + let drag: Drag; + if (count === 1) { + const anchor = e.shiftKey ? this.hooks.selection().anchor : offset; + drag = { unit: 'char', anchor: { start: anchor, end: anchor }, x: e.clientX, y: e.clientY }; + } else { + const unit = count === 2 ? 'word' : 'line'; + const span = unit === 'word' ? this.hooks.wordAt(offset) : this.hooks.lineUnit(offset); + drag = { unit, anchor: span, x: e.clientX, y: e.clientY }; + } + this.drag = drag; + try { + this.scroller.setPointerCapture(this.pointerId); + } catch { + // The pointer is gone already, the next move without a button ends the drag. + } + if (drag.unit === 'char') this.hooks.select(drag.anchor.start, offset); + else this.hooks.select(drag.anchor.start, drag.anchor.end); + this.hooks.focus(); + } + + // One autoscroll step while a drag is held outside the visible box. True when it scrolled. + step(): boolean { + const d = this.drag; + if (!d) return false; + const box = this.hooks.visibleBox(); + const dx = edgeStep(d.x, box.left, box.right); + const dy = edgeStep(d.y, box.top, box.bottom); + if ((dx === 0 && dy === 0) || !this.hooks.autoscroll(dx, dy)) return false; + this.extend(d); + return true; + } + + destroy(): void { + this.drag = null; + this.scroller.removeEventListener('pointerdown', this.down); + this.scroller.removeEventListener('pointermove', this.move); + this.scroller.removeEventListener('pointerup', this.up); + this.scroller.removeEventListener('pointercancel', this.cancel); + this.scroller.removeEventListener('lostpointercapture', this.cancel); + } + + private readonly down = (e: PointerEvent) => { + this.hooks.stopLineScroll(); + this.pointerType = e.pointerType; + this.pointerId = e.pointerId; + if (e.pointerType !== 'mouse' && e.isPrimary) + this.tap = { id: e.pointerId, x: e.clientX, y: e.clientY }; + }; + + private readonly move = (e: PointerEvent) => { + const t = this.tap; + if (t && e.pointerId === t.id && Math.hypot(e.clientX - t.x, e.clientY - t.y) > TAP_SLOP) + this.tap = null; + const d = this.drag; + if (!d || e.pointerType !== 'mouse') return; + // The button came up outside the window, where the page saw no release. + if ((e.buttons & 1) === 0) { + this.end(); + return; + } + d.x = e.clientX; + d.y = e.clientY; + this.extend(d); + requestPump(); + }; + + private readonly up = (e: PointerEvent) => { + if (e.pointerType === 'mouse') { + if (this.drag) this.end(); + return; + } + const t = this.tap; + this.tap = null; + if (!t || e.pointerId !== t.id || this.hooks.inGap(e.clientY)) return; + const offset = this.hooks.offsetAt(e.clientX, e.clientY, false); + if (offset !== null) this.hooks.select(offset, offset); + this.hooks.focus(); + }; + + private readonly cancel = (e: PointerEvent) => { + if (e.pointerType === 'mouse' && this.drag) this.end(); + else if (this.tap?.id === e.pointerId) this.tap = null; + }; + + private extend(d: Drag): void { + const head = this.hooks.offsetAt(d.x, d.y, true); + if (head === null) return; + if (d.unit === 'char') { + this.hooks.select(d.anchor.start, head); + return; + } + const unit = d.unit === 'word' ? this.hooks.wordAt(head) : this.hooks.lineUnit(head); + const [anchor, to] = extendUnits(d.anchor, unit); + this.hooks.select(anchor, to); + } + + private end(): void { + this.drag = null; + this.hooks.dragEnded(); + } +} + +// The signed scroll step for a point past an edge of [low, high), zero inside. +function edgeStep(p: number, low: number, high: number): number { + const distance = p < low ? p - low : p >= high ? p - high + 1 : 0; + if (distance === 0) return 0; + return ( + Math.sign(distance) * Math.round(Math.min(AUTOSCROLL_MAX, Math.max(2, Math.abs(distance) / 2))) + ); +} diff --git a/src/web/input/units.ts b/src/web/input/units.ts new file mode 100644 index 0000000..867edf8 --- /dev/null +++ b/src/web/input/units.ts @@ -0,0 +1,23 @@ +export type Span = { start: number; end: number }; + +export type LineSource = { + readonly length: number; + readonly lineCount: number; + lineAt(offset: number): number; + lineStart(line: number): number; + lineEnd(line: number): number; +}; + +// A selection from the anchor unit to the far edge of the unit under the point, keeping the anchor unit whole. +export function extendUnits(anchor: Span, unit: Span): [anchor: number, head: number] { + if (unit.start >= anchor.start) return [anchor.start, Math.max(unit.end, anchor.end)]; + return [anchor.end, unit.start]; +} + +// The line under the offset with its newline, or up to the end of the text on the last line. +export function lineUnit(doc: LineSource, offset: number): Span { + const line = doc.lineAt(offset); + const start = doc.lineStart(line); + const end = line < doc.lineCount - 1 ? doc.lineStart(line + 1) : doc.lineEnd(line); + return { start, end }; +} diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index d9417e8..68e161a 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -102,8 +102,14 @@ for (const engine of [chromium, webkit]) { // Clicks the left edge of a column in a drawn line. async function clickAt(page, id, line, column) { + const { x, y } = await pointAt(page, id, line, column); + await page.mouse.click(x, y); + } + + // The page point just right of a column's left edge in a drawn line. + async function pointAt(page, id, line, column) { await page.waitForSelector(`#${id} [data-line="${line}"]`, { state: 'attached' }); - const { x, y } = await page.evaluate( + return page.evaluate( ([id, line, column]) => { const el = document.querySelector(`#${id} [data-line="${line}"]`); const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); @@ -123,7 +129,29 @@ for (const engine of [chromium, webkit]) { }, [id, line, column], ); - await page.mouse.click(x, y); + } + + const selectionOf = (page, id) => + page.evaluate((id) => { + const { anchor, head } = window.views[id].core.selection; + return [anchor, head]; + }, id); + + // Presses at one column, moves to each point in turn and releases, with the click count of the press. + async function dragThrough(page, from, points, clickCount = 1) { + await page.mouse.move(from.x, from.y); + for (let n = 1; n < clickCount; n++) { + await page.mouse.down({ clickCount: n }); + await page.mouse.up({ clickCount: n }); + } + await page.mouse.down({ clickCount }); + const seen = []; + for (const p of points) { + await page.mouse.move(p.x, p.y, { steps: 4 }); + seen.push(await selectionOf(page, 'a')); + } + await page.mouse.up({ clickCount }); + return seen; } const textOf = (page, id) => page.evaluate((id) => window.views[id].core.text(), id); @@ -360,6 +388,215 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('a drag selects from the press to the release', async () => { + const { page, errors } = await open(); + await editor(page, 'a', 'abcdef\nghijkl\nmnopqr'); + const from = await pointAt(page, 'a', 0, 2); + await dragThrough(page, from, [await pointAt(page, 'a', 2, 4)]); + assert.deepEqual(await selectionOf(page, 'a'), [2, 18]); + await page.keyboard.type('X'); + assert.equal(await textOf(page, 'a'), 'abXqr'); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('Shift+click extends from the anchor', async () => { + const { page } = await open(); + await editor(page, 'a', 'abcdef\nghijkl'); + await clickAt(page, 'a', 0, 1); + await page.keyboard.down('Shift'); + await clickAt(page, 'a', 1, 3); + assert.deepEqual(await selectionOf(page, 'a'), [1, 10]); + await clickAt(page, 'a', 0, 4); + await page.keyboard.up('Shift'); + assert.deepEqual(await selectionOf(page, 'a'), [1, 4]); + await page.close(); + }); + + test('a double click selects the word and a drag after it extends by words', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma\ndelta'); + const from = await pointAt(page, 'a', 0, 7); + const seen = await dragThrough( + page, + from, + [from, await pointAt(page, 'a', 0, 13), await pointAt(page, 'a', 0, 2)], + 2, + ); + assert.deepEqual(seen, [ + [6, 10], + [6, 16], + [10, 0], + ]); + await page.close(); + }); + + test('a triple click selects the line with its newline and a drag after it extends by lines', async () => { + const { page } = await open(); + await editor(page, 'a', 'one\ntwo\nthree\nfour'); + const from = await pointAt(page, 'a', 1, 1); + const seen = await dragThrough( + page, + from, + [from, await pointAt(page, 'a', 3, 2), await pointAt(page, 'a', 0, 1)], + 3, + ); + assert.deepEqual(seen, [ + [4, 8], + [4, 18], + [8, 0], + ]); + await page.close(); + }); + + test("a click left of a wrapped line's second row puts the caret at that row's start", async () => { + const { page } = await open(); + await editor(page, 'a', 'word '.repeat(60), { softWrap: true }); + const { x, y, start } = await page.evaluate(() => { + const el = document.querySelector('#a [data-line="0"]'); + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + const first = el.getBoundingClientRect().top; + let at = 0; + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + for (let i = 0; i < node.data.length; i++) { + const range = document.createRange(); + range.setStart(node, i); + range.setEnd(node, i + 1); + const r = range.getBoundingClientRect(); + if (r.top >= first + r.height / 2) { + const host = document.getElementById('a').getBoundingClientRect(); + return { x: host.left + 4, y: r.top + r.height / 2, start: at + i }; + } + } + at += node.data.length; + } + return null; + }); + assert.ok(start > 0); + await page.mouse.click(x, y); + assert.deepEqual(await selectionOf(page, 'a'), [start, start]); + await page.close(); + }); + + test('a drag held below the editor autoscrolls and the selection follows', async () => { + const { page, errors } = await open(); + await editor(page, 'a', lines(300)); + const from = await pointAt(page, 'a', 0, 1); + const box = await page.evaluate(() => document.getElementById('a').getBoundingClientRect()); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x, box.bottom + 30, { steps: 4 }); + await page.waitForFunction(() => window.views.a.visibleLines().first > 20); + const shown = await page.evaluate(() => window.views.a.visibleLines()); + const [anchor, head] = await selectionOf(page, 'a'); + await page.mouse.up(); + const line = await page.evaluate((head) => window.views.a.core.lineAt(head), head); + assert.equal(anchor, 1); + assert.ok(line >= shown.last - 2 && line <= shown.last + 2, JSON.stringify({ line, shown })); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('a drag released outside the window ends it and a later move selects nothing', async () => { + const { page } = await open(); + await editor(page, 'a', 'abcdef\nghijkl\nmnopqr'); + const from = await pointAt(page, 'a', 0, 1); + const to = await pointAt(page, 'a', 1, 2); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(to.x, to.y, { steps: 4 }); + await page.mouse.move(to.x, -20, { steps: 2 }); + await page.mouse.up(); + const ended = await selectionOf(page, 'a'); + const later = await pointAt(page, 'a', 2, 5); + await page.mouse.move(later.x, later.y, { steps: 4 }); + assert.deepEqual(await selectionOf(page, 'a'), ended); + await page.close(); + }); + + test('a drag over an Arabic word selects exactly its letters', async () => { + const { page } = await open(); + await editor(page, 'a', 'abc مرحبا xyz'); + const word = await page.evaluate(() => { + const el = document.querySelector('#a [data-line="0"]'); + const node = document.createTreeWalker(el, NodeFilter.SHOW_TEXT).nextNode(); + const range = document.createRange(); + range.setStart(node, 4); + range.setEnd(node, 9); + const r = range.getBoundingClientRect(); + return { left: r.left, right: r.right, y: r.top + r.height / 2 }; + }); + await dragThrough(page, { x: word.right - 1, y: word.y }, [{ x: word.left + 1, y: word.y }]); + const [anchor, head] = await selectionOf(page, 'a'); + assert.deepEqual([Math.min(anchor, head), Math.max(anchor, head)], [4, 9]); + await page.close(); + }); + + test('a press during an animated scrollToLine stops it', async () => { + const { page } = await open(); + await editor(page, 'a', lines(300)); + const at = await pointAt(page, 'a', 2, 1); + await page.mouse.move(at.x, at.y); + await page.evaluate(() => window.views.a.scrollToLine(250, true)); + await page.mouse.down(); + await page.mouse.up(); + const out = await page.evaluate(async () => { + await new Promise((r) => setTimeout(r, 400)); + const scroller = document.querySelector('#a [data-scroller]'); + return { end: scroller.scrollTop, target: window.views.a.layout.rowHeight * 250 }; + }); + assert.ok(out.end < out.target * 0.9, JSON.stringify(out)); + await page.close(); + }); + + test('with scrollEnabled false a drag below the page fold scrolls the page', async () => { + const { page, errors } = await open(); + await editor(page, 'c', lines(300), { scrollEnabled: false }); + const from = await pointAt(page, 'c', 0, 1); + const fold = await page.evaluate(() => window.innerHeight); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x, fold + 20, { steps: 4 }); + await page.waitForFunction(() => window.scrollY > 200); + const out = await page.evaluate(() => { + const v = window.views.c; + const fold = [...document.querySelectorAll('#c [data-line]')].find((el) => { + const r = el.getBoundingClientRect(); + return r.top <= window.innerHeight - 1 && r.bottom > window.innerHeight - 1; + }); + const { anchor, head } = v.core.selection; + return { anchor, line: v.core.lineAt(head), fold: Number(fold?.dataset.line) }; + }); + await page.mouse.up(); + assert.equal(out.anchor, 1); + assert.ok(Math.abs(out.line - out.fold) <= 2, JSON.stringify(out)); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('a touch tap still places the caret and focuses', async () => { + const { page } = await open(); + await editor(page, 'a', 'abcdef\nghijkl'); + const at = await pointAt(page, 'a', 1, 3); + const result = await page.evaluate(async ({ x, y }) => { + const target = document.elementFromPoint(x, y); + const init = { + bubbles: true, + cancelable: true, + pointerId: 7, + pointerType: 'touch', + isPrimary: true, + }; + target.dispatchEvent(new PointerEvent('pointerdown', { ...init, clientX: x, clientY: y })); + target.dispatchEvent(new PointerEvent('pointerup', { ...init, clientX: x, clientY: y })); + await window.codepad.frames(2); + const v = window.views.a; + return { head: v.core.selection.head, focused: v.focused }; + }, at); + assert.deepEqual(result, { head: 10, focused: true }); + await page.close(); + }); + test('typing after replaceRange, setText and undo lands at the core caret', async () => { const { page } = await open(); await editor(page, 'a', 'abc');