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
109 changes: 108 additions & 1 deletion src/web/EditorView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<typeof setTimeout> | 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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 & {
Expand Down Expand Up @@ -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`);
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
103 changes: 103 additions & 0 deletions src/web/Handles.ts
Original file line number Diff line number Diff line change
@@ -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<HandleKind, number> = { insertion: 0.5, start: 1, end: 0 };
const SHAPES: Record<HandleKind, { path: string; height: number }> = {
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<HandleKind, { box: HTMLDivElement; path: SVGPathElement }>();
private readonly written = new Map<HTMLElement, Record<string, string>>();
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);
}
}
Loading