From 4289530d762941f296dd8abf4ebd58ea38e73d81 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 18 Nov 2026 20:15:31 +0100 Subject: [PATCH 01/14] fix(web): type at the caret during a drag and keep handle and menu up A key pressed while the mouse was still down typed at the press point, because the textarea skipped every write during a drag, and the insertion handle vanished as the phone keyboard opened. A selection taller than the view also lost its menu or put it under the editor. Only the drag's own selections now wait for its end, the page and keyboard no longer hide the handle, and the menu clamps into the view. --- src/web/EditMenu.ts | 2 + src/web/EditorView.ts | 51 +++++++++++++++++---- tests/web/render.e2e.mjs | 99 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 143 insertions(+), 9 deletions(-) diff --git a/src/web/EditMenu.ts b/src/web/EditMenu.ts index e244630..5363297 100644 --- a/src/web/EditMenu.ts +++ b/src/web/EditMenu.ts @@ -97,6 +97,8 @@ export class EditMenu { const { width, height } = this.size; let top = anchor.y - GAP - height; if (top < visible.y) top = anchor.y + anchor.height + GAP; + // With room neither above nor below, the menu sits as high as it can inside the visible area, as Android's toolbar. + if (top + height > visible.y + visible.height) top = visible.y; const centre = anchor.x + anchor.width / 2; const left = Math.max( visible.x, diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 7a505c9..c4949a0 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -182,10 +182,15 @@ export class EditorView { private frameIntsCap = 0; private frameText = 0; private frameTextCap = 0; + // The editor's own scroll hides the insertion handle, as Android's onScrolled. The page's scroll and the keyboard only redraw. private readonly onScrollEvent = () => { if (!this.handleDrag) this.hideInsertion(); this.invalidate(); }; + private readonly onPageEvent = () => this.invalidate(); + // A pointer drag writes the textarea once at its end, or before the next key when one comes first. + private pointerSelecting = false; + private textareaStale = false; private offViewport: () => void = () => {}; // The keyboard's overlap with the editor, part of the bottom inset under avoidKeyboard. private keyboard = 0; @@ -328,7 +333,7 @@ export class EditorView { 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)), + select: (anchor, head) => this.pointerSelect(anchor, head), wordAt: (offset) => this.core.wordAt(offset), lineUnit: (offset) => lineUnit(this.core, offset), inGap: (y) => this.inGap(y), @@ -339,7 +344,7 @@ export class EditorView { visibleBox: () => this.visibleBox(), autoscroll: (dx, dy) => this.autoscroll(dx, dy), dragEnded: () => { - if (!this.destroyed) this.input.write(this.session.sync()); + if (!this.destroyed) this.syncTextarea(); }, pointerDown: (kind) => this.pointerDown(kind), showInsertion: () => this.showInsertion(), @@ -410,7 +415,7 @@ export class EditorView { if (before.scrollEnabled !== this.o.scrollEnabled) this.listenToPage(!this.o.scrollEnabled); if (before.avoidKeyboard !== this.o.avoidKeyboard) { this.offViewport(); - this.offViewport = this.o.avoidKeyboard ? watchViewport(this.onScrollEvent) : () => {}; + this.offViewport = this.o.avoidKeyboard ? watchViewport(this.onPageEvent) : () => {}; } this.input.setSuggestions(this.o.suggestions); this.input.setReadOnly(this.o.readOnly); @@ -472,8 +477,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(); - // A drag writes the textarea once, when it ends. - if (outside && !this.pointer.dragging) this.input.write(this.session.sync()); + if (outside && this.pointerSelecting) this.textareaStale = true; + else if (outside) this.syncTextarea(); 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)); @@ -532,6 +537,21 @@ export class EditorView { return moved; } + // A selection from a mouse drag or a held touch, which skips the textarea write until the gesture ends. + private pointerSelect(anchor: number, head: number): void { + this.pointerSelecting = this.pointer.dragging; + try { + this.apply(() => this.core.setSelection(anchor, head)); + } finally { + this.pointerSelecting = false; + } + } + + private syncTextarea(): void { + this.textareaStale = false; + this.input.write(this.session.sync()); + } + private pointerDown(kind: string): void { const touch = kind !== 'mouse'; if (!touch) this.hideInsertion(); @@ -573,10 +593,10 @@ export class EditorView { 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)); + this.pointerSelect(drag.fixed, offset); return; } - this.apply(() => this.core.setSelection(offset, offset)); + this.pointerSelect(offset, offset); this.showInsertion(); } @@ -615,6 +635,17 @@ export class EditorView { out = { x: left, y: top, width: right - left, height: bottom - top }; } if (out && handles) out.height += HANDLE_HEIGHT; + // A selection that runs past both edges of the view keeps its menu, clamped to the view as Android does. + if (!out && from < to) { + const { first, last } = this.visibleLines(); + if (from <= this.core.lineEnd(last) && to >= this.core.lineStart(first)) + out = { + x: view.left, + y: view.top, + width: view.right - view.left, + height: view.bottom - view.top, + }; + } return out; } @@ -739,6 +770,8 @@ export class EditorView { // A hardware key the editor runs itself. True when the browser must not act on it. private keyDown(e: KeyboardEvent): boolean { if (this.destroyed) return false; + // A key during a drag acts on the selection the drag made, so the textarea takes it first. + if (this.textareaStale) this.syncTextarea(); const command = keyCommand(e, MAC); if (!command) return false; switch (command.kind) { @@ -1694,11 +1727,11 @@ export class EditorView { if (on === this.listening) return; this.listening = on; const method = on ? 'addEventListener' : 'removeEventListener'; - window[method]('scroll', this.onScrollEvent, { + window[method]('scroll', this.onPageEvent, { capture: true, passive: true, } as AddEventListenerOptions); - window[method]('resize', this.onScrollEvent); + window[method]('resize', this.onPageEvent); } private applyOptions(metrics: boolean): void { diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 9cc89a7..62347d8 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -1099,6 +1099,105 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('a key pressed while a mouse drag is held types at the caret it moved to', async () => { + const { page } = await open(); + await editor(page, 'a', 'abcdef\nghijkl'); + const at = await pointAt(page, 'a', 0, 1); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('ArrowDown'); + await page.keyboard.type('X'); + await page.mouse.up(); + assert.equal(await textOf(page, 'a'), 'abcdef\nghiXjkl'); + await page.close(); + }); + + test('a letter typed during a mouse drag replaces the dragged selection', async () => { + const { page } = await open(); + await editor(page, 'a', 'abcdef\nghijkl'); + const from = await pointAt(page, 'a', 0, 1); + const to = await pointAt(page, 'a', 1, 3); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(to.x, to.y, { steps: 4 }); + await page.keyboard.type('X'); + await page.mouse.up(); + assert.equal(await textOf(page, 'a'), 'aXjkl'); + await page.close(); + }); + + test('under avoidKeyboard a viewport resize after a tap keeps the insertion handle', async () => { + const { page } = await open(); + await editor(page, 'a', 'abcdef\nghijkl', { avoidKeyboard: true }); + await tap(page, 'a', await pointAt(page, 'a', 1, 3)); + assert.deepEqual(Object.keys(await tips(page, 'a')), ['insertion']); + await page.evaluate(() => window.visualViewport.dispatchEvent(new Event('resize'))); + await settle(page); + assert.deepEqual(Object.keys(await tips(page, 'a')), ['insertion']); + await page.close(); + }); + + test('a page scroll after a tap keeps the insertion handle', async () => { + const { page } = await open(); + await editor(page, 'c', lines(300), { scrollEnabled: false }); + await tap(page, 'c', await pointAt(page, 'c', 2, 3)); + assert.deepEqual(Object.keys(await tips(page, 'c')), ['insertion']); + await page.evaluate(async () => { + window.scrollBy(0, 40); + await window.codepad.frames(3); + }); + assert.deepEqual(Object.keys(await tips(page, 'c')), ['insertion']); + await page.close(); + }); + + test('Select all in the middle of a long file keeps the menu on screen', async () => { + const { page } = await open(); + await editor(page, 'a', lines(400)); + await page.evaluate(async () => { + window.views.a.scrollToLine(200); + await window.codepad.frames(3); + }); + await longPress(page, 'a', await pointAt(page, 'a', 203, 1)); + await pressMenu(page, 'Select all'); + const menu = await menuOf(page); + const box = await page.evaluate(() => + document.getElementById('a').getBoundingClientRect().toJSON(), + ); + assert.ok(menu !== null, 'the menu shows'); + assert.ok( + menu.box.top >= box.top && menu.box.bottom <= box.bottom, + JSON.stringify({ menu, box }), + ); + await page.close(); + }); + + test('a selection from the top row to the bottom row keeps the menu inside the viewport', async () => { + const { page } = await open(); + await editor(page, 'a', lines(100)); + const box = await page.evaluate(() => + document.getElementById('a').getBoundingClientRect().toJSON(), + ); + const shown = await page.evaluate(() => window.views.a.visibleLines()); + await longPress(page, 'a', await pointAt(page, 'a', shown.first, 1)); + await page.evaluate( + async ([first, last]) => { + const v = window.views.a; + v.apply(() => v.core.setSelection(v.core.lineStart(first), v.core.lineEnd(last))); + await window.codepad.frames(3); + }, + [shown.first, shown.last - 1], + ); + const menu = await menuOf(page); + assert.ok(menu !== null, 'the menu shows'); + assert.ok( + menu.box.top >= box.top && menu.box.bottom <= box.bottom, + JSON.stringify({ menu, box }), + ); + 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'); From 001bc060b3aa074989f2f012e66159323ed10887 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sun, 22 Nov 2026 01:50:14 +0100 Subject: [PATCH 02/14] perf(web): paint underlines with the text instead of an overlay With 100 underlines in view, every key rebuilt the edited line's underline boxes and read a Range rect for each piece, 3.3 ms a key at 8x CPU throttling. Each underline is now a span around its text whose background draws the bar or the wave, so a key repaints only its own line, about 0.3 ms over plain typing. Selection and match boxes are read per text node, so the span's padding never grows them, and the span takes no taps. --- src/web/EditorView.ts | 262 ++++++++++++++------------ src/web/__tests__/decorations.test.ts | 79 +++++++- src/web/decorations.ts | 101 +++++++++- tests/web/harness/index.html | 29 ++- tests/web/render.e2e.mjs | 224 +++++++++++++++++++--- 5 files changed, 545 insertions(+), 150 deletions(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index c4949a0..335792a 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -14,7 +14,13 @@ import { chunksOf } from './chunks'; import { EditorCore, type MoveUnit, type WebChange } from './core/EditorCore'; import { Layout } from './core/Layout'; import type { CoreModule } from './core/module'; -import { measureBaseline, solidTop, waveAmplitude, wavePath } from './decorations'; +import { + measureBaseline, + measureTextBox, + type UnderlineLink, + underlineLayer, + underlinePieces, +} from './decorations'; import { EditMenu } from './EditMenu'; import { type DecodedFrame, decodeFrame } from './frame'; import { HANDLE_HEIGHT, type HandleEnds, Handles } from './Handles'; @@ -90,7 +96,6 @@ export const DEFAULT_OPTIONS: ViewOptions = { const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace'; 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. @@ -128,6 +133,8 @@ type Entry = { text: string; // Edited since its last draw: the element is reused, but the frame reads the line again. stale?: boolean; + // The underlines painted into it, as described by underlinesByLine. + underlines: string; }; // One layer's marks on a line, in a box placed where the line is, kept while the line and its marks stay the same. @@ -135,11 +142,20 @@ type LineMarks = { line: number; desc: string; box: HTMLElement }; // One run of a painted line: key is empty for bare text, else the span's resolved style. type PaintRun = { key: string; text: string; style: CssTokenStyle | null }; -type PaintedRun = { key: string; parts: Text[] }; +// A painted run with the underline spans it sits in, keyed by their ids and looks. +type PaintPiece = PaintRun & { chain?: UnderlineLink[]; mark?: string }; +type PaintedRun = { key: string; mark: string; parts: Text[] }; // An underline's part on one line, as columns of that line. type LineUnderline = { d: Extract; a: number; b: number }; +// The underlines on each drawn line, with a description that changes when what a line paints does. +type LineUnderlines = { + key: string; + lines: Map; + descs: Map; +}; + // The edited line's previous spans moved along an edit that stayed inside it, kept until a parse lands. type Kept = { line: number; revision: number; spans: Int32Array | null; tail: Int32Array | null }; @@ -202,9 +218,8 @@ export class EditorView { }); readonly session: WebInputSession; private readonly input: InputHost; - // The app's line backgrounds over the active line, and its underlines under the text. + // The app's line backgrounds over the active line. Underlines are painted with the text. private readonly lineBackgroundLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); - private readonly underlineLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); // Search matches under the selection, the selected match in the active color. private readonly matchLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); private readonly bracketLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); @@ -218,16 +233,14 @@ export class EditorView { }; private readonly matchMarks = new Map(); private readonly search: SearchController; - private readonly underlineMarks = new Map(); - private underlines: { key: string; lines: Map } = { - key: '', - lines: new Map(), - }; + private underlines: LineUnderlines = { key: '', lines: new Map(), descs: new Map() }; private readonly backgroundEls: HTMLElement[] = []; // Bumped when the theme, the font or the text's place changes, so every overlay is planned again. private overlayVersion = 0; private placedAt = ''; private baseline = 0; + // A text span's box in its row, where underline backgrounds are placed from. + private textBox = { top: 0, bottom: 0 }; private drawnWindow = { first: 0, last: -1 }; // The scroller's position as the draw last read or wrote it. private readonly shownScroll = { x: 0, y: 0 }; @@ -304,7 +317,6 @@ export class EditorView { this.matchLayer, this.bracketLayer, this.selectionLayer, - this.underlineLayer, this.placeholderEl, this.composingLayer, this.caretEl, @@ -1019,16 +1031,25 @@ export class EditorView { return out; } - // The page boxes of columns a to b of a drawn line. + // The page boxes of columns a to b of a drawn line, read per text node so an underline span's padded box is left out. private columnRects(entry: Entry, a: number, b: number): DOMRect[] { const range = document.createRange(); - const [sn, so] = textPoint(entry.el, a); - const [en, eo] = textPoint(entry.el, b); - range.setStart(sn, so); - range.setEnd(en, eo); - const rects = [...range.getClientRects()].filter((r) => r.width > 0); + const rects: DOMRect[] = []; + for (const { node, at } of textRuns(entry.el)) { + const end = at + node.data.length; + if (end <= a || at >= b) continue; + range.setStart(node, Math.max(a, at) - at); + range.setEnd(node, Math.min(b, end) - at); + for (const r of range.getClientRects()) if (r.width > 0) rects.push(r); + } // An empty part of a line inside the selection still shows a little. - if (rects.length === 0) rects.push(range.getBoundingClientRect()); + if (rects.length === 0) { + const [sn, so] = textPoint(entry.el, a); + const [en, eo] = textPoint(entry.el, b); + range.setStart(sn, so); + range.setEnd(en, eo); + rects.push(range.getBoundingClientRect()); + } return rects; } @@ -1305,7 +1326,7 @@ export class EditorView { return this.drawnGaps.some((g) => y >= g.rect.y && y < g.rect.y + g.rect.height); } - // Reads the underlines' boxes on the lines where they changed and returns the writes, so the draw keeps one read phase. + // Plans the line backgrounds and the lines to paint again for their underlines, and returns the writes. private planDecorations(): () => void { const items = this.core.decorations(); const { first, last } = this.drawnWindow; @@ -1321,30 +1342,15 @@ export class EditorView { d.color, ]); } - const byLine = this.underlinesByLine(items, first, last); - const wanted = new Map(); + // A drawn line whose underlines changed while its text did not is painted again. + const { lines, descs } = this.underlinesByLine(items, first, last); + const repaint: [Entry, LineUnderline[], string][] = []; for (let line = first; line <= last; line++) { - const list = byLine.get(line); - if (!list) continue; - const parts = list.map( - (u) => `${u.a},${u.b},${u.d.color},${u.d.style},${u.d.thickness},${u.d.offset}`, - ); - wanted.set(line, `${this.overlayVersion}|${parts.join(';')}`); - } - const writeUnderlines = this.planLines( - this.underlineLayer, - this.underlineMarks, - wanted, - (line, entry, lineBox) => { - const out: Element[] = []; - for (const u of byLine.get(line) ?? []) { - for (const r of this.rowSpans(entry, u.a, u.b, lineBox)) { - out.push(this.underline(u.d, r.left, r.right, r.top)); - } - } - return out; - }, - ); + const entry = this.cache.get(line); + if (!entry || entry.stale || !this.attached.has(line)) continue; + const desc = descs.get(line) ?? ''; + if (entry.underlines !== desc) repaint.push([entry, lines.get(line) ?? [], desc]); + } return () => { // Each background keeps its element, so a wider line or a moved one is a style write. const els = this.backgroundEls; @@ -1363,18 +1369,17 @@ export class EditorView { put(el, 'height', height); put(el, 'background', color); }); - writeUnderlines(); + for (const [entry, under, desc] of repaint) { + this.paint(entry.el, entry.text, entry.spans, under); + entry.underlines = desc; + } }; } // The underlines on each drawn line as columns of that line, for the current decorations and text. - private underlinesByLine( - items: Decoration[], - first: number, - last: number, - ): Map { + private underlinesByLine(items: Decoration[], first: number, last: number): LineUnderlines { const key = `${this.core.decorationsVersion}:${this.core.revision}:${first}:${last}`; - if (key === this.underlines.key) return this.underlines.lines; + if (key === this.underlines.key) return this.underlines; const lines = new Map(); for (const d of items) { if (d.kind !== 'underline') continue; @@ -1389,8 +1394,17 @@ export class EditorView { else lines.set(line, [{ d, a, b }]); } } - this.underlines = { key, lines }; - return lines; + const descs = new Map(); + for (const [line, list] of lines) { + descs.set( + line, + list + .map((u) => `${u.a},${u.b},${u.d.color},${u.d.style},${u.d.thickness},${u.d.offset}`) + .join(';'), + ); + } + this.underlines = { key, lines, descs }; + return this.underlines; } // Reads the matches' boxes on the lines where they changed and returns the writes, the selected match in the active color. @@ -1508,61 +1522,6 @@ export class EditorView { return [start + columnEndingAfter(runs, left), start + columnEndingAfter(runs, right) + 1]; } - // Columns a to b of a drawn line merged to one box per row, relative to the line's top left. - private rowSpans( - entry: Entry, - a: number, - b: number, - lineBox: DOMRect, - ): { left: number; right: number; top: number }[] { - const rows = new Map(); - for (const r of this.columnRects(entry, a, b)) { - if (r.width <= 0) continue; - const row = Math.floor((r.top + r.height / 2 - lineBox.top) / this.rowHeight); - const left = r.left - lineBox.left; - const right = r.right - lineBox.left; - const seen = rows.get(row); - if (seen) { - seen.left = Math.min(seen.left, left); - seen.right = Math.max(seen.right, right); - } else rows.set(row, { left, right, top: row * this.rowHeight }); - } - return [...rows.values()]; - } - - // One underline piece on a row, solid as a bar or wavy as a clipped path, as DecorationPainter.kt draws them. - private underline( - d: Extract, - left: number, - right: number, - rowTop: number, - ): Element { - const thickness = d.thickness ?? 1; - const offset = d.offset ?? 2; - if (d.style !== 'wavy') { - const bar = div( - `position:absolute;left:${left}px;top:${solidTop(rowTop, this.baseline, offset)}px;width:${right - left}px;height:${Math.max(1, Math.round(thickness))}px;background:${d.color};`, - ); - bar.dataset.underline = ''; - return bar; - } - // The wave's centre sits a thickness below a solid line's top, and the box clips it like native. - const pad = waveAmplitude(thickness) + thickness; - const centre = rowTop + this.baseline + offset + thickness; - const svg = document.createElementNS(SVG, 'svg'); - svg.setAttribute('width', String(right - left)); - svg.setAttribute('height', String(2 * pad)); - svg.style.cssText = `position:absolute;left:${left}px;top:${centre - pad}px;overflow:hidden;`; - const path = document.createElementNS(SVG, 'path'); - path.setAttribute('d', wavePath(0, right - left, pad, thickness)); - path.setAttribute('fill', 'none'); - path.setAttribute('stroke', d.color); - path.setAttribute('stroke-width', String(thickness)); - svg.append(path); - svg.dataset.underline = ''; - return svg; - } - // Scrolls the least that shows the caret, by its line's row while the line is not drawn. True when it scrolled. private revealCaret(): boolean { const caret = this.drawnCaret; @@ -1761,6 +1720,7 @@ export class EditorView { if (metrics) { this.charWidth = measureChar(this.root); this.baseline = measureBaseline(this.root); + this.textBox = measureTextBox(this.root); this.layout.rowHeight = this.rowHeight; this.layout.wrap = o.softWrap; this.relayout(); @@ -1901,15 +1861,22 @@ export class EditorView { const revision = consistent ? frame.revision : -1; const pairs: number[] = []; const fresh: [number, Entry][] = []; + const under = this.underlinesByLine(this.core.decorations(), frame.first, frame.last); for (const run of frame.runs) { for (let line = run.lo; line <= run.hi; line++) { const data = run.lines[line - run.lo]; if (!data) continue; const entry = this.cache.get(line); + const desc = under.descs.get(line) ?? ''; let spans: Int32Array | null = null; if (consistent) { spans = data.spans.length > 0 ? data.spans : null; - if (entry && entry.text === data.text && sameSpans(entry.spans, spans)) { + if ( + entry && + entry.text === data.text && + sameSpans(entry.spans, spans) && + entry.underlines === desc + ) { entry.revision = revision; entry.stale = false; continue; @@ -1919,10 +1886,10 @@ export class EditorView { } const el = entry?.el ?? this.makeLine(); el.dataset.line = String(line); - this.paint(el, data.text, spans); + this.paint(el, data.text, spans, under.lines.get(line)); // The width it wraps at, before prepare reads its height. el.style.width = this.o.softWrap ? `${this.layout.wrapWidth}px` : ''; - const next = { el, revision, spans, text: data.text }; + const next: Entry = { el, revision, spans, text: data.text, underlines: desc }; this.cache.delete(line); this.cache.set(line, next); if (!el.isConnected) this.textLayer.append(el); @@ -2059,31 +2026,45 @@ export class EditorView { return div('position:absolute;direction:ltr;'); } - // Fills a line element with its text, one span per styled run. Runs that keep their styles only get new text. - private paint(el: HTMLDivElement, text: string, spans: Int32Array | null): void { + // Fills a line element with its text, one span per styled run, inside a span per underline over it. Runs that keep their styles only get new text. + private paint( + el: HTMLDivElement, + text: string, + spans: Int32Array | null, + under: LineUnderline[] = [], + ): void { el.style.whiteSpace = this.o.softWrap ? 'pre-wrap' : 'pre'; el.style.overflowWrap = this.o.softWrap ? 'anywhere' : 'normal'; - const runs: PaintRun[] = []; + const styled: PaintRun[] = []; let at = 0; if (spans) { for (let i = 0; i + 2 < spans.length; i += 3) { const start = Math.max(at, spans[i] as number); const end = Math.min(text.length, spans[i + 1] as number); if (end <= start) continue; - if (start > at) runs.push({ key: '', text: text.slice(at, start), style: null }); + if (start > at) styled.push({ key: '', text: text.slice(at, start), style: null }); const style = this.css.token(styleName(this.m, spans[i + 2] as number)); const key = style ? `s ${style.color} ${style.bold ? 1 : 0}${style.italic ? 1 : 0}` : 's'; - runs.push({ key, text: text.slice(start, end), style }); + styled.push({ key, text: text.slice(start, end), style }); at = end; } } - if (at < text.length) runs.push({ key: '', text: text.slice(at), style: null }); + if (at < text.length) styled.push({ key: '', text: text.slice(at), style: null }); + const runs: PaintPiece[] = + under.length > 0 + ? underlinePieces(styled, under).map((p) => ({ ...p, mark: underlineMark(p.chain) })) + : styled; const pieces = runs.map((run) => chunksOf(run.text)); const old = this.painted.get(el); const same = old !== undefined && old.length === runs.length && - old.every((r, i) => r.key === runs[i]?.key && r.parts.length === pieces[i]?.length); + old.every((r, i) => { + const run = runs[i] as PaintPiece; + return ( + r.key === run.key && r.mark === (run.mark ?? '') && r.parts.length === pieces[i]?.length + ); + }); if (same) { for (let i = 0; i < runs.length; i++) { const parts = (old[i] as PaintedRun).parts; @@ -2097,10 +2078,22 @@ export class EditorView { } const painted: PaintedRun[] = []; el.replaceChildren(); + // The underline spans open at this piece, outermost first, by the id each piece names. + let open: { id: number; span: HTMLSpanElement }[] = []; runs.forEach((run, i) => { const parts = (pieces[i] as string[]).map((piece) => document.createTextNode(piece)); + const chain = run.chain ?? []; + let keep = 0; + while (keep < open.length && open[keep]?.id === chain[keep]?.id) keep++; + open = open.slice(0, keep); + for (const link of chain.slice(keep)) { + const span = this.underlineSpan(link.u); + (open.at(-1)?.span ?? el).append(span); + open.push({ id: link.id, span }); + } + const host: HTMLElement = open.at(-1)?.span ?? el; if (run.key === '') { - el.append(...parts); + host.append(...parts); } else { const span = document.createElement('span'); span.append(...parts); @@ -2109,13 +2102,37 @@ export class EditorView { if (run.style.bold) span.style.fontWeight = 'bold'; if (run.style.italic) span.style.fontStyle = 'italic'; } - el.append(span); + host.append(span); } - painted.push({ key: run.key, parts }); + painted.push({ key: run.key, mark: run.mark ?? '', parts }); }); this.painted.set(el, painted); } + // A span drawing one underline as its background. Padding grows its box to reach the line, and each wrapped row starts the wave again, as native. + private underlineSpan(u: LineUnderline): HTMLSpanElement { + const box = this.textBox; + const layer = underlineLayer( + u.d.color, + u.d.style, + u.d.thickness ?? 1, + u.d.offset ?? 2, + this.baseline, + box.top, + ); + const above = Math.max(0, Math.ceil(-layer.top)); + const below = Math.max(0, Math.ceil(layer.bottom - (box.bottom - box.top))); + const span = document.createElement('span'); + span.dataset.underline = ''; + // The padding must not take taps from the next line. + span.style.cssText = `pointer-events:none;box-decoration-break:clone;-webkit-box-decoration-break:clone;background-repeat:${layer.repeat};background-size:${layer.size};`; + span.style.backgroundImage = layer.image; + span.style.backgroundPosition = `0 ${layer.top + above}px`; + if (above > 0) span.style.paddingTop = `${above}px`; + if (below > 0) span.style.paddingBottom = `${below}px`; + return span; + } + // Moves the cache along an edit and keeps the edited line's spans shifted until the parse catches up. private changed(change: WebChange, count: number): void { if (count > 1) { @@ -2198,6 +2215,13 @@ export class EditorView { } } +// The spans a piece sits in by id and look, so a repaint keeps those spans only when both hold. +function underlineMark(chain: UnderlineLink[]): string { + return chain + .map(({ id, u }) => `${id} ${u.d.color} ${u.d.style} ${u.d.thickness} ${u.d.offset}`) + .join(','); +} + // The non-empty text nodes of a line element with the column each starts at. function textRuns(el: HTMLElement): { node: Text; at: number }[] { const runs: { node: Text; at: number }[] = []; diff --git a/src/web/__tests__/decorations.test.ts b/src/web/__tests__/decorations.test.ts index 1b31447..a0dfd52 100644 --- a/src/web/__tests__/decorations.test.ts +++ b/src/web/__tests__/decorations.test.ts @@ -1,5 +1,5 @@ import { expect, test } from '@jest/globals'; -import { solidTop, wavePath } from '../decorations'; +import { solidTop, underlineLayer, underlinePieces, wavePath } from '../decorations'; test('a wave starts on the centre line heading down, half a wavelength per curve', () => { const d = wavePath(0, 10, 5, 1); @@ -16,6 +16,79 @@ test('a wave scales with the thickness', () => { }); test('a solid underline sits offset below the baseline, on a whole pixel', () => { - expect(solidTop(20, 14.6, 2)).toBe(37); - expect(solidTop(0, 14.4, 2)).toBe(16); + expect(solidTop(14.6, 2)).toBe(17); + expect(solidTop(14.4, 2)).toBe(16); +}); + +test('a solid underline layer sits where the bar sat, measured from the text box top', () => { + const layer = underlineLayer('red', 'solid', 2, 4, 14.6, 1); + expect(layer.position).toBe('0 18px'); + expect(layer.size).toBe('100% 2px'); + expect(layer.repeat).toBe('no-repeat'); + expect(layer.bottom).toBe(20); +}); + +test('a wavy underline layer tiles one wavelength of the native wave', () => { + const layer = underlineLayer('blue', 'wavy', 1, 2, 14.6, 1); + // Wavelength (4 + 0.375), box twice the amplitude plus the thickness, centre a thickness below a bar's top. + expect(layer.size).toBe('4.375px 3.75px'); + expect(layer.position).toBe(`0 ${14.6 + 2 + 1 - 1.875 - 1}px`); + expect(layer.repeat).toBe('repeat-x'); + expect(decodeURIComponent(layer.image)).toContain('M0 1.875 Q1.09375 3.625 2.1875 1.875'); +}); + +// Each piece's text and the ids of the underline spans it sits in, outermost first. +const chains = (pieces: { text: string; chain: { id: number }[] }[]) => + pieces.map((p) => [p.text, p.chain.map((c) => c.id)]); + +test('one underline over several syntax runs is one span', () => { + const runs = [ + { key: 'a', text: 'foo' }, + { key: 'b', text: '.' }, + { key: 'a', text: 'bar' }, + ]; + expect(chains(underlinePieces(runs, [{ a: 0, b: 7 }]))).toEqual([ + ['foo', [0]], + ['.', [0]], + ['bar', [0]], + ]); +}); + +test('a short underline inside a long one opens inside it, so the long wave runs on', () => { + const pieces = underlinePieces( + [{ key: '', text: 'abcdefghij' }], + [ + { a: 0, b: 10 }, + { a: 3, b: 5 }, + ], + ); + expect(chains(pieces)).toEqual([ + ['abc', [0]], + ['de', [0, 1]], + ['fghij', [0]], + ]); +}); + +test('a partial overlap reopens the underline that goes on, bare text outside', () => { + const pieces = underlinePieces( + [{ key: '', text: 'abcdefgh' }], + [ + { a: 0, b: 4 }, + { a: 2, b: 6 }, + ], + ); + expect(chains(pieces)).toEqual([ + ['ab', [0]], + ['cd', [0, 1]], + ['ef', [2]], + ['gh', []], + ]); +}); + +test('underlines on the same text nest in their order, so the later one draws on top', () => { + const first = { a: 0, b: 3 }; + const second = { a: 0, b: 3 }; + const [piece] = underlinePieces([{ key: '', text: 'abc' }], [first, second]); + expect(piece?.chain.map((c) => c.u)).toEqual([first, second]); + expect(piece?.chain[1]?.u).toBe(second); }); diff --git a/src/web/decorations.ts b/src/web/decorations.ts index 2065e85..c318f9f 100644 --- a/src/web/decorations.ts +++ b/src/web/decorations.ts @@ -23,9 +23,104 @@ export function wavePath(left: number, right: number, centre: number, thickness: return d; } -// The top of a solid underline: offset below the baseline, on a whole pixel like a browser draws it. -export function solidTop(rowTop: number, baseline: number, offset: number): number { - return Math.round(rowTop + baseline + offset); +// The top of a solid underline below its row's top: offset below the baseline, on a whole pixel like a browser draws it. +export function solidTop(baseline: number, offset: number): number { + return Math.round(baseline + offset); +} + +// One underline drawn as a background layer of the span over its text, placed from the span's top. +export type UnderlineLayer = { + image: string; + size: string; + position: string; + repeat: string; + // Where the layer starts and ends below the span's top, so the span can grow its box to show it. + top: number; + bottom: number; +}; + +export function underlineLayer( + color: string, + style: 'solid' | 'wavy' | undefined, + thickness: number, + offset: number, + baseline: number, + boxTop: number, +): UnderlineLayer { + if (style !== 'wavy') { + const height = Math.max(1, Math.round(thickness)); + const y = solidTop(baseline, offset) - boxTop; + return { + image: `linear-gradient(${color},${color})`, + size: `100% ${height}px`, + position: `0 ${y}px`, + repeat: 'no-repeat', + top: y, + bottom: y + height, + }; + } + // One wavelength per tile, its centre a thickness below a solid line's top as native draws it. + const pad = waveAmplitude(thickness) + thickness; + const period = 2 * waveHalf(thickness); + const top = baseline + offset + thickness - pad - boxTop; + const path = wavePath(0, period, pad, thickness); + const svg = ``; + return { + image: `url("data:image/svg+xml,${encodeURIComponent(svg)}")`, + size: `${period}px ${2 * pad}px`, + position: `0 ${top}px`, + repeat: 'repeat-x', + top, + bottom: top + 2 * pad, + }; +} + +// An underline span a piece sits in. Pieces with the same id share one span. +export type UnderlineLink = { id: number; u: U }; + +// Runs cut at every underline edge, each with the underline spans it sits in, outermost first. An underline stays one span while the ones inside it close first, so its wave keeps its phase. A partial overlap reopens the one that goes on. +export function underlinePieces( + runs: R[], + under: U[], +): (R & { chain: UnderlineLink[] })[] { + const cuts = [...new Set(under.flatMap((u) => [u.a, u.b]))].sort((x, y) => x - y); + const out: (R & { chain: UnderlineLink[] })[] = []; + let open: UnderlineLink[] = []; + let next = 0; + let at = 0; + for (const run of runs) { + const end = at + run.text.length; + let from = at; + for (const to of [...cuts.filter((c) => c > at && c < end), end]) { + const over = under.filter((u) => u.a < to && u.b > from); + let keep = 0; + while (keep < open.length && over.includes((open[keep] as UnderlineLink).u)) keep++; + open = open.slice(0, keep); + // The longer ones open outside, and the same text nests in list order so the later one draws on top. + const opening = over + .filter((u) => !open.some((l) => l.u === u)) + .sort((x, y) => y.b - x.b || under.indexOf(x) - under.indexOf(y)); + for (const u of opening) open.push({ id: next++, u }); + out.push({ ...run, text: run.text.slice(from - at, to - at), chain: open }); + from = to; + } + at = end; + } + return out; +} + +// A span's box in a row, from the row's top: the area an inline background paints in. +export function measureTextBox(root: HTMLElement): { top: number; bottom: number } { + const line = document.createElement('div'); + line.style.cssText = 'position:absolute;visibility:hidden;white-space:pre;'; + const span = document.createElement('span'); + span.textContent = '0'; + line.append(span); + root.append(line); + const top = line.getBoundingClientRect().top; + const box = span.getBoundingClientRect(); + line.remove(); + return { top: box.top - top, bottom: box.bottom - top }; } // From a row's top to its text baseline, in the root's font and line height. diff --git a/tests/web/harness/index.html b/tests/web/harness/index.html index 3f53a42..9bb89ec 100644 --- a/tests/web/harness/index.html +++ b/tests/web/harness/index.html @@ -42,7 +42,34 @@ const boxes = lineBoxes(id); return boxes.slice(1).filter((b, i) => b.top < boxes[i].bottom - 0.5).length; } - window.codepad = { EditorView, ensureLanguage, frames, githubLight, loadCore, overlaps, until }; + // Each underline under a host as drawn: one page box per row its span covers, from the span's background. + function underlineBars(id) { + return [...document.querySelectorAll(`#${id} [data-underline]`)].flatMap((span) => { + const style = getComputedStyle(span); + const y = Number.parseFloat(style.backgroundPositionY); + const [width, height] = style.backgroundSize.split(' ').map(Number.parseFloat); + const wavy = style.backgroundImage.includes('svg'); + return [...span.getClientRects()].map((r) => ({ + left: r.left, + right: r.right, + width: r.width, + top: r.top + y, + bottom: r.top + y + height, + wavy, + wavelength: wavy ? width : 0, + })); + }); + } + window.codepad = { + EditorView, + ensureLanguage, + frames, + githubLight, + loadCore, + overlaps, + underlineBars, + until, + }; window.ready = true; diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 62347d8..19e79ac 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -1402,7 +1402,21 @@ for (const engine of [chromium, webkit]) { await page.close(); }); - // The box of a line element and the underline bars, relative to the editor's root. + // Each underline as drawn, one box per row, relative to the editor's root. + const bars = (page, id) => + page.evaluate(async (id) => { + await window.codepad.frames(2); + const root = document.getElementById(id).firstElementChild.getBoundingClientRect(); + return window.codepad.underlineBars(id).map((b) => ({ + ...b, + top: b.top - root.top, + bottom: b.bottom - root.top, + left: b.left - root.left, + right: b.right - root.left, + })); + }, id); + + // The box of a line element, relative to the editor's root. const boxes = (page, id, selector) => page.evaluate( async ([id, selector]) => { @@ -1430,22 +1444,30 @@ for (const engine of [chromium, webkit]) { -1, ), ); - const bars = await boxes(page, 'a', '[data-underline]'); + const drawn = await bars(page, 'a'); const [line] = await boxes(page, 'a', '[data-line="0"]'); - const row = await page.evaluate(() => window.views.a.layout.rowHeight); - assert.ok(bars.length >= 2, `${bars.length} bars`); - for (const b of bars) { + const [row, baseline] = await page.evaluate(() => [ + window.views.a.layout.rowHeight, + window.views.a.baseline, + ]); + assert.ok(drawn.length >= 2, `${drawn.length} bars`); + // The default offset puts the bar 2 px under the baseline on a whole pixel, as native. + assert.ok( + Math.abs(drawn[0].top - line.top - Math.round(baseline + 2)) < 0.5, + JSON.stringify({ bar: drawn[0], line, baseline }), + ); + for (const b of drawn) { assert.ok(b.top > line.top && b.bottom <= line.bottom + 1, JSON.stringify({ b, line })); assert.ok( b.left >= line.left - 1 && b.right <= line.right + 1, JSON.stringify({ b, line }), ); - assert.equal(Math.round(b.top - bars[0].top) % row, 0); + assert.equal(Math.round(b.top - drawn[0].top) % row, 0); } await page.close(); }); - test('a wavy underline draws one path per row clipped to its range', async () => { + test('a wavy underline draws one wave across its range', async () => { const { page } = await open(); await editor(page, 'a', 'let total = 1'); await page.evaluate(() => @@ -1454,23 +1476,61 @@ for (const engine of [chromium, webkit]) { -1, ), ); - const [wave] = await boxes(page, 'a', 'svg[data-underline]'); - const width = await page.evaluate(() => { - const el = document.querySelector('#a [data-line="0"]'); - const range = document.createRange(); - range.setStart(el.firstChild, 4); - range.setEnd(el.firstChild, 9); - return range.getBoundingClientRect().width; - }); - assert.ok(wave, 'no wave'); + // The width of columns a to b of line 0, and the line's top and baseline, from the text itself. + const text = (a, b) => + page.evaluate( + ([a, b]) => { + const el = document.querySelector('#a [data-line="0"]'); + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + const range = document.createRange(); + let at = 0; + for (let n = walker.nextNode(); n; n = walker.nextNode()) { + if (a >= at && a <= at + n.data.length) range.setStart(n, a - at); + if (b >= at && b <= at + n.data.length) range.setEnd(n, b - at); + at += n.data.length; + } + const root = document.getElementById('a').firstElementChild.getBoundingClientRect(); + return { + width: range.getBoundingClientRect().width, + top: el.getBoundingClientRect().top - root.top, + baseline: window.views.a.baseline, + }; + }, + [a, b], + ); + let drawn = await bars(page, 'a'); + let range = await text(4, 9); + assert.equal(drawn.length, 1, JSON.stringify(drawn)); + assert.ok(drawn[0].wavy, 'not a wave'); + assert.ok( + Math.abs(drawn[0].width - range.width) <= 1, + `${drawn[0].width} for ${range.width}`, + ); + // One wavelength of the native wave at thickness 1, its box from a thickness below the bar's top less the swing and the stroke. + assert.equal(drawn[0].wavelength, 4.375); assert.ok( - Math.abs(wave.right - wave.left - width) <= 1, - `${wave.right - wave.left} for ${width}`, + Math.abs(drawn[0].top - range.top - (range.baseline + 2 + 1 - 1.875)) < 0.5, + JSON.stringify({ bar: drawn[0], range }), + ); + // A short solid underline inside a long wavy one leaves the wave in one piece. + await page.evaluate(() => + window.views.a.setDecorations( + [ + { kind: 'underline', range: { start: 0, end: 13 }, color: 'blue', style: 'wavy' }, + { kind: 'underline', range: { start: 4, end: 9 }, color: 'red' }, + ], + -1, + ), ); - assert.equal( - await page.evaluate(() => document.querySelectorAll('#a svg[data-underline] path').length), - 1, + drawn = await bars(page, 'a'); + range = await text(0, 13); + const waves = drawn.filter((b) => b.wavy); + assert.equal(waves.length, 1, JSON.stringify(drawn)); + assert.ok( + Math.abs(waves[0].width - range.width) <= 1, + `${waves[0].width} for ${range.width}`, ); + assert.equal(drawn.length, 2, JSON.stringify(drawn)); await page.close(); }); @@ -1497,6 +1557,121 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('a typed letter on an underlined line adds no underline element outside its line', async () => { + const { page } = await open(); + await editor(page, 'a', 'let total = 1\nlet count = 2'); + const seen = await page.evaluate(async () => { + const v = window.views.a; + v.setDecorations( + [ + { kind: 'underline', range: { start: 4, end: 9 }, color: '#ff0000' }, + { kind: 'underline', range: { start: 18, end: 23 }, color: '#0000ff', style: 'wavy' }, + ], + v.core.revision, + ); + await window.codepad.frames(2); + const outside = []; + const observer = new MutationObserver((list) => { + for (const m of list) { + for (const n of m.addedNodes) { + if (n.nodeType !== 1 || n.closest('[data-line]')) continue; + if (n.matches('[data-underline]') || n.querySelector('[data-underline]')) + outside.push(n.outerHTML.slice(0, 60)); + } + } + }); + observer.observe(document.getElementById('a'), { childList: true, subtree: true }); + v.apply(() => v.core.replace(0, 0, 'x')); + await window.codepad.frames(2); + observer.disconnect(); + return { + outside, + inLines: document.querySelectorAll('#a [data-line] [data-underline]').length, + }; + }); + assert.deepEqual(seen, { outside: [], inLines: 2 }); + await page.close(); + }); + + test('a selection over an underlined word draws every box the height of the text', async () => { + const { page } = await open(); + await editor(page, 'a', 'let total = 1'); + const bottoms = await page.evaluate(async () => { + const v = window.views.a; + const underline = { start: 4, end: 9 }; + v.setDecorations( + [{ kind: 'underline', range: underline, color: '#0000ff', style: 'wavy', thickness: 2 }], + v.core.revision, + ); + await window.codepad.frames(2); + v.apply(() => v.core.setSelection(0, 13)); + await window.codepad.frames(2); + return [...document.querySelectorAll('#a [data-selection] > div')].map( + (d) => d.getBoundingClientRect().bottom, + ); + }); + assert.ok(bottoms.length > 0, 'no selection'); + assert.ok( + Math.max(...bottoms) - Math.min(...bottoms) < 0.5, + `selection bottoms ${bottoms.join(', ')}`, + ); + await page.close(); + }); + + test('a tap at the top of a line under a low underline lands on that line', async () => { + const { page } = await open(); + await editor(page, 'a', 'aaaa\nbbbb'); + const offset = await page.evaluate(async () => { + const v = window.views.a; + v.setDecorations( + [ + { + kind: 'underline', + range: { start: 0, end: 4 }, + color: '#0000ff', + style: 'wavy', + thickness: 3, + offset: 6, + }, + ], + v.core.revision, + ); + await window.codepad.frames(2); + // The upper line painted last, as a line scrolled in from above is, so its box lies over the next. + const upper = document.querySelector('#a [data-line="0"]'); + upper.parentElement.append(upper); + const lower = document.querySelector('#a [data-line="1"]').getBoundingClientRect(); + return v.textOffsetAt(lower.left + 12, lower.top + 1); + }); + assert.ok(offset >= 5, `offset ${offset}`); + await page.close(); + }); + + test('a tap inside an underlined word puts the caret there', async () => { + const { page } = await open(); + await editor(page, 'a', 'let total = 1'); + await page.evaluate(async () => { + const v = window.views.a; + v.setDecorations( + [ + { kind: 'underline', range: { start: 4, end: 9 }, color: '#ff0000', style: 'wavy' }, + { kind: 'underline', range: { start: 6, end: 8 }, color: '#0000ff' }, + ], + v.core.revision, + ); + await window.codepad.frames(2); + }); + for (const column of [5, 7]) { + await clickAt(page, 'a', 0, column); + const head = await page.evaluate(async () => { + await window.codepad.frames(2); + return window.views.a.core.selection.head; + }); + assert.equal(head, column); + } + await page.close(); + }); + test('a line background keeps its element and grows when a key widens the text', async () => { const { page } = await open(); await editor(page, 'a', 'ab\ncd'); @@ -1850,7 +2025,7 @@ for (const engine of [chromium, webkit]) { const off = () => { const match = document.querySelector('#a [data-match]').getBoundingClientRect(); const bracket = document.querySelector('#a [data-bracket]').getBoundingClientRect(); - const line = document.querySelector('#a [data-underline]').getBoundingClientRect(); + const [line] = window.codepad.underlineBars('a'); const ab = textBox(1, 3); const open = textBox(0, 1); const under = textBox(5, 7); @@ -1907,7 +2082,7 @@ for (const engine of [chromium, webkit]) { const marks = (s) => [...document.querySelectorAll(`#a ${s}`)].map((m) => m.getBoundingClientRect()); const matches = marks('[data-match]'); - const unders = marks('[data-underline]'); + const unders = window.codepad.underlineBars('a'); let missing = 0; let wantMatches = 0; let wantUnders = 0; @@ -1975,7 +2150,8 @@ for (const engine of [chromium, webkit]) { await window.codepad.frames(3); return [before.length, all().filter((m) => m.__kept).length]; }); - assert.deepEqual(kept, [18, 15]); + // The edited line's matches move with its text. Its underline is painted with the text and stays. + assert.deepEqual(kept, [18, 16]); assert.deepEqual(await marksOnText(page), ON_TEXT); await page.close(); }); From 0917bd08b87dd4444b5c29781841ccaff0a98d3d Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sun, 22 Nov 2026 02:02:36 +0100 Subject: [PATCH 03/14] fix(web): put the caret on the empty line a tap lands on An empty line's element held no text, so its box was 0 px tall. A click on a blank line put the caret on an earlier line (line 0 for line 1 of a file that opens with an import and a blank line), because the browser's hit test snapped to the nearest text and the fallback by row never matched a box with no height. Line elements now keep at least one row of height. --- src/web/EditorView.ts | 3 ++- tests/web/render.e2e.mjs | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 335792a..67f7080 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -2022,8 +2022,9 @@ export class EditorView { } } + // An empty line keeps a row of height, so a tap on it hits it and not the nearest text. private makeLine(): HTMLDivElement { - return div('position:absolute;direction:ltr;'); + return div(`position:absolute;direction:ltr;min-height:${this.rowHeight}px;`); } // Fills a line element with its text, one span per styled run, inside a span per underline over it. Runs that keep their styles only get new text. diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 19e79ac..c51bf98 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -1647,6 +1647,29 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('a click on an empty line puts the caret on it', async () => { + const { page } = await open(); + await editor(page, 'a', 'import re\n\nTOKEN = 1\n\n\nend'); + for (const line of [1, 3, 4]) { + const { x, y } = await page.evaluate((line) => { + const v = window.views.a; + const first = document.querySelector('#a [data-line="0"]').getBoundingClientRect(); + return { + x: first.left + 40, + y: first.top + v.layout.rowHeight * (line + 0.5), + }; + }, line); + await page.mouse.click(x, y); + const head = await page.evaluate(async () => { + await window.codepad.frames(2); + const v = window.views.a; + return v.core.lineAt(v.core.selection.head); + }); + assert.equal(head, line); + } + await page.close(); + }); + test('a tap inside an underlined word puts the caret there', async () => { const { page } = await open(); await editor(page, 'a', 'let total = 1'); From 936d44821a68568824913ac173c0d12240f569e0 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sun, 22 Nov 2026 02:27:53 +0100 Subject: [PATCH 04/14] fix(web): keep the insertion handle while its menu is open The insertion handle faded 4 s after a tap even with its Paste menu open, and a menu placed under the caret then jumped up 44 px, so a finger on its way to Paste landed on the text instead. The handle now stays while the menu is open and fades 4 s after the menu closes. --- src/web/EditorView.ts | 12 ++++++++++-- tests/web/render.e2e.mjs | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 67f7080..16b4e5f 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -573,12 +573,19 @@ export class EditorView { } private showInsertion(): void { - clearTimeout(this.insertionTimer); this.insertionShown = true; - this.insertionTimer = setTimeout(() => this.hideInsertion(), INSERTION_HANDLE_MS); + this.fadeInsertionLater(); this.invalidate(); } + // The handle fades 4 s on, but not while its menu is open: the menu stands under it and would jump up. + private fadeInsertionLater(): void { + clearTimeout(this.insertionTimer); + this.insertionTimer = setTimeout(() => { + if (!this.menu.shown) this.hideInsertion(); + }, INSERTION_HANDLE_MS); + } + private hideInsertion(): void { clearTimeout(this.insertionTimer); if (!this.insertionShown) return; @@ -622,6 +629,7 @@ export class EditorView { if (!this.menu.shown) return; this.menu.hide(); this.menuAt = null; + if (this.insertionShown) this.fadeInsertionLater(); } // The menu's anchor in page coordinates: a right click's pointer, else the ends in view and, as Android, the handles under them. diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index c51bf98..00603ed 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -870,6 +870,26 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('the insertion handle stays while its menu is open, so the menu stays put', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await tap(page, 'a', await pointAt(page, 'a', 0, 3)); + const tip = (await tips(page, 'a')).insertion; + await tap(page, 'a', { x: tip.x, y: tip.y + 10 }); + const before = (await menuOf(page))?.box; + await page.waitForTimeout(4200); + await settle(page); + assert.deepEqual(Object.keys(await tips(page, 'a')), ['insertion']); + assert.deepEqual((await menuOf(page))?.box, before); + // Once the menu closes, the handle fades 4 s later. + await page.evaluate(() => window.views.a.blur()); + await page.waitForTimeout(4200); + await settle(page); + assert.equal(await menuOf(page), null); + assert.deepEqual(await tips(page, 'a'), {}); + await page.close(); + }); + test('readOnly shows only Copy and Select all and the textarea stays readonly', async () => { const { page } = await open(); await editor(page, 'a', 'alpha beta gamma', { readOnly: true }); From dbf2742bb78d9bd4b0eb55be8b82fe387250fd56 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 12:52:50 +0100 Subject: [PATCH 05/14] chore(web): print none for an empty list in the typing bench --- scripts/bench-web.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/bench-web.mjs b/scripts/bench-web.mjs index 34d5e19..e48554c 100644 --- a/scripts/bench-web.mjs +++ b/scripts/bench-web.mjs @@ -113,6 +113,7 @@ try { if (desktop !== null) await cdp.send('Emulation.setCPUThrottlingRate', { rate: 1 }); const probe = await page.evaluate(() => globalThis.__codepadProbe); const stats = (list) => { + if (list.length === 0) return 'none'; const sorted = [...list].sort((a, b) => a - b); const mean = list.reduce((a, b) => a + b, 0) / Math.max(1, list.length); return `mean ${ms(mean)}, p50 ${ms(pct(sorted, 0.5))}, p95 ${ms(pct(sorted, 0.95))}, max ${ms(sorted.at(-1) ?? 0)}`; From d486f5d585c7f2ee2f800e52b6e90f3454bfc0a7 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 12:55:43 +0100 Subject: [PATCH 06/14] feat(example): add a readOnly toggle on the web and a minified file --- example/src/EditorApp.web.tsx | 10 ++++++++-- example/src/bench/generate.ts | 9 +++++++++ example/src/files.ts | 8 +++++++- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx index e56bb00..7e1ed95 100644 --- a/example/src/EditorApp.web.tsx +++ b/example/src/EditorApp.web.tsx @@ -10,7 +10,10 @@ import { NESTED_SNIPPET } from './screens/nestedSnippet'; import { THEMES } from './themes'; type Demo = 'editor' | 'nested' | 'two'; -const FILES = [...SAMPLE_FILES, ...GENERATED_FILES.filter((f) => f.id === 'js10k')]; +const FILES = [ + ...SAMPLE_FILES, + ...GENERATED_FILES.filter((f) => f.id === 'js10k' || f.id === 'min'), +]; const FONT = 'JetBrainsMono_400Regular'; const NO_DECORATIONS: { items: Decoration[]; revision: number } = { items: [], revision: -1 }; @@ -29,11 +32,12 @@ function Chip({ label, on, onPress }: { label: string; on?: boolean; onPress: () ); } -// The example on the web: a file picker, a theme and scrollEnabled toggle, a nested and a two editor demo. +// The example on the web: a file picker, theme, scrollEnabled and readOnly toggles, a nested and a two editor demo. export function EditorApp() { const [fileId, setFileId] = useState('python'); const [themeIndex, setThemeIndex] = useState(0); const [scrollEnabled, setScrollEnabled] = useState(true); + const [readOnly, setReadOnly] = useState(false); const [suggestions, setSuggestions] = useState<'on' | 'off'>('off'); const [decorate, setDecorate] = useState(false); const [finding, setFinding] = useState(false); @@ -113,6 +117,7 @@ export function EditorApp() { on={!scrollEnabled} onPress={() => setScrollEnabled((s) => !s)} /> + setReadOnly((r) => !r)} /> !line.startsWith('//')) + .map((line) => line.trim()) + .join(''); +} + const WORDS = ['editor', 'caret', 'buffer', 'syntax', 'theme', 'inset', 'scroll', 'layout']; /** Deterministic markdown: a heading every 50 paragraphs, emphasis and inline code in each, a fenced block every tenth. */ diff --git a/example/src/files.ts b/example/src/files.ts index 7355d97..21df8a7 100644 --- a/example/src/files.ts +++ b/example/src/files.ts @@ -1,4 +1,4 @@ -import { generateJavaScript, generateMarkdown } from './bench/generate'; +import { generateJavaScript, generateMarkdown, generateMinified } from './bench/generate'; import { type LanguageId, SAMPLES } from './samples'; export type EditorFile = { @@ -85,6 +85,12 @@ export const GENERATED_FILES: EditorFile[] = [ language: 'markdown', load: () => generateMarkdown(2000), }, + { + id: 'min', + name: 'minified.js', + language: 'javascript', + load: () => generateMinified(1000), + }, ]; export const UNTITLED: EditorFile = { id: 'untitled', name: 'untitled', load: () => '' }; From 1a97271a3a5d79d1fba8fcceb7d4b030c766447a Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 13:07:55 +0100 Subject: [PATCH 07/14] fix(web): let the insertion handle fade after a menu item closes the menu When Safari's paste prompt was dismissed, the insertion handle stayed on screen for good. Its 4 s fade comes due while the menu is open and waits for the menu to close, but a menu item closed the menu without telling the editor. The menu now reports every close, so the fade starts again whatever closed it. --- src/web/EditMenu.ts | 6 +++++- src/web/EditorView.ts | 7 ++++--- tests/web/render.e2e.mjs | 24 ++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/web/EditMenu.ts b/src/web/EditMenu.ts index 5363297..5319da3 100644 --- a/src/web/EditMenu.ts +++ b/src/web/EditMenu.ts @@ -8,6 +8,8 @@ export type MenuActions = { copy(): void; paste(): void; selectAll(): void; + // Runs whatever closed the menu: an item, the editor, or another editor's menu opening. + hidden(): void; }; export type MenuTheme = { background: string; foreground: string; border: string }; @@ -29,7 +31,7 @@ export class EditMenu { private size = { width: 0, height: 0 }; private themed = ''; - constructor(actions: MenuActions) { + constructor(private readonly actions: MenuActions) { this.items = [ { label: 'Cut', enabled: () => actions.canCut(), run: () => actions.cut(), keepsMenu: false }, { @@ -75,9 +77,11 @@ export class EditMenu { } hide(): void { + const was = this.isShown; this.isShown = false; if (active === this) active = null; this.el.style.display = 'none'; + if (was) this.actions.hidden(); } // Places the menu above the anchor, or below when the visible area has no room above. Both in page coordinates. diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 16b4e5f..cabfcfc 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -385,6 +385,10 @@ export class EditorView { }, paste: () => this.clipboardFailed(this.pasteClipboard()), selectAll: () => this.apply(() => this.core.selectAll()), + hidden: () => { + this.menuAt = null; + if (this.insertionShown) this.fadeInsertionLater(); + }, }); this.handles = new Handles(this.textLayer); // The browser keeps panning and pinch zoom, the editor takes taps and long presses. @@ -626,10 +630,7 @@ export class EditorView { } private hideMenu(): void { - if (!this.menu.shown) return; this.menu.hide(); - this.menuAt = null; - if (this.insertionShown) this.fadeInsertionLater(); } // The menu's anchor in page coordinates: a right click's pointer, else the ends in view and, as Android, the handles under them. diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 00603ed..3492ce1 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -890,6 +890,30 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('a refused Paste from the handle menu lets the insertion handle fade', async () => { + const { page, warnings } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await page.evaluate(() => + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { readText: () => Promise.reject(new Error('NotAllowedError')) }, + }), + ); + await tap(page, 'a', await pointAt(page, 'a', 0, 3)); + const tip = (await tips(page, 'a')).insertion; + await tap(page, 'a', { x: tip.x, y: tip.y + 10 }); + // The fade comes due while the menu is open, so only the menu closing can start it again. + await page.waitForTimeout(4200); + await pressMenu(page, 'Paste'); + await page.waitForTimeout(4200); + await settle(page); + assert.equal(await menuOf(page), null); + assert.deepEqual(await tips(page, 'a'), {}); + assert.equal(await page.evaluate(() => window.views.a.core.text()), 'alpha beta gamma'); + assert.equal(warnings.length, 1); + await page.close(); + }); + test('readOnly shows only Copy and Select all and the textarea stays readonly', async () => { const { page } = await open(); await editor(page, 'a', 'alpha beta gamma', { readOnly: true }); From 0d983f334446bc81ba45dff8fb09fbf8982ea066 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 13:20:16 +0100 Subject: [PATCH 08/14] fix(web): keep Safari's callout off the line numbers A long press on the gutter in Safari on iOS selected a line number and opened Safari's own Copy, Look Up, Translate menu on top of the editor's menu. Only the text layer turned off text selection and the touch callout. The gutter now does too. --- src/web/EditorView.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index cabfcfc..2fdbb47 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -307,7 +307,10 @@ export class EditorView { this.scroller = div('position:absolute;inset:0;overflow:auto;'); this.scroller.dataset.scroller = ''; this.content = div('position:relative;'); - this.gutter = div('position:sticky;left:0;top:0;z-index:2;'); + // Safari selects a line number and opens its own callout on a long press without these. + this.gutter = div( + 'position:sticky;left:0;top:0;z-index:2;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;', + ); this.textLayer = div('position:absolute;left:0;top:0;width:100%;height:100%;'); this.activeLine = div('position:absolute;left:0;display:none;'); this.placeholderEl = div('position:absolute;white-space:pre;display:none;pointer-events:none;'); From be71a4fa69112a59daa58ac046b1428a4fa3f639 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 13:39:46 +0100 Subject: [PATCH 09/14] fix(web): focus the editor again after a held handle drag On Chrome for Android, dragging a selection handle for more than half a second dropped the keyboard and hid the handles, while the selection and its menu stayed. Chrome blurs the focused field during any held touch, and only a tap or a long press focused the editor again on release. A handle drag now does too. --- src/web/input/PointerHost.ts | 7 ++++++- tests/web/render.e2e.mjs | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/web/input/PointerHost.ts b/src/web/input/PointerHost.ts index cccc5df..b4ea472 100644 --- a/src/web/input/PointerHost.ts +++ b/src/web/input/PointerHost.ts @@ -55,7 +55,12 @@ export class PointerHost { 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), + // Chrome blurs the textarea during a held handle as during a long press, so the release focuses it again. + handleAt: (x, y) => { + const kind = hooks.handleAt(x, y); + if (kind) this.focusOnUp = true; + return kind; + }, insideSelection: (offset) => { const { anchor, head } = hooks.selection(); return ( diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 3492ce1..57c279f 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -658,6 +658,23 @@ for (const engine of [chromium, webkit]) { await settle(page); } + test('a handle drag the browser blurs mid-hold ends with the editor focused', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + const tip = (await tips(page, 'a')).end; + const from = { x: tip.x, y: tip.y + 10 }; + await touch(page, 'a', 'pointerdown', from); + // Chrome on Android blurs the textarea about 500 ms into a held touch. + await page.evaluate(() => document.querySelector('#a textarea').blur()); + await touch(page, 'a', 'pointermove', { x: from.x + 20, y: from.y }); + await touch(page, 'a', 'pointerup', { x: from.x + 20, y: from.y }); + await settle(page); + assert.equal(await page.evaluate(() => window.views.a.focused), true); + assert.deepEqual(Object.keys(await tips(page, 'a')).sort(), ['end', 'start']); + await page.close(); + }); + 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'); From f19467bb4d8874cf66271d72bd5860daca50c493 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 14:12:04 +0100 Subject: [PATCH 10/14] fix(web): end the insertion handle when the selection becomes a range A tap, then a long press on a word, then an arrow key 4 s later showed an insertion handle at the new caret for another 4 s. The handle's fade skips while a menu is open, and the word's menu kept the tap's handle alive under the selection. A range selection now ends the insertion handle. The test for the handle's fade after its menu closes now closes the menu with a key instead of a blur, which hid the handles on its own. --- src/web/EditorView.ts | 2 ++ tests/web/render.e2e.mjs | 24 +++++++++++++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 2fdbb47..7429b0b 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -493,6 +493,8 @@ export class EditorView { this.changed(change, changes.length); } const s = this.core.selection; + // The insertion handle belongs to a caret, so a range ends it. + if (s.anchor !== s.head) this.hideInsertion(); const moved = s.anchor !== this.lastSelection.anchor || s.head !== this.lastSelection.head; if (moved) this.lastSelection = s; if (moved && !this.movingVertically) this.mover.reset(); diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 57c279f..a0c4a32 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -898,11 +898,29 @@ for (const engine of [chromium, webkit]) { await settle(page); assert.deepEqual(Object.keys(await tips(page, 'a')), ['insertion']); assert.deepEqual((await menuOf(page))?.box, before); - // Once the menu closes, the handle fades 4 s later. - await page.evaluate(() => window.views.a.blur()); - await page.waitForTimeout(4200); + // Once the menu closes, the handle fades 4 s later. An arrow key closes it and keeps the focus. + await page.keyboard.press('ArrowRight'); await settle(page); assert.equal(await menuOf(page), null); + assert.deepEqual(Object.keys(await tips(page, 'a')), ['insertion']); + await page.waitForTimeout(4200); + await settle(page); + assert.deepEqual(await tips(page, 'a'), {}); + await page.close(); + }); + + test('an arrow key after a long-pressed word shows no insertion handle from an earlier tap', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await tap(page, 'a', await pointAt(page, 'a', 0, 3)); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + await page.waitForTimeout(4300); + await page.keyboard.press('ArrowRight'); + await settle(page); + assert.deepEqual(await page.evaluate(() => window.views.a.core.selection), { + anchor: 10, + head: 10, + }); assert.deepEqual(await tips(page, 'a'), {}); await page.close(); }); From 8206a29e70c05a4877aed8b7479597f4c524518e Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 14:12:09 +0100 Subject: [PATCH 11/14] docs(web): correct the menu close hook and focusOnUp comments --- src/web/EditMenu.ts | 2 +- src/web/input/PointerHost.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/web/EditMenu.ts b/src/web/EditMenu.ts index 5319da3..a609661 100644 --- a/src/web/EditMenu.ts +++ b/src/web/EditMenu.ts @@ -8,7 +8,7 @@ export type MenuActions = { copy(): void; paste(): void; selectAll(): void; - // Runs whatever closed the menu: an item, the editor, or another editor's menu opening. + // Runs whenever the menu closes, whatever closed it: an item, the editor, or another editor's menu. hidden(): void; }; diff --git a/src/web/input/PointerHost.ts b/src/web/input/PointerHost.ts index b4ea472..6b8cd38 100644 --- a/src/web/input/PointerHost.ts +++ b/src/web/input/PointerHost.ts @@ -43,7 +43,7 @@ export class PointerHost { // 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. + // Set by a tap, a long press or a handle press, so the release focuses inside a user gesture and the keyboard opens. private focusOnUp = false; private longPressTimer: ReturnType | undefined; private readonly gestures: GestureMachine; From 127287d50bb4a3df8d9947c16b0303b36e9c3cdc Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 18:25:55 +0100 Subject: [PATCH 12/14] fix(web): scroll the page's own scrolling element with scrolling off With scrollEnabled false inside a scrolling element, as a ScrollView renders on the web, a mouse drag held below the fold scrolled nothing and scrollToLine left the line out of view: both wrote window.scrollTo, and the window does not scroll in that layout. The editor now scrolls its nearest scrolling ancestor and falls back to the window, and the drag's fold is that element's bottom edge. The edit menu also hides once its selection scrolls out of that element, where it stayed pinned to the element's top. --- src/web/EditorView.ts | 75 +++++++++++++++++++++++++++++-------- tests/web/render.e2e.mjs | 81 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 15 deletions(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 7429b0b..3a5d647 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -538,11 +538,19 @@ export class EditorView { const r = this.scroller.getBoundingClientRect(); const left = this.o.lineNumbers ? this.gutter.getBoundingClientRect().right : r.left; const page = document.documentElement; + let top = Math.max(r.top, 0); + let bottom = Math.min(r.top + this.scroller.clientHeight, page.clientHeight); + const host = this.o.scrollEnabled ? null : this.pageScroller(); + if (host) { + const h = host.getBoundingClientRect().top + host.clientTop; + top = Math.max(top, h); + bottom = Math.min(bottom, h + host.clientHeight); + } return { left: Math.max(left, 0), - top: Math.max(r.top, 0), + top, right: Math.min(r.left + this.scroller.clientWidth, page.clientWidth), - bottom: Math.min(r.top + this.scroller.clientHeight, page.clientHeight), + bottom, }; } @@ -662,19 +670,29 @@ export class EditorView { } if (out && handles) out.height += HANDLE_HEIGHT; // A selection that runs past both edges of the view keeps its menu, clamped to the view as Android does. - if (!out && from < to) { - const { first, last } = this.visibleLines(); - if (from <= this.core.lineEnd(last) && to >= this.core.lineStart(first)) - out = { - x: view.left, - y: view.top, - width: view.right - view.left, - height: view.bottom - view.top, - }; - } + if (!out && from < to && this.selectionInView(from, to, view)) + out = { + x: view.left, + y: view.top, + width: view.right - view.left, + height: view.bottom - view.top, + }; return out; } + // Whether a drawn line of the range meets the view, which a scrolling element around the editor can clip. + private selectionInView(from: number, to: number, view: Box): boolean { + const { first, last } = this.visibleLines(); + const end = Math.min(last, this.core.lineAt(to)); + for (let line = Math.max(first, this.core.lineAt(from)); line <= end; line++) { + const el = this.attached.has(line) ? this.cache.get(line)?.el : undefined; + if (!el) continue; + const r = el.getBoundingClientRect(); + if (r.bottom > view.top && r.top < view.bottom) return true; + } + return false; + } + // The editor's box where it meets the visual viewport, which the keyboard can shrink and pan. private menuArea(rootBox: DOMRect): Rect { const vv = typeof visualViewport === 'undefined' ? null : visualViewport; @@ -1119,15 +1137,42 @@ export class EditorView { private lineTarget(line: number): number { const top = this.layout.insetTop + this.layout.rowStart(line) * this.rowHeight; if (this.o.scrollEnabled) return Math.min(top - this.layout.insetTop, this.layout.maxScrollY); - return this.root.getBoundingClientRect().top + window.scrollY + top; + const host = this.pageScroller(); + const viewTop = host ? host.getBoundingClientRect().top + host.clientTop : 0; + return ( + this.root.getBoundingClientRect().top - viewTop + (host?.scrollTop ?? window.scrollY) + top + ); + } + + // What scrolls the editor with scrolling off: its nearest scrolling ancestor, as a ScrollView on the web, or null for the window. + private pageScroller(): HTMLElement | null { + const page = document.scrollingElement; + for ( + let el = this.root.parentElement; + el && el !== document.body && el !== page; + el = el.parentElement + ) { + if ( + el.scrollHeight > el.clientHeight && + /auto|scroll|overlay/.test(getComputedStyle(el).overflowY) + ) + return el; + } + return null; } private scrollNow(): number { - return this.o.scrollEnabled ? this.scroller.scrollTop : window.scrollY; + if (this.o.scrollEnabled) return this.scroller.scrollTop; + return this.pageScroller()?.scrollTop ?? window.scrollY; } private scrollTo(y: number): void { - if (this.o.scrollEnabled) this.scroller.scrollTop = y; + if (this.o.scrollEnabled) { + this.scroller.scrollTop = y; + return; + } + const host = this.pageScroller(); + if (host) host.scrollTop = y; else window.scrollTo({ top: y }); } diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index a0c4a32..eedc0fb 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -574,6 +574,87 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + // A 400 px element under a 60 px header that scrolls host d while the window stays still, as a ScrollView on the web. + const scrollingHost = (page) => + page.evaluate(() => { + const host = document.createElement('div'); + host.id = 'sv'; + host.style.cssText = + 'position:fixed;left:0;top:60px;width:600px;height:400px;overflow-y:auto;border:6px solid gray;'; + host.innerHTML = + '
'; + document.body.append(host); + }); + // The host's content box in page coordinates, inside its border. + const hostBox = (page) => + page.evaluate(() => { + const sv = document.getElementById('sv'); + const top = sv.getBoundingClientRect().top + sv.clientTop; + return { top, bottom: top + sv.clientHeight }; + }); + + test('with scrollEnabled false inside a scrolling element a drag below its bottom scrolls that element', async () => { + const { page, errors } = await open(); + await scrollingHost(page); + await editor(page, 'd', lines(300), { scrollEnabled: false }); + const from = await pointAt(page, 'd', 0, 1); + const box = await hostBox(page); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x, box.bottom + 20, { steps: 4 }); + await page.waitForFunction(() => document.getElementById('sv').scrollTop > 200); + const out = await page.evaluate((bottom) => { + const v = window.views.d; + const fold = [...document.querySelectorAll('#d [data-line]')].find((el) => { + const r = el.getBoundingClientRect(); + return r.top <= bottom - 1 && r.bottom > bottom - 1; + }); + const { anchor, head } = v.core.selection; + return { anchor, line: v.core.lineAt(head), fold: Number(fold?.dataset.line), y: scrollY }; + }, box.bottom); + await page.mouse.up(); + assert.equal(out.anchor, 1); + assert.ok(Math.abs(out.line - out.fold) <= 2, JSON.stringify(out)); + assert.equal(out.y, 0); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('with scrollEnabled false inside a scrolling element scrollToLine puts the line at its top', async () => { + const { page } = await open(); + await scrollingHost(page); + await editor(page, 'd', lines(300), { scrollEnabled: false }); + const out = await page.evaluate(async () => { + window.views.d.scrollToLine(150); + await window.codepad.frames(3); + const line = document.querySelector('#d [data-line="150"]'); + return { lineTop: line ? line.getBoundingClientRect().top : null, y: scrollY }; + }); + const box = await hostBox(page); + assert.ok(out.lineTop !== null && Math.abs(out.lineTop - box.top) <= 1, JSON.stringify(out)); + assert.equal(out.y, 0); + await page.close(); + }); + + test('with scrollEnabled false the menu hides once its selection scrolls out of the scrolling element', async () => { + const { page } = await open(); + await scrollingHost(page); + await editor(page, 'd', lines(300), { scrollEnabled: false }); + await longPress(page, 'd', await pointAt(page, 'd', 0, 1)); + assert.notEqual(await menuOf(page), null); + // Line 0 goes under the 60 px header, out of the host but still inside the window. + const shown = await page.evaluate(async () => { + const sv = document.getElementById('sv'); + const line = document.querySelector('#d [data-line="0"]'); + sv.scrollTop += line.getBoundingClientRect().top - 20; + await window.codepad.frames(3); + const menu = document.querySelector('[data-codepad-menu]'); + return menu !== null && getComputedStyle(menu).display !== 'none'; + }); + assert.equal(shown, false); + await page.close(); + }); + test('a touch tap still places the caret and focuses', async () => { const { page } = await open(); await editor(page, 'a', 'abcdef\nghijkl'); From 605fb4b34f5f59f6f9ab254ee2fd185413e602a2 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 18:32:26 +0100 Subject: [PATCH 13/14] fix(web): keep the textarea above the keyboard under avoidKeyboard After Select all with the keyboard up, a tap inside the selection slid the page up 312 px on Chrome Android. The hidden textarea sat at the selection end under the keyboard, and Chrome scrolls the page to a focused field after every tap. Under avoidKeyboard the editor already keeps the caret clear of the keyboard, so the textarea now stays above it too. --- src/web/EditorView.ts | 14 ++++++++-- src/web/input/keyboardInset.ts | 7 +++++ tests/web/render.e2e.mjs | 50 ++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 3a5d647..492a955 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -27,7 +27,7 @@ import { HANDLE_HEIGHT, 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 { overlapOf, visibleBottomIn, watchViewport } from './input/keyboardInset'; import { keyCommand } from './input/keys'; import { type Box, PointerHost } from './input/PointerHost'; import { lineUnit } from './input/units'; @@ -210,6 +210,8 @@ export class EditorView { private offViewport: () => void = () => {}; // The keyboard's overlap with the editor, part of the bottom inset under avoidKeyboard. private keyboard = 0; + // The lowest textarea top in view coordinates that the keyboard leaves visible, read with the overlap. + private inputLimit = 0; // Injection names the engine found no language for, and the ids this view already refreshed after. private readonly missed = new Set(); private readonly refreshedFor = new Set(); @@ -693,6 +695,11 @@ export class EditorView { return false; } + // The textarea at the caret, kept above the keyboard under avoidKeyboard so the browser's scroll to a focused field never moves the page. + private placeInput(x: number, y: number): void { + this.input.place(x, this.keyboard > 0 ? Math.max(0, Math.min(y, this.inputLimit)) : y); + } + // The editor's box where it meets the visual viewport, which the keyboard can shrink and pan. private menuArea(rootBox: DOMRect): Rect { const vv = typeof visualViewport === 'undefined' ? null : visualViewport; @@ -1008,7 +1015,7 @@ export class EditorView { put(this.caretEl, 'top', `${caret.y + rootBox.top - box.top}px`); put(this.caretEl, 'height', `${caret.height}px`); put(this.caretEl, 'background', this.css.cursor); - this.input.place(caret.x, caret.y); + this.placeInput(caret.x, caret.y); } else { put(this.caretEl, 'display', 'none'); } @@ -1639,7 +1646,7 @@ export class EditorView { // Lines and the caret scroll with the content: only the textarea, placed in view coordinates, follows. const x = caret.x - (this.layout.scrollX - beforeX); this.drawnCaret = { ...caret, x }; - if (this.input.focused) this.input.place(x, caret.y); + if (this.input.focused) this.placeInput(x, caret.y); break; } moved = this.frame(); @@ -1810,6 +1817,7 @@ export class EditorView { const keyboard = o.avoidKeyboard && o.scrollEnabled ? overlapOf(this.root) : 0; if (keyboard > this.keyboard && this.input.focused) this.revealing = true; this.keyboard = keyboard; + if (keyboard > 0) this.inputLimit = visibleBottomIn(this.root) - this.rowHeight; const bottom = (insets.bottom ?? 0) + keyboard; this.layout.setInsets(insets.top ?? 0, bottom, insets.left ?? 0, insets.right ?? 0); const placedAt = `${this.layout.textAreaLeft}:${this.layout.insetTop}`; diff --git a/src/web/input/keyboardInset.ts b/src/web/input/keyboardInset.ts index 805df8a..14d2a65 100644 --- a/src/web/input/keyboardInset.ts +++ b/src/web/input/keyboardInset.ts @@ -19,6 +19,13 @@ export function overlapOf(el: HTMLElement): number { return Math.round(keyboardOverlap(bottom, vv.offsetTop, vv.height, layout)); } +// The visual viewport's bottom in an element's own coordinates: the lowest point the keyboard leaves uncovered. +export function visibleBottomIn(el: HTMLElement): number { + const vv = typeof window === 'undefined' ? undefined : window.visualViewport; + const bottom = vv ? vv.offsetTop + vv.height : document.documentElement.clientHeight; + return bottom - el.getBoundingClientRect().top; +} + // Calls back when the visual viewport moves or resizes, as the keyboard opens, closes or animates. Returns the removal. export function watchViewport(changed: () => void): () => void { const vv = typeof window === 'undefined' ? undefined : window.visualViewport; diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index eedc0fb..34be7f6 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -655,6 +655,56 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('under avoidKeyboard the textarea stays above the keyboard when the selection ends under it', async () => { + const { page } = await open(); + await editor(page, 'a', lines(14), { avoidKeyboard: true }); + const bottom = await page.evaluate(async () => { + const v = window.views.a; + v.focus(); + // A keyboard over all of the page but its top 100 px. + Object.defineProperty(window.visualViewport, 'height', { + configurable: true, + get: () => 100, + }); + window.visualViewport.dispatchEvent(new Event('resize')); + await window.codepad.frames(3); + v.apply(() => v.core.setSelection(0, v.core.text().length)); + await window.codepad.frames(3); + return document.querySelector('#a textarea').getBoundingClientRect().bottom; + }); + // Chrome Android scrolls the page to a focused field after every tap, so one under the keyboard moved the page. + assert.ok(bottom <= 100, `textarea bottom at ${bottom}`); + await page.close(); + }); + + test('under avoidKeyboard the textarea stays above the keyboard when the editor runs past the window', async () => { + const { page } = await open(); + await page.evaluate(() => { + Object.assign(document.getElementById('a').style, { + position: 'absolute', + top: '56px', + height: '900px', + }); + }); + await editor(page, 'a', lines(60), { avoidKeyboard: true }); + const bottom = await page.evaluate(async () => { + const v = window.views.a; + v.focus(); + Object.defineProperty(window.visualViewport, 'height', { + configurable: true, + get: () => 300, + }); + window.visualViewport.dispatchEvent(new Event('resize')); + await window.codepad.frames(3); + // Line 20 is drawn above what the editor's inset keeps clear, and under the keyboard. + v.apply(() => v.core.setSelection(0, v.core.lineEnd(20))); + await window.codepad.frames(3); + return document.querySelector('#a textarea').getBoundingClientRect().bottom; + }); + assert.ok(bottom <= 300, `textarea bottom at ${bottom}`); + await page.close(); + }); + test('a touch tap still places the caret and focuses', async () => { const { page } = await open(); await editor(page, 'a', 'abcdef\nghijkl'); From 7fb0dd68b4199cb6fb56cdc9d08b9f6e62294b6b Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 21:18:09 +0100 Subject: [PATCH 14/14] fix(web): fade the insertion handle with its menu open, as Android does The insertion handle stayed for as long as its Paste menu was open, while Android hides it 4 s after the last touch and leaves the menu where it is. It was kept because the menu's anchor counted the handle only while drawn, so a menu under the caret jumped up 44 px when it faded. The anchor now keeps room for the handles whether drawn or faded, a finger held on the handle keeps it, and lifting the finger starts its 4 s again. --- src/web/EditMenu.ts | 6 +----- src/web/EditorView.ts | 27 +++++++++++++++------------ tests/web/render.e2e.mjs | 28 ++++++++++++---------------- 3 files changed, 28 insertions(+), 33 deletions(-) diff --git a/src/web/EditMenu.ts b/src/web/EditMenu.ts index a609661..5363297 100644 --- a/src/web/EditMenu.ts +++ b/src/web/EditMenu.ts @@ -8,8 +8,6 @@ export type MenuActions = { copy(): void; paste(): void; selectAll(): void; - // Runs whenever the menu closes, whatever closed it: an item, the editor, or another editor's menu. - hidden(): void; }; export type MenuTheme = { background: string; foreground: string; border: string }; @@ -31,7 +29,7 @@ export class EditMenu { private size = { width: 0, height: 0 }; private themed = ''; - constructor(private readonly actions: MenuActions) { + constructor(actions: MenuActions) { this.items = [ { label: 'Cut', enabled: () => actions.canCut(), run: () => actions.cut(), keepsMenu: false }, { @@ -77,11 +75,9 @@ export class EditMenu { } hide(): void { - const was = this.isShown; this.isShown = false; if (active === this) active = null; this.el.style.display = 'none'; - if (was) this.actions.hidden(); } // Places the menu above the anchor, or below when the visible area has no room above. Both in page coordinates. diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 492a955..cec97f2 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -370,6 +370,7 @@ export class EditorView { endHandleDrag: () => { this.handleDrag = null; this.handles.dragging = false; + if (this.insertionShown) this.fadeInsertionLater(); this.showMenu(); }, showMenu: (at) => this.showMenu(at), @@ -390,10 +391,6 @@ export class EditorView { }, paste: () => this.clipboardFailed(this.pasteClipboard()), selectAll: () => this.apply(() => this.core.selectAll()), - hidden: () => { - this.menuAt = null; - if (this.insertionShown) this.fadeInsertionLater(); - }, }); this.handles = new Handles(this.textLayer); // The browser keeps panning and pinch zoom, the editor takes taps and long presses. @@ -597,12 +594,10 @@ export class EditorView { this.invalidate(); } - // The handle fades 4 s on, but not while its menu is open: the menu stands under it and would jump up. + // The handle fades 4 s after the last touch on it, menu open or not, as Android does. private fadeInsertionLater(): void { clearTimeout(this.insertionTimer); - this.insertionTimer = setTimeout(() => { - if (!this.menu.shown) this.hideInsertion(); - }, INSERTION_HANDLE_MS); + this.insertionTimer = setTimeout(() => this.hideInsertion(), INSERTION_HANDLE_MS); } private hideInsertion(): void { @@ -616,6 +611,8 @@ export class EditorView { private handleAt(x: number, y: number): HandleKind | null { const kind = this.handles.hit(x, y); if (!kind) return null; + // A handle under a finger never fades. Its 4 s start again when the drag ends. + if (kind === 'insertion') clearTimeout(this.insertionTimer); 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 }; @@ -648,7 +645,7 @@ export class EditorView { this.menu.hide(); } - // The menu's anchor in page coordinates: a right click's pointer, else the ends in view and, as Android, the handles under them. + // The menu's anchor in page coordinates: a right click's pointer, else the ends in view and, as Android, room for their handles even once faded. private menuAnchor(from: number, to: number, rootBox: DOMRect, handles: boolean): Rect | null { if (this.menuAt) return { ...this.menuAt, width: 0, height: 0 }; const view = this.visibleBox(); @@ -715,9 +712,14 @@ export class EditorView { action.catch((e) => console.warn('[codepad]', e)); } + // Whether the ends take handles, drawn or faded: after a touch, while the editor has the focus or the finger. + private touchHandles(): boolean { + return this.touchMode && (this.input.focused || this.pointer.holdsTouch); + } + // 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 (!this.touchHandles()) return {}; if (from === to && !this.insertionShown) return {}; const view = this.visibleBox(); const at = (offset: number): Rect | undefined => { @@ -995,8 +997,9 @@ export class EditorView { const writeMatches = this.planMatches(rootBox, from, to); const writeBrackets = this.planBrackets(); const ends = this.handleEnds(from, to, rootBox, box); - const shownHandles = Object.values(ends).some(Boolean); - const menuAnchor = this.menu.shown ? this.menuAnchor(from, to, rootBox, shownHandles) : null; + const menuAnchor = this.menu.shown + ? this.menuAnchor(from, to, rootBox, this.touchHandles()) + : null; const menuArea = this.menu.shown ? this.menuArea(rootBox) : null; const layout = this.layout; const handleArea = { diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 34be7f6..95ec85d 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -1018,25 +1018,26 @@ for (const engine of [chromium, webkit]) { await page.close(); }); - test('the insertion handle stays while its menu is open, so the menu stays put', async () => { + test('the insertion handle fades 4 s after a touch on it, with its menu open and in place', async () => { const { page } = await open(); await editor(page, 'a', 'alpha beta gamma'); await tap(page, 'a', await pointAt(page, 'a', 0, 3)); + await page.waitForTimeout(3000); const tip = (await tips(page, 'a')).insertion; - await tap(page, 'a', { x: tip.x, y: tip.y + 10 }); - const before = (await menuOf(page))?.box; - await page.waitForTimeout(4200); + // A finger held still on the handle past its 4 s keeps it, and the release starts the 4 s again. + await touch(page, 'a', 'pointerdown', { x: tip.x, y: tip.y + 10 }); + await page.waitForTimeout(1500); + await touch(page, 'a', 'pointerup', { x: tip.x, y: tip.y + 10 }); await settle(page); assert.deepEqual(Object.keys(await tips(page, 'a')), ['insertion']); - assert.deepEqual((await menuOf(page))?.box, before); - // Once the menu closes, the handle fades 4 s later. An arrow key closes it and keeps the focus. - await page.keyboard.press('ArrowRight'); - await settle(page); - assert.equal(await menuOf(page), null); + const before = (await menuOf(page))?.box; + assert.ok(before); + await page.waitForTimeout(1500); assert.deepEqual(Object.keys(await tips(page, 'a')), ['insertion']); - await page.waitForTimeout(4200); + await page.waitForTimeout(3200); await settle(page); assert.deepEqual(await tips(page, 'a'), {}); + assert.deepEqual((await menuOf(page))?.box, before); await page.close(); }); @@ -1045,7 +1046,6 @@ for (const engine of [chromium, webkit]) { await editor(page, 'a', 'alpha beta gamma'); await tap(page, 'a', await pointAt(page, 'a', 0, 3)); await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); - await page.waitForTimeout(4300); await page.keyboard.press('ArrowRight'); await settle(page); assert.deepEqual(await page.evaluate(() => window.views.a.core.selection), { @@ -1056,7 +1056,7 @@ for (const engine of [chromium, webkit]) { await page.close(); }); - test('a refused Paste from the handle menu lets the insertion handle fade', async () => { + test('a refused Paste from the handle menu warns once and changes nothing', async () => { const { page, warnings } = await open(); await editor(page, 'a', 'alpha beta gamma'); await page.evaluate(() => @@ -1068,13 +1068,9 @@ for (const engine of [chromium, webkit]) { await tap(page, 'a', await pointAt(page, 'a', 0, 3)); const tip = (await tips(page, 'a')).insertion; await tap(page, 'a', { x: tip.x, y: tip.y + 10 }); - // The fade comes due while the menu is open, so only the menu closing can start it again. - await page.waitForTimeout(4200); await pressMenu(page, 'Paste'); - await page.waitForTimeout(4200); await settle(page); assert.equal(await menuOf(page), null); - assert.deepEqual(await tips(page, 'a'), {}); assert.equal(await page.evaluate(() => window.views.a.core.text()), 'alpha beta gamma'); assert.equal(warnings.length, 1); await page.close();