diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx index e56bb009..7e1ed952 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 7355d97e..21df8a7e 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: () => '' }; diff --git a/scripts/bench-web.mjs b/scripts/bench-web.mjs index 34d5e197..e48554cf 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)}`; diff --git a/src/web/EditMenu.ts b/src/web/EditMenu.ts index e2446305..53632974 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 7a505c97..cec97f22 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -14,14 +14,20 @@ 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'; 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'; @@ -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 }; @@ -182,13 +198,20 @@ 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; + // 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(); @@ -197,9 +220,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;'); @@ -213,16 +235,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 }; @@ -289,7 +309,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;'); @@ -299,7 +322,6 @@ export class EditorView { this.matchLayer, this.bracketLayer, this.selectionLayer, - this.underlineLayer, this.placeholderEl, this.composingLayer, this.caretEl, @@ -328,7 +350,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 +361,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(), @@ -348,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), @@ -410,7 +433,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); @@ -469,11 +492,13 @@ 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(); - // 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)); @@ -512,11 +537,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, }; } @@ -532,6 +565,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(); @@ -541,12 +589,17 @@ 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 after the last touch on it, menu open or not, as Android does. + private fadeInsertionLater(): void { + clearTimeout(this.insertionTimer); + this.insertionTimer = setTimeout(() => this.hideInsertion(), INSERTION_HANDLE_MS); + } + private hideInsertion(): void { clearTimeout(this.insertionTimer); if (!this.insertionShown) return; @@ -558,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 }; @@ -573,10 +628,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(); } @@ -587,12 +642,10 @@ export class EditorView { } private hideMenu(): void { - if (!this.menu.shown) return; this.menu.hide(); - this.menuAt = null; } - // 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(); @@ -615,9 +668,35 @@ 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 && 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 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; @@ -633,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 => { @@ -739,6 +823,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) { @@ -911,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 = { @@ -931,7 +1018,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'); } @@ -986,16 +1073,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; } @@ -1051,15 +1147,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 }); } @@ -1272,7 +1395,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; @@ -1288,30 +1411,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; @@ -1330,18 +1438,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; @@ -1356,8 +1463,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. @@ -1475,61 +1591,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; @@ -1588,7 +1649,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(); @@ -1694,11 +1755,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 { @@ -1728,6 +1789,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(); @@ -1758,6 +1820,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}`; @@ -1868,15 +1931,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; @@ -1886,10 +1956,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); @@ -2022,35 +2092,50 @@ 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. 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; @@ -2064,10 +2149,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); @@ -2076,13 +2173,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) { @@ -2165,6 +2286,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 1b31447b..a0dfd52c 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 2065e858..c318f9f2 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/src/web/input/PointerHost.ts b/src/web/input/PointerHost.ts index cccc5df2..6b8cd386 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; @@ -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/src/web/input/keyboardInset.ts b/src/web/input/keyboardInset.ts index 805df8a6..14d2a650 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/harness/index.html b/tests/web/harness/index.html index 3f53a426..9bb89ecb 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 9cc89a7e..95ec85dd 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -574,6 +574,137 @@ 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('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'); @@ -658,6 +789,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'); @@ -870,6 +1018,64 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + 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; + // 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']); + 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(3200); + await settle(page); + assert.deepEqual(await tips(page, 'a'), {}); + assert.deepEqual((await menuOf(page))?.box, before); + 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.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(); + }); + + 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(() => + 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 }); + await pressMenu(page, 'Paste'); + await settle(page); + assert.equal(await menuOf(page), null); + 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 }); @@ -1099,6 +1305,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'); @@ -1303,7 +1608,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]) => { @@ -1331,22 +1650,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(() => @@ -1355,23 +1682,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(wave.right - wave.left - width) <= 1, - `${wave.right - wave.left} for ${width}`, + 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(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(); }); @@ -1398,6 +1763,144 @@ 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 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'); + 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'); @@ -1751,7 +2254,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); @@ -1808,7 +2311,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; @@ -1876,7 +2379,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(); });