diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index d107289..26f2398 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -16,7 +16,9 @@ import { Layout } from './core/Layout'; import type { CoreModule } from './core/module'; import { measureBaseline, solidTop, waveAmplitude, wavePath } from './decorations'; import { type DecodedFrame, decodeFrame } from './frame'; +import { type HandleEnds, Handles } from './Handles'; import { CaretMover, type LineGeometry } from './input/CaretMover'; +import type { HandleKind } from './input/GestureMachine'; import { InputHost } from './input/InputHost'; import { overlapOf, watchViewport } from './input/keyboardInset'; import { keyCommand } from './input/keys'; @@ -90,6 +92,8 @@ const SNAPSHOT_INFO_INTS = 7; const SVG = 'http://www.w3.org/2000/svg'; // How long an animated scrollToLine runs, as ScrollController.kt. const LINE_SCROLL_MS = 250; +// How long the insertion handle shows after a tap, as Android. +const INSERTION_HANDLE_MS = 4000; // The browser clipboard, which only a secure origin has. function browserClipboard(): Clipboard { @@ -177,7 +181,10 @@ export class EditorView { private frameIntsCap = 0; private frameText = 0; private frameTextCap = 0; - private readonly onScrollEvent = () => this.invalidate(); + private readonly onScrollEvent = () => { + if (!this.handleDrag) this.hideInsertion(); + this.invalidate(); + }; private offViewport: () => void = () => {}; // The keyboard's overlap with the editor, part of the bottom inset under avoidKeyboard. private keyboard = 0; @@ -248,6 +255,13 @@ export class EditorView { columnAt: (line, row, x) => this.columnAt(line, row, x), }; private readonly pointer: PointerHost; + private readonly handles: Handles; + // True while the last pointer down on the editor was touch or pen: only then do handles show. + private touchMode = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches; + private insertionShown = false; + private insertionTimer: ReturnType | undefined; + // A handle drag: the finger's offset below the handle's top, and the selection end that stays. + private handleDrag: { dy: number; fixed: number } | null = null; // 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; @@ -321,7 +335,20 @@ export class EditorView { dragEnded: () => { if (!this.destroyed) this.input.write(this.session.sync()); }, + pointerDown: (kind) => this.pointerDown(kind), + showInsertion: () => this.showInsertion(), + handleAt: (x, y) => this.handleAt(x, y), + moveHandle: (kind, x, y) => this.moveHandle(kind, x, y), + endHandleDrag: () => { + this.handleDrag = null; + this.handles.dragging = false; + this.invalidate(); + }, }); + this.handles = new Handles(this.textLayer); + // The browser keeps panning and pinch zoom, the editor takes taps and long presses. + this.scroller.style.touchAction = 'manipulation'; + this.textLayer.style.setProperty('-webkit-touch-callout', 'none'); this.scroller.addEventListener('mousedown', this.onMouseDownEvent); blinkStyle(); this.content.append(this.gutter, this.textLayer); @@ -409,6 +436,7 @@ export class EditorView { if (outside) this.session.external(); edit(); const changes = this.core.takeChanges(); + if (changes.length) this.hideInsertion(); for (const change of changes) { this.search.onChange(change); this.changed(change, changes.length); @@ -477,6 +505,71 @@ export class EditorView { return moved; } + private pointerDown(kind: string): void { + const touch = kind !== 'mouse'; + if (!touch) this.hideInsertion(); + if (touch === this.touchMode) return; + this.touchMode = touch; + this.invalidate(); + } + + private showInsertion(): void { + clearTimeout(this.insertionTimer); + this.insertionShown = true; + this.insertionTimer = setTimeout(() => this.hideInsertion(), INSERTION_HANDLE_MS); + this.invalidate(); + } + + private hideInsertion(): void { + clearTimeout(this.insertionTimer); + if (!this.insertionShown) return; + this.insertionShown = false; + this.invalidate(); + } + + // The handle under a touch down. Its drag keeps the finger's offset below the handle and the other end fixed. + private handleAt(x: number, y: number): HandleKind | null { + const kind = this.handles.hit(x, y); + if (!kind) return null; + const { anchor, head } = this.core.selection; + const fixed = kind === 'start' ? Math.max(anchor, head) : Math.min(anchor, head); + this.handleDrag = { dy: y - this.handles.top(kind), fixed }; + this.handles.dragging = true; + return kind; + } + + // A handle under the finger reads the text at the middle of the row it points at, so the finger never covers it. + private moveHandle(kind: HandleKind, x: number, y: number): void { + const drag = this.handleDrag; + if (!drag) return; + const offset = this.offsetAt(x, y - drag.dy - this.rowHeight / 2, true); + if (offset === null) return; + if (kind !== 'insertion') { + this.apply(() => this.core.setSelection(drag.fixed, offset)); + return; + } + this.apply(() => this.core.setSelection(offset, offset)); + this.showInsertion(); + } + + // The handles a touch shows, each at its end's row in the text layer, read before the draw writes. + private handleEnds(from: number, to: number, rootBox: DOMRect, layer: DOMRect): HandleEnds { + if (!this.touchMode || !(this.input.focused || this.pointer.holdsTouch)) return {}; + if (from === to && !this.insertionShown) return {}; + const view = this.visibleBox(); + const at = (offset: number): Rect | undefined => { + const r = this.caretRect(offset, rootBox); + if (!r) return undefined; + const x = r.x + rootBox.left; + const y = r.y + rootBox.top; + if (y + r.height <= view.top || y >= view.bottom) return undefined; + if (x < view.left - 1 || x > view.right + 1) return undefined; + return { x: x - layer.left, y: y - layer.top, width: r.width, height: r.height }; + }; + if (from === to) return { insertion: at(from) }; + return { start: at(from), end: at(to) }; + } + // The offset of the drawn text under a page point, or null when the point is not on a line. private textOffsetAt(clientX: number, clientY: number): number | null { const d = document as Document & { @@ -735,6 +828,18 @@ export class EditorView { const writeDecorations = this.planDecorations(); const writeMatches = this.planMatches(rootBox, from, to); const writeBrackets = this.planBrackets(); + const ends = this.handleEnds(from, to, rootBox, box); + const layout = this.layout; + const handleArea = { + width: Math.max( + layout.textAreaLeft + layout.contentWidth + layout.insetRight, + this.scroller.clientWidth, + ), + height: Math.max( + layout.insetTop + layout.contentHeight + layout.insetBottom, + this.scroller.clientHeight, + ), + }; if (caret && this.input.focused) { put(this.caretEl, 'display', 'block'); put(this.caretEl, 'left', `${caret.x + rootBox.left - box.left}px`); @@ -768,6 +873,7 @@ export class EditorView { writeDecorations(); writeMatches(); writeBrackets(); + this.handles.place(ends, this.css.cursor, handleArea); } // The page boxes of the document range on the lines that are drawn. @@ -1431,6 +1537,7 @@ export class EditorView { this.root.remove(); if (this.frameInts) this.m._free(this.frameInts); if (this.frameText) this.m._free(this.frameText); + clearTimeout(this.insertionTimer); this.search.close(); this.core.close(); // The engine finishes closing in the pump, which may have no other editor to run for. diff --git a/src/web/Handles.ts b/src/web/Handles.ts new file mode 100644 index 0000000..95990de --- /dev/null +++ b/src/web/Handles.ts @@ -0,0 +1,103 @@ +import type { Rect } from '../types'; +import type { HandleKind } from './input/GestureMachine'; + +export type HandleEnds = { insertion?: Rect; start?: Rect; end?: Rect }; + +const SIZE = 22; +// A finger-sized hit area under the row, centered on the shape. +const HIT = 44; +// Where each shape's tip sits along its width. +const TIP: Record = { insertion: 0.5, start: 1, end: 0 }; +const SHAPES: Record = { + insertion: { path: 'M11 0L18.78 7.78A11 11 0 1 1 3.22 7.78Z', height: 27 }, + start: { path: 'M11 0H22V11A11 11 0 1 1 11 0Z', height: SIZE }, + end: { path: 'M0 0H11A11 11 0 1 1 0 11Z', height: SIZE }, +}; +// Hit testing order when two areas overlap, as SelectionHandles.kt. +const ORDER: HandleKind[] = ['start', 'end', 'insertion']; +const SVG = 'http://www.w3.org/2000/svg'; + +// The Material teardrop handles, hanging from the row bottom of each selection end in the text layer. +export class Handles { + private readonly layer = document.createElement('div'); + private readonly els = new Map(); + private readonly written = new Map>(); + private fill = ''; + + constructor(parent: HTMLElement) { + this.layer.style.cssText = + 'position:absolute;left:0;top:0;overflow:hidden;pointer-events:none;z-index:3;'; + for (const kind of ORDER) { + const box = document.createElement('div'); + box.dataset.handle = kind; + box.style.cssText = `position:absolute;width:${HIT}px;height:${HIT}px;touch-action:none;pointer-events:auto;display:none;`; + const svg = document.createElementNS(SVG, 'svg'); + const shape = SHAPES[kind]; + svg.setAttribute('width', String(SIZE)); + svg.setAttribute('height', String(shape.height)); + svg.setAttribute('viewBox', `0 0 ${SIZE} ${shape.height}`); + svg.style.cssText = `position:absolute;left:${(HIT - SIZE) / 2}px;top:0;`; + const path = document.createElementNS(SVG, 'path'); + path.setAttribute('d', shape.path); + svg.append(path); + box.append(svg); + this.layer.append(box); + this.els.set(kind, { box, path }); + } + parent.append(this.layer); + } + + // Shows the handles of the given ends, each a rect of its end in the parent's coordinates, inside a layer of size. + place(ends: HandleEnds, color: string, size: { width: number; height: number }): void { + this.write(this.layer, 'width', `${size.width}px`); + this.write(this.layer, 'height', `${size.height}px`); + if (color !== this.fill) { + this.fill = color; + for (const { path } of this.els.values()) path.setAttribute('fill', color); + } + for (const [kind, { box }] of this.els) { + const r = ends[kind]; + if (!r) { + this.write(box, 'display', 'none'); + continue; + } + this.write(box, 'display', 'block'); + this.write(box, 'left', `${r.x - SIZE * TIP[kind] - (HIT - SIZE) / 2}px`); + this.write(box, 'top', `${r.y + r.height}px`); + } + } + + // The handle under a page point, if one shows there. + hit(clientX: number, clientY: number): HandleKind | null { + for (const kind of ORDER) { + const box = this.els.get(kind)?.box; + if (!box || box.style.display === 'none') continue; + const r = box.getBoundingClientRect(); + if (clientX >= r.left && clientX < r.right && clientY >= r.top && clientY < r.bottom) + return kind; + } + return null; + } + + // The page y of a handle's top, the bottom of the row it points at. + top(kind: HandleKind): number { + return this.els.get(kind)?.box.getBoundingClientRect().top ?? 0; + } + + // While a handle drags, points under it read the text beneath. + set dragging(on: boolean) { + for (const { box } of this.els.values()) box.style.pointerEvents = on ? 'none' : 'auto'; + } + + // Writes a style only when it changed, so an unchanged draw keeps the layout valid. + private write(el: HTMLElement, key: string, value: string): void { + let last = this.written.get(el); + if (!last) { + last = {}; + this.written.set(el, last); + } + if (last[key] === value) return; + last[key] = value; + el.style.setProperty(key, value); + } +} diff --git a/src/web/__tests__/gesture-machine.test.ts b/src/web/__tests__/gesture-machine.test.ts new file mode 100644 index 0000000..a0bc6f0 --- /dev/null +++ b/src/web/__tests__/gesture-machine.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, test } from '@jest/globals'; +import { type GestureHost, GestureMachine, type HandleKind } from '../input/GestureMachine'; + +class FakeHost implements GestureHost { + calls: string[] = []; + handle: HandleKind | null = null; + selected: [number, number] | null = null; + gap: [number, number] | null = null; + offsetAt = (x: number) => Math.trunc(x); + inGap = (_x: number, y: number) => this.gap !== null && y >= this.gap[0] && y <= this.gap[1]; + handleAt = () => this.handle; + insideSelection = (offset: number) => + this.selected !== null && offset >= this.selected[0] && offset <= this.selected[1]; + placeCaret = (offset: number) => void this.calls.push(`caret ${offset}`); + selectWord = (offset: number) => void this.calls.push(`word ${offset}`); + extendWords = (offset: number) => void this.calls.push(`extend ${offset}`); + moveHandle = (kind: HandleKind, x: number) => void this.calls.push(`handle ${kind} ${x}`); + endHandleDrag = () => void this.calls.push('handle end'); + showMenu = () => void this.calls.push('menu'); + postLongPress = (ms: number) => void this.calls.push(`timer ${ms}`); + cancelLongPress = () => void this.calls.push('cancel'); +} + +describe('GestureMachine', () => { + test('a tap or long press in a gap leaves the caret', () => { + const h = new FakeHost(); + h.gap = [20, 40]; + const m = new GestureMachine(h); + m.down(100, 30, 0); + m.up(100, 30, 50); + m.down(100, 30, 1000); + m.longPress(); + m.up(100, 30, 1600); + expect(h.calls).toEqual(['timer 400', 'cancel', 'timer 400', 'cancel']); + }); + + test('a tap places the caret', () => { + const h = new FakeHost(); + const m = new GestureMachine(h); + m.down(100, 10, 0); + m.move(103, 12, 20); + m.up(103, 12, 50); + expect(h.calls).toEqual(['timer 400', 'cancel', 'caret 103']); + }); + + test('a tap inside the selection shows the menu', () => { + const h = new FakeHost(); + h.selected = [90, 120]; + const m = new GestureMachine(h); + m.down(100, 10, 0); + m.up(100, 10, 50); + expect(h.calls).toEqual(['timer 400', 'cancel', 'menu']); + }); + + test('a second tap within 300 ms and 100 px selects the word', () => { + const h = new FakeHost(); + const m = new GestureMachine(h); + m.down(100, 10, 0); + m.up(100, 10, 50); + m.down(180, 12, 200); + m.up(180, 12, 240); + expect(h.calls.at(-1)).toBe('word 180'); + m.down(180, 12, 400); + m.up(180, 12, 450); + expect(h.calls.at(-1)).toBe('caret 180'); + m.down(180, 12, 1000); + m.up(180, 12, 1050); + expect(h.calls.at(-1)).toBe('caret 180'); + m.down(300, 12, 1200); + m.up(300, 12, 1250); + expect(h.calls.at(-1)).toBe('caret 300'); + }); + + test('a long press selects, then extends by words, and the release shows the menu', () => { + const h = new FakeHost(); + const m = new GestureMachine(h); + m.down(100, 10, 0); + m.longPress(); + expect(h.calls).toEqual(['timer 400', 'word 100', 'menu']); + m.move(104, 10, 500); + expect(h.calls.length).toBe(3); + m.move(130, 10, 520); + expect(h.calls.at(-1)).toBe('extend 130'); + m.up(130, 10, 600); + expect(h.calls.at(-1)).toBe('menu'); + }); + + test('a handle drag moves the handle and the release ends it', () => { + const h = new FakeHost(); + h.handle = 'end'; + const m = new GestureMachine(h); + m.down(100, 10, 0); + m.move(120, 10, 10); + m.up(120, 10, 20); + expect(h.calls).toEqual(['handle end 120', 'cancel', 'handle end']); + }); + + test('a move past slop before the long press cancels it and taps nothing', () => { + const h = new FakeHost(); + const m = new GestureMachine(h); + m.down(100, 100, 0); + m.move(100, 80, 20); + m.longPress(); + m.up(100, 60, 40); + expect(h.calls).toEqual(['timer 400', 'cancel', 'cancel']); + }); + + test('holdsTouch is true only in a handle drag, a long press and a word drag', () => { + const h = new FakeHost(); + const m = new GestureMachine(h); + const held: boolean[] = []; + m.down(100, 10, 0); + held.push(m.holdsTouch); + m.longPress(); + held.push(m.holdsTouch); + m.move(140, 10, 500); + held.push(m.holdsTouch); + m.up(140, 10, 600); + held.push(m.holdsTouch); + h.handle = 'start'; + m.down(100, 10, 1000); + held.push(m.holdsTouch); + m.cancel(); + held.push(m.holdsTouch); + h.handle = null; + m.down(100, 10, 2000); + m.move(100, 40, 2010); + held.push(m.holdsTouch); + expect(held).toEqual([false, true, true, false, true, false, false]); + }); +}); diff --git a/src/web/input/GestureMachine.ts b/src/web/input/GestureMachine.ts new file mode 100644 index 0000000..eb24591 --- /dev/null +++ b/src/web/input/GestureMachine.ts @@ -0,0 +1,135 @@ +export type HandleKind = 'insertion' | 'start' | 'end'; + +export type GestureConfig = { + touchSlop: number; + doubleTapSlop: number; + doubleTapTimeout: number; + longPressTimeout: number; +}; + +// Android's ViewConfiguration defaults. +export const TOUCH_GESTURES: GestureConfig = { + touchSlop: 8, + doubleTapSlop: 100, + doubleTapTimeout: 300, + longPressTimeout: 400, +}; + +export type GestureHost = { + offsetAt(x: number, y: number): number; + // True over empty space a decoration opened under a line, where touches leave the caret alone. + inGap(x: number, y: number): boolean; + handleAt(x: number, y: number): HandleKind | null; + insideSelection(offset: number): boolean; + placeCaret(offset: number): void; + selectWord(offset: number): void; + extendWords(offset: number): void; + moveHandle(kind: HandleKind, x: number, y: number): void; + endHandleDrag(): void; + showMenu(): void; + postLongPress(ms: number): void; + cancelLongPress(): void; +}; + +type State = 'idle' | 'pressed' | 'passed' | 'handleDrag' | 'longPressed' | 'wordDrag'; + +// The touch state machine, as GestureMachine.kt without scrolling: past slop the browser scrolls and cancels. +export class GestureMachine { + private state: State = 'idle'; + private handle: HandleKind | null = null; + private downX = 0; + private downY = 0; + private lastTapTime = -1; + private lastTapX = 0; + private lastTapY = 0; + + constructor( + private readonly host: GestureHost, + private readonly config: GestureConfig = TOUCH_GESTURES, + ) {} + + // True while the touch belongs to the editor, so the browser must not scroll with it. + get holdsTouch(): boolean { + return this.state === 'handleDrag' || this.state === 'longPressed' || this.state === 'wordDrag'; + } + + down(x: number, y: number, _time: number): void { + this.downX = x; + this.downY = y; + this.handle = this.host.handleAt(x, y); + if (this.handle) { + this.state = 'handleDrag'; + return; + } + this.state = 'pressed'; + this.host.postLongPress(this.config.longPressTimeout); + } + + move(x: number, y: number, _time: number): void { + const far = Math.hypot(x - this.downX, y - this.downY) > this.config.touchSlop; + switch (this.state) { + case 'pressed': + if (far) { + this.host.cancelLongPress(); + this.state = 'passed'; + } + break; + case 'handleDrag': + if (this.handle) this.host.moveHandle(this.handle, x, y); + break; + case 'longPressed': + if (far) { + this.state = 'wordDrag'; + this.host.extendWords(this.host.offsetAt(x, y)); + } + break; + case 'wordDrag': + this.host.extendWords(this.host.offsetAt(x, y)); + break; + } + } + + up(x: number, y: number, time: number): void { + this.host.cancelLongPress(); + const state = this.state; + this.state = 'idle'; + if (state === 'pressed') this.tap(x, y, time); + else if (state === 'handleDrag') this.host.endHandleDrag(); + else if (state === 'wordDrag') this.host.showMenu(); + } + + cancel(): void { + this.host.cancelLongPress(); + const state = this.state; + this.state = 'idle'; + if (state === 'handleDrag') this.host.endHandleDrag(); + } + + // The long press timer fired. + longPress(): void { + if (this.state !== 'pressed' || this.host.inGap(this.downX, this.downY)) return; + this.state = 'longPressed'; + this.host.selectWord(this.host.offsetAt(this.downX, this.downY)); + this.host.showMenu(); + } + + private tap(x: number, y: number, time: number): void { + if (this.host.inGap(x, y)) return; + const offset = this.host.offsetAt(x, y); + const c = this.config; + const double = + this.lastTapTime >= 0 && + time - this.lastTapTime <= c.doubleTapTimeout && + Math.hypot(x - this.lastTapX, y - this.lastTapY) <= c.doubleTapSlop; + if (double) { + this.lastTapTime = -1; + this.host.selectWord(offset); + return; + } + this.lastTapTime = time; + this.lastTapX = x; + this.lastTapY = y; + if (this.host.insideSelection(offset)) this.host.showMenu(); + else this.host.placeCaret(offset); + } +} diff --git a/src/web/input/PointerHost.ts b/src/web/input/PointerHost.ts index 3fd05c5..6b39167 100644 --- a/src/web/input/PointerHost.ts +++ b/src/web/input/PointerHost.ts @@ -1,8 +1,7 @@ import { requestPump } from '../pump'; +import { GestureMachine, type HandleKind } from './GestureMachine'; 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; @@ -17,36 +16,89 @@ export type PointerHooks = { inGap(y: number): boolean; focus(): void; stopLineScroll(): void; + // The kind of every pointer that goes down on the editor, which decides whether handles show. + pointerDown(kind: string): 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; + showInsertion(): void; + handleAt(x: number, y: number): HandleKind | null; + moveHandle(kind: HandleKind, x: number, y: number): void; + endHandleDrag(): void; + showMenu?(): 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. +// The mouse selects by drag, double and triple click and Shift+click. Touch and pen run the gesture machine. 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; + // The touch or pen pointer the machine follows. + private touchId = -1; + private wordAnchor: Span = { start: 0, end: 0 }; + // Set by a tap or a long press, so the release focuses inside a user gesture and the keyboard opens. + private focusOnUp = false; + private longPressTimer: ReturnType | undefined; + private readonly gestures: GestureMachine; constructor( private readonly scroller: HTMLElement, private readonly hooks: PointerHooks, ) { + this.gestures = new GestureMachine({ + offsetAt: (x, y) => hooks.offsetAt(x, y, true) ?? hooks.selection().head, + inGap: (_x, y) => hooks.inGap(y), + handleAt: (x, y) => hooks.handleAt(x, y), + insideSelection: (offset) => { + const { anchor, head } = hooks.selection(); + return ( + anchor !== head && offset >= Math.min(anchor, head) && offset <= Math.max(anchor, head) + ); + }, + placeCaret: (offset) => { + hooks.select(offset, offset); + hooks.showInsertion(); + this.focusOnUp = true; + }, + selectWord: (offset) => { + this.wordAnchor = hooks.wordAt(offset); + hooks.select(this.wordAnchor.start, this.wordAnchor.end); + this.focusOnUp = true; + }, + extendWords: (offset) => { + const [anchor, head] = extendUnits(this.wordAnchor, hooks.wordAt(offset)); + hooks.select(anchor, head); + }, + moveHandle: (kind, x, y) => hooks.moveHandle(kind, x, y), + endHandleDrag: () => hooks.endHandleDrag(), + showMenu: () => hooks.showMenu?.(), + postLongPress: (ms) => { + clearTimeout(this.longPressTimer); + this.longPressTimer = setTimeout(() => this.gestures.longPress(), ms); + }, + cancelLongPress: () => clearTimeout(this.longPressTimer), + }); 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); + scroller.addEventListener('lostpointercapture', this.lost); + scroller.addEventListener('contextmenu', this.contextMenu); + scroller.addEventListener('touchmove', this.touchMove, { passive: false }); } + // True while a mouse drag or a touch the editor holds runs, which write the textarea once at their end. get dragging(): boolean { - return this.drag !== null; + return this.drag !== null || this.gestures.holdsTouch; + } + + get holdsTouch(): boolean { + return this.gestures.holdsTouch; } // A mouse press on the text, from mousedown, whose detail is the click count. @@ -70,11 +122,7 @@ export class PointerHost { 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. - } + this.capture(this.pointerId); if (drag.unit === 'char') this.hooks.select(drag.anchor.start, offset); else this.hooks.select(drag.anchor.start, drag.anchor.end); this.hooks.focus(); @@ -94,27 +142,35 @@ export class PointerHost { destroy(): void { this.drag = null; + clearTimeout(this.longPressTimer); 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); + this.scroller.removeEventListener('lostpointercapture', this.lost); + this.scroller.removeEventListener('contextmenu', this.contextMenu); + this.scroller.removeEventListener('touchmove', this.touchMove); } 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 }; + this.hooks.pointerDown(e.pointerType); + if (e.pointerType === 'mouse' || !e.isPrimary) return; + this.touchId = e.pointerId; + this.focusOnUp = false; + this.capture(e.pointerId); + this.gestures.down(e.clientX, e.clientY, e.timeStamp); }; 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; + if (e.pointerType !== 'mouse') { + if (e.pointerId === this.touchId) this.gestures.move(e.clientX, e.clientY, e.timeStamp); + return; + } const d = this.drag; - if (!d || e.pointerType !== 'mouse') return; + if (!d) return; // The button came up outside the window, where the page saw no release. if ((e.buttons & 1) === 0) { this.end(); @@ -131,19 +187,52 @@ export class PointerHost { 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(); + if (e.pointerId !== this.touchId) return; + const held = this.gestures.holdsTouch; + this.gestures.up(e.clientX, e.clientY, e.timeStamp); + this.endTouch(held); }; private readonly cancel = (e: PointerEvent) => { - if (e.pointerType === 'mouse' && this.drag) this.end(); - else if (this.tap?.id === e.pointerId) this.tap = null; + if (e.pointerType === 'mouse') { + if (this.drag) this.end(); + return; + } + if (e.pointerId !== this.touchId) return; + const held = this.gestures.holdsTouch; + this.gestures.cancel(); + this.endTouch(held); }; + // Capture moves from the pressed element to the scroller, and that element's loss must not end the drag. + private readonly lost = (e: PointerEvent) => { + if (e.target === this.scroller) this.cancel(e); + }; + + // Chrome opens its own menu and selection about 500 ms into a long press. + private readonly contextMenu = (e: Event) => { + if (this.pointerType !== 'mouse') e.preventDefault(); + }; + + private readonly touchMove = (e: TouchEvent) => { + if (this.gestures.holdsTouch && e.cancelable) e.preventDefault(); + }; + + private endTouch(held: boolean): void { + this.touchId = -1; + if (held) this.hooks.dragEnded(); + if (this.focusOnUp) this.hooks.focus(); + this.focusOnUp = false; + } + + private capture(pointerId: number): void { + try { + this.scroller.setPointerCapture(pointerId); + } catch { + // The pointer is gone already: a mouse drag then ends on the next move without a button. + } + } + private extend(d: Drag): void { const head = this.hooks.offsetAt(d.x, d.y, true); if (head === null) return; diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 68e161a..e78c2e7 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -597,6 +597,214 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + // A touch pointer event at a page point: the down on the element there, the rest on the scroller, as capture does. + const touch = (page, id, type, p) => + page.evaluate( + ([id, type, p]) => { + const scroller = document.querySelector(`#${id} [data-scroller]`); + const target = type === 'pointerdown' ? document.elementFromPoint(p.x, p.y) : scroller; + target.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + cancelable: true, + pointerId: 9, + pointerType: 'touch', + isPrimary: true, + clientX: p.x, + clientY: p.y, + }), + ); + }, + [id, type, p], + ); + const settle = (page) => page.evaluate(() => window.codepad.frames(2)); + async function tap(page, id, p) { + await touch(page, id, 'pointerdown', p); + await touch(page, id, 'pointerup', p); + await settle(page); + } + async function longPress(page, id, p) { + await touch(page, id, 'pointerdown', p); + await page.waitForTimeout(550); + await touch(page, id, 'pointerup', p); + await settle(page); + } + // Each shown handle's tip, the point it hangs from, in page coordinates. + const tips = (page, id) => + page.evaluate((id) => { + const out = {}; + for (const el of document.querySelectorAll(`#${id} [data-handle]`)) { + if (getComputedStyle(el).display === 'none') continue; + const r = el.querySelector('svg').getBoundingClientRect(); + const kind = el.dataset.handle; + const x = kind === 'start' ? r.right : kind === 'end' ? r.left : (r.left + r.right) / 2; + out[kind] = { x, y: r.top }; + } + return out; + }, id); + // Drags a handle, held 10 px under its tip, until the text point it reads is at. + async function dragHandle(page, id, kind, at) { + const tip = (await tips(page, id))[kind]; + const row = await page.evaluate((id) => window.views[id].layout.rowHeight, id); + const from = { x: tip.x, y: tip.y + 10 }; + const to = { x: at.x, y: at.y + row / 2 + 10 }; + await touch(page, id, 'pointerdown', from); + for (let i = 1; i <= 4; i++) + await touch(page, id, 'pointermove', { + x: from.x + ((to.x - from.x) * i) / 4, + y: from.y + ((to.y - from.y) * i) / 4, + }); + await touch(page, id, 'pointerup', to); + await settle(page); + } + + test('a tap shows the insertion handle and it hides after 4 s', async () => { + const { page, errors } = await open(); + await editor(page, 'a', 'abcdef\nghijkl'); + const at = await pointAt(page, 'a', 1, 3); + await tap(page, 'a', at); + const shown = await tips(page, 'a'); + assert.deepEqual(Object.keys(shown), ['insertion']); + const caret = await page.evaluate(() => { + const v = window.views.a; + const box = document.getElementById('a').firstElementChild.getBoundingClientRect(); + const r = v.caretRect(v.core.selection.head); + return { x: r.x + box.left, y: r.y + r.height + box.top }; + }); + assert.ok(Math.abs(shown.insertion.x - caret.x) <= 1, JSON.stringify({ shown, caret })); + assert.ok(Math.abs(shown.insertion.y - caret.y) <= 1, JSON.stringify({ shown, caret })); + await page.waitForTimeout(4200); + await settle(page); + assert.deepEqual(await tips(page, 'a'), {}); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('a long press selects the word and shows both handles', async () => { + const { page, errors } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + assert.deepEqual(await selectionOf(page, 'a'), [6, 10]); + const shown = await tips(page, 'a'); + assert.deepEqual(Object.keys(shown).sort(), ['end', 'start']); + const word = await page.evaluate(() => { + const v = window.views.a; + const box = document.getElementById('a').firstElementChild.getBoundingClientRect(); + return { start: v.caretRect(6).x + box.left, end: v.caretRect(10).x + box.left }; + }); + assert.ok(Math.abs(shown.start.x - word.start) <= 1, JSON.stringify({ shown, word })); + assert.ok(Math.abs(shown.end.x - word.end) <= 1, JSON.stringify({ shown, word })); + assert.equal(await page.evaluate(() => window.views.a.focused), true); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('dragging the end handle past the start handle swaps the ends', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + await dragHandle(page, 'a', 'end', await pointAt(page, 'a', 0, 2)); + assert.deepEqual(await selectionOf(page, 'a'), [6, 2]); + const shown = await tips(page, 'a'); + const ends = await page.evaluate(() => { + const v = window.views.a; + const box = document.getElementById('a').firstElementChild.getBoundingClientRect(); + return { start: v.caretRect(2).x + box.left, end: v.caretRect(6).x + box.left }; + }); + assert.ok(Math.abs(shown.start.x - ends.start) <= 1, JSON.stringify({ shown, ends })); + assert.ok(Math.abs(shown.end.x - ends.end) <= 1, JSON.stringify({ shown, ends })); + await page.close(); + }); + + test('a mouse down hides the handles a touch showed', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma\nsecond'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + assert.equal(Object.keys(await tips(page, 'a')).length, 2); + await clickAt(page, 'a', 1, 2); + await settle(page); + assert.deepEqual(await tips(page, 'a'), {}); + await page.close(); + }); + + test('a desktop drag shows no handles', async () => { + const { page } = await open(); + await editor(page, 'a', 'abcdef\nghijkl'); + await dragThrough(page, await pointAt(page, 'a', 0, 1), [await pointAt(page, 'a', 1, 3)]); + await settle(page); + assert.deepEqual(await selectionOf(page, 'a'), [1, 10]); + assert.deepEqual(await tips(page, 'a'), {}); + await page.close(); + }); + + test('the handle of an end scrolled out of view hides', async () => { + const { page } = await open(); + await editor(page, 'a', lines(300)); + await longPress(page, 'a', await pointAt(page, 'a', 1, 1)); + await page.evaluate(async () => { + const v = window.views.a; + v.apply(() => v.core.setSelection(v.core.lineStart(1), v.core.lineStart(12) + 2)); + document.querySelector('#a [data-scroller]').scrollTop = v.layout.rowHeight * 4; + await window.codepad.frames(3); + }); + assert.deepEqual(Object.keys(await tips(page, 'a')), ['end']); + await page.close(); + }); + + test('the handles of a selection over an Arabic word stand at its logical ends', 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 tap(page, 'a', await pointAt(page, 'a', 0, 1)); + await page.evaluate(async () => { + const v = window.views.a; + v.apply(() => v.core.setSelection(4, 9)); + await window.codepad.frames(2); + }); + const shown = await tips(page, 'a'); + assert.ok(Math.abs(shown.start.x - word.left) <= 1, JSON.stringify({ shown, word })); + assert.ok(Math.abs(shown.end.x - word.right) <= 1, JSON.stringify({ shown, word })); + await page.close(); + }); + + test('dragging the end handle onto a letter of an Arabic word ends the selection at that letter', async () => { + const { page } = await open(); + await editor(page, 'a', 'abc مرحبا xyz'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 1)); + assert.deepEqual(await selectionOf(page, 'a'), [0, 3]); + const letter = 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, 6); + range.setEnd(node, 7); + const r = range.getBoundingClientRect(); + return { x: r.right - r.width / 4, y: r.top + r.height / 2 }; + }); + await dragHandle(page, 'a', 'end', letter); + assert.deepEqual(await selectionOf(page, 'a'), [0, 6]); + await page.close(); + }); + + test('under readOnly a long press selects and a handle drag leaves the text alone', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma', { readOnly: true }); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + assert.deepEqual(await selectionOf(page, 'a'), [6, 10]); + await dragHandle(page, 'a', 'end', await pointAt(page, 'a', 0, 13)); + assert.deepEqual(await selectionOf(page, 'a'), [6, 13]); + assert.equal(await textOf(page, 'a'), 'alpha beta gamma'); + 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');