From f10a36448758cc45dcbc1be839d3b60a7cc82d01 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Wed, 18 Nov 2026 19:18:48 +0100 Subject: [PATCH] feat(web): the edit menu with Cut, Copy, Paste and Select all On the web a selection could only reach the clipboard through keyboard shortcuts, so a phone had no way to copy or cut. A long press, a tap inside the selection or on the insertion handle, a handle release and a right click now open a menu in the theme's colors. Copy and Cut run the browser's own command, so the whole selection reaches the clipboard even though the textarea holds a window of the text, and a menu that opens under the selection sits below the handles, as on Android. --- src/web/EditMenu.ts | 143 ++++++++++++++++++++++ src/web/EditorView.ts | 107 ++++++++++++++++- src/web/Handles.ts | 5 +- src/web/input/InputHost.ts | 10 ++ src/web/input/PointerHost.ts | 26 +++- tests/web/render.e2e.mjs | 225 +++++++++++++++++++++++++++++++++++ 6 files changed, 503 insertions(+), 13 deletions(-) create mode 100644 src/web/EditMenu.ts diff --git a/src/web/EditMenu.ts b/src/web/EditMenu.ts new file mode 100644 index 0000000..e244630 --- /dev/null +++ b/src/web/EditMenu.ts @@ -0,0 +1,143 @@ +import type { Rect } from '../types'; + +export type MenuActions = { + canCut(): boolean; + canCopy(): boolean; + canPaste(): boolean; + cut(): void; + copy(): void; + paste(): void; + selectAll(): void; +}; + +export type MenuTheme = { background: string; foreground: string; border: string }; + +type Item = { label: string; enabled(): boolean; run(): void; keepsMenu: boolean }; + +// The space between the menu and what it points at. +const GAP = 8; + +// One menu shows on the page at a time. +let active: EditMenu | null = null; + +// The floating Cut, Copy, Paste and Select all bar, fixed on the page so it can leave the editor's box. +export class EditMenu { + private readonly el = document.createElement('div'); + private readonly items: Item[]; + private isShown = false; + private labels = ''; + private size = { width: 0, height: 0 }; + private themed = ''; + + constructor(actions: MenuActions) { + this.items = [ + { label: 'Cut', enabled: () => actions.canCut(), run: () => actions.cut(), keepsMenu: false }, + { + label: 'Copy', + enabled: () => actions.canCopy(), + run: () => actions.copy(), + keepsMenu: false, + }, + { + label: 'Paste', + enabled: () => actions.canPaste(), + run: () => actions.paste(), + keepsMenu: false, + }, + { label: 'Select all', enabled: () => true, run: () => actions.selectAll(), keepsMenu: true }, + ]; + this.el.dataset.codepadMenu = ''; + this.el.style.cssText = + 'position:fixed;left:0;top:0;display:none;z-index:2147483647;border-radius:8px;overflow:hidden;' + + 'box-shadow:0 2px 8px rgba(0,0,0,0.25);font:14px system-ui;user-select:none;-webkit-user-select:none;' + + '-webkit-touch-callout:none;white-space:nowrap;'; + // The textarea keeps the focus, so Copy and Cut act on the editor's selection. + for (const type of ['pointerdown', 'mousedown']) + this.el.addEventListener(type, (e) => e.preventDefault()); + this.el.addEventListener('click', (e) => { + const button = (e.target as Element).closest('button'); + const item = this.items.find((i) => i.label === button?.textContent); + if (!item) return; + if (!item.keepsMenu) this.hide(); + item.run(); + }); + document.body.append(this.el); + } + + get shown(): boolean { + return this.isShown; + } + + show(): void { + if (active && active !== this) active.hide(); + active = this; + this.isShown = true; + } + + hide(): void { + this.isShown = false; + if (active === this) active = null; + this.el.style.display = 'none'; + } + + // Places the menu above the anchor, or below when the visible area has no room above. Both in page coordinates. + place(anchor: Rect | null, visible: Rect, theme: MenuTheme): void { + const out = + !anchor || + anchor.y + anchor.height < visible.y || + anchor.y > visible.y + visible.height || + anchor.x + anchor.width < visible.x || + anchor.x > visible.x + visible.width; + if (!this.isShown || out) { + this.el.style.display = 'none'; + return; + } + this.theme(theme); + this.build(); + const { width, height } = this.size; + let top = anchor.y - GAP - height; + if (top < visible.y) top = anchor.y + anchor.height + GAP; + const centre = anchor.x + anchor.width / 2; + const left = Math.max( + visible.x, + Math.min(centre - width / 2, visible.x + visible.width - width), + ); + this.el.style.left = `${Math.round(left)}px`; + this.el.style.top = `${Math.round(top)}px`; + } + + destroy(): void { + this.hide(); + this.el.remove(); + } + + // The buttons of the actions that apply now, measured again only when that set changes. + private build(): void { + const items = this.items.filter((i) => i.enabled()); + const labels = items.map((i) => i.label).join('\n'); + this.el.style.display = 'flex'; + if (labels === this.labels) return; + this.labels = labels; + this.el.replaceChildren( + ...items.map((item) => { + const button = document.createElement('button'); + button.type = 'button'; + button.textContent = item.label; + button.style.cssText = + 'height:44px;padding:0 16px;border:0;margin:0;background:transparent;color:inherit;font:inherit;cursor:pointer;'; + return button; + }), + ); + this.size = { width: this.el.offsetWidth, height: this.el.offsetHeight }; + } + + private theme(t: MenuTheme): void { + const key = `${t.background} ${t.foreground} ${t.border}`; + if (key === this.themed) return; + this.themed = key; + this.el.style.background = t.background; + this.el.style.color = t.foreground; + this.el.style.border = `1px solid ${t.border}`; + this.labels = ''; + } +} diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 26f2398..3dc28e7 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -15,8 +15,9 @@ 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 { EditMenu } from './EditMenu'; import { type DecodedFrame, decodeFrame } from './frame'; -import { type HandleEnds, Handles } from './Handles'; +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'; @@ -256,6 +257,9 @@ export class EditorView { }; private readonly pointer: PointerHost; private readonly handles: Handles; + private readonly menu: EditMenu; + // Where a right click opened the menu, which then stays at the pointer. + private menuAt: { x: number; y: number } | null = null; // True while the last pointer down on the editor was touch or pen: only then do handles show. private touchMode = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches; private insertionShown = false; @@ -271,7 +275,7 @@ export class EditorView { const beside = target === s && e.clientX < r.left + s.clientWidth && e.clientY < r.top + s.clientHeight; const inside = this.textLayer.contains(target) || this.gutter.contains(target) || beside; - if (e.button !== 0 || !inside) return; + if ((e.button !== 0 && e.button !== 2) || !inside) return; e.preventDefault(); this.pointer.press(e); }; @@ -310,6 +314,8 @@ export class EditorView { keyDown: (e) => this.keyDown(e), clipboard: (cut) => this.clipboard(cut), focusChanged: (focused) => { + // Chrome blurs the textarea during a long press, and the release focuses it again. + if (!focused && !this.pointer.holdsTouch) this.hideMenu(); this.safely(() => (focused ? this.o.onFocus?.() : this.o.onBlur?.())); this.invalidate(); }, @@ -342,8 +348,26 @@ export class EditorView { endHandleDrag: () => { this.handleDrag = null; this.handles.dragging = false; - this.invalidate(); + this.showMenu(); + }, + showMenu: (at) => this.showMenu(at), + hideMenu: () => this.hideMenu(), + }); + this.menu = new EditMenu({ + canCut: () => !this.o.readOnly && this.selectedText() !== '', + canCopy: () => this.selectedText() !== '', + canPaste: () => + !this.o.readOnly && + typeof navigator !== 'undefined' && + typeof navigator.clipboard?.readText === 'function', + cut: () => { + if (!this.input.execute('cut')) this.clipboardFailed(this.cutSelection()); + }, + copy: () => { + if (!this.input.execute('copy')) this.clipboardFailed(this.copySelection()); }, + paste: () => this.clipboardFailed(this.pasteClipboard()), + selectAll: () => this.apply(() => this.core.selectAll()), }); this.handles = new Handles(this.textLayer); // The browser keeps panning and pinch zoom, the editor takes taps and long presses. @@ -436,7 +460,10 @@ export class EditorView { if (outside) this.session.external(); edit(); const changes = this.core.takeChanges(); - if (changes.length) this.hideInsertion(); + if (changes.length) { + this.hideInsertion(); + this.hideMenu(); + } for (const change of changes) { this.search.onChange(change); this.changed(change, changes.length); @@ -534,6 +561,7 @@ export class EditorView { const { anchor, head } = this.core.selection; const fixed = kind === 'start' ? Math.max(anchor, head) : Math.min(anchor, head); this.handleDrag = { dy: y - this.handles.top(kind), fixed }; + this.hideMenu(); this.handles.dragging = true; return kind; } @@ -552,6 +580,59 @@ export class EditorView { this.showInsertion(); } + private showMenu(at?: { x: number; y: number }): void { + this.menuAt = at ?? null; + this.menu.show(); + this.invalidate(); + } + + 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. + 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(); + let out: Rect | null = null; + for (const offset of from === to ? [from] : [from, to]) { + const r = this.caretRect(offset, rootBox); + if (!r) continue; + const x = r.x + rootBox.left; + const y = r.y + rootBox.top; + if (y + r.height <= view.top || y >= view.bottom || x < view.left - 1 || x > view.right + 1) + continue; + if (!out) { + out = { x, y, width: 1, height: r.height }; + continue; + } + const left = Math.min(out.x, x); + const top = Math.min(out.y, y); + const right = Math.max(out.x + out.width, x + 1); + const bottom = Math.max(out.y + out.height, y + r.height); + out = { x: left, y: top, width: right - left, height: bottom - top }; + } + if (out && handles) out.height += HANDLE_HEIGHT; + return out; + } + + // 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; + const top = Math.max(rootBox.top, vv ? vv.offsetTop : 0); + const bottom = Math.min(rootBox.bottom, vv ? vv.offsetTop + vv.height : innerHeight); + const left = Math.max(rootBox.left, vv ? vv.offsetLeft : 0); + const right = Math.min(rootBox.right, vv ? vv.offsetLeft + vv.width : innerWidth); + return { x: left, y: top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) }; + } + + // A menu action the clipboard refused, reported without failing the page. + private clipboardFailed(action: Promise): void { + action.catch((e) => console.warn('[codepad]', e)); + } + // 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 {}; @@ -684,6 +765,7 @@ export class EditorView { // Runs an edit or a move from a key or the ref, then shows the caret. private perform(edit: () => void): void { + this.hideMenu(); this.revealing = true; this.apply(edit); } @@ -829,6 +911,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 menuArea = this.menu.shown ? this.menuArea(rootBox) : null; const layout = this.layout; const handleArea = { width: Math.max( @@ -874,6 +959,15 @@ export class EditorView { writeMatches(); writeBrackets(); this.handles.place(ends, this.css.cursor, handleArea); + if (menuArea) { + const css = this.css; + const theme = { + background: css.background, + foreground: css.foreground, + border: css.gutterForeground, + }; + this.menu.place(menuAnchor, menuArea, theme); + } } // The page boxes of the document range on the lines that are drawn. @@ -1316,8 +1410,8 @@ export class EditorView { } } } - // A clipped long line follows the window, so a page scroll draws again. - this.listenToPage(!this.o.scrollEnabled || clipped); + // A clipped long line and the menu follow the window, so a page scroll draws again. + this.listenToPage(!this.o.scrollEnabled || clipped || this.menu.shown); const css = this.css; const wanted = new Map(); for (const [line, list] of parts) { @@ -1527,6 +1621,7 @@ export class EditorView { this.offRegistered(); this.input.destroy(); this.pointer.destroy(); + this.menu.destroy(); this.scroller.removeEventListener('mousedown', this.onMouseDownEvent); this.listenToPage(false); this.offViewport(); diff --git a/src/web/Handles.ts b/src/web/Handles.ts index 95990de..67e8161 100644 --- a/src/web/Handles.ts +++ b/src/web/Handles.ts @@ -4,8 +4,9 @@ import type { HandleKind } from './input/GestureMachine'; export type HandleEnds = { insertion?: Rect; start?: Rect; end?: Rect }; const SIZE = 22; -// A finger-sized hit area under the row, centered on the shape. -const HIT = 44; +// A finger-sized hit area under the row, centered on the shape, and how far handles reach below it. +export const HANDLE_HEIGHT = 44; +const HIT = HANDLE_HEIGHT; // Where each shape's tip sits along its width. const TIP: Record = { insertion: 0.5, start: 1, end: 0 }; const SHAPES: Record = { diff --git a/src/web/input/InputHost.ts b/src/web/input/InputHost.ts index 83cefa6..3f62c17 100644 --- a/src/web/input/InputHost.ts +++ b/src/web/input/InputHost.ts @@ -151,6 +151,16 @@ export class InputHost { this.textarea.remove(); } + // Runs the browser's copy or cut on the textarea, whose events put the editor's selection on the clipboard. False when the browser refuses. + execute(command: 'copy' | 'cut'): boolean { + if (!this.focused) this.focus(); + try { + return document.execCommand(command); + } catch { + return false; + } + } + // The textarea holds only a window, so the clipboard takes the editor's whole selection. private clip(e: ClipboardEvent, cut: boolean): void { const text = this.hooks.clipboard(cut); diff --git a/src/web/input/PointerHost.ts b/src/web/input/PointerHost.ts index 6b39167..cccc5df 100644 --- a/src/web/input/PointerHost.ts +++ b/src/web/input/PointerHost.ts @@ -27,7 +27,9 @@ export type PointerHooks = { handleAt(x: number, y: number): HandleKind | null; moveHandle(kind: HandleKind, x: number, y: number): void; endHandleDrag(): void; - showMenu?(): void; + // At a page point for a right click, else at the selection. + showMenu(at?: { x: number; y: number }): void; + hideMenu(): void; }; type Drag = { unit: 'char' | 'word' | 'line'; anchor: Span; x: number; y: number }; @@ -61,6 +63,7 @@ export class PointerHost { ); }, placeCaret: (offset) => { + hooks.hideMenu(); hooks.select(offset, offset); hooks.showInsertion(); this.focusOnUp = true; @@ -76,7 +79,7 @@ export class PointerHost { }, moveHandle: (kind, x, y) => hooks.moveHandle(kind, x, y), endHandleDrag: () => hooks.endHandleDrag(), - showMenu: () => hooks.showMenu?.(), + showMenu: () => hooks.showMenu(), postLongPress: (ms) => { clearTimeout(this.longPressTimer); this.longPressTimer = setTimeout(() => this.gestures.longPress(), ms); @@ -105,6 +108,7 @@ export class PointerHost { press(e: MouseEvent): void { if ((this.pointerType && this.pointerType !== 'mouse') || e.button !== 0) return; if (this.drag) this.end(); + this.hooks.hideMenu(); if (this.hooks.inGap(e.clientY)) return; const offset = this.hooks.offsetAt(e.clientX, e.clientY, false); if (offset === null) { @@ -209,9 +213,21 @@ export class PointerHost { if (e.target === this.scroller) this.cancel(e); }; - // Chrome opens its own menu and selection about 500 ms into a long press. - private readonly contextMenu = (e: Event) => { - if (this.pointerType !== 'mouse') e.preventDefault(); + // Chrome opens its own menu and selection about 500 ms into a long press. A right click opens ours at the pointer. + private readonly contextMenu = (e: MouseEvent) => { + if (this.pointerType !== 'mouse') { + e.preventDefault(); + return; + } + if (this.hooks.inGap(e.clientY)) return; + e.preventDefault(); + const offset = this.hooks.offsetAt(e.clientX, e.clientY, false); + const { anchor, head } = this.hooks.selection(); + const outside = + offset !== null && (offset < Math.min(anchor, head) || offset > Math.max(anchor, head)); + if (outside) this.hooks.select(offset, offset); + this.hooks.focus(); + this.hooks.showMenu({ x: e.clientX, y: e.clientY }); }; private readonly touchMove = (e: TouchEvent) => { diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index e78c2e7..f3b483e 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -805,6 +805,231 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + // The edit menu that shows: its labels in order, its page box, and how many menus show. + const menuOf = (page) => + page.evaluate(() => { + const shown = [...document.querySelectorAll('[data-codepad-menu]')].filter( + (el) => getComputedStyle(el).display !== 'none', + ); + if (shown.length === 0) return null; + const r = shown[0].getBoundingClientRect(); + return { + labels: [...shown[0].querySelectorAll('button')].map((b) => b.textContent), + box: { left: r.left, top: r.top, right: r.right, bottom: r.bottom }, + count: shown.length, + }; + }); + async function pressMenu(page, label) { + const p = await page.evaluate((label) => { + const button = [...document.querySelectorAll('[data-codepad-menu] button')].find( + (b) => b.textContent === label && getComputedStyle(b.parentElement).display !== 'none', + ); + const r = button.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + }, label); + await page.mouse.click(p.x, p.y); + await settle(page); + } + // The left of a menu centred on x and kept inside editor a's box. + const centredLeft = (page, menu, x) => + page.evaluate( + ([width, x]) => { + const r = document.getElementById('a').getBoundingClientRect(); + return Math.max(r.left, Math.min(x - width / 2, r.right - width)); + }, + [menu.box.right - menu.box.left, x], + ); + // Records the text every copy or cut event carries, after the editor wrote it. + const recordClipboard = (page) => + page.evaluate(() => { + window.copied = []; + for (const type of ['copy', 'cut']) + document.addEventListener(type, (e) => + window.copied.push(e.clipboardData.getData('text/plain')), + ); + }); + + test('a long press shows Cut, Copy, Paste and Select all in that order', async () => { + const { page, errors } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + assert.deepEqual((await menuOf(page))?.labels, ['Cut', 'Copy', 'Paste', 'Select all']); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('a tap on the insertion handle shows the menu', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await tap(page, 'a', await pointAt(page, 'a', 0, 3)); + assert.equal(await menuOf(page), null); + const tip = (await tips(page, 'a')).insertion; + await tap(page, 'a', { x: tip.x, y: tip.y + 10 }); + assert.deepEqual((await menuOf(page))?.labels, ['Paste', 'Select all']); + assert.deepEqual(await selectionOf(page, 'a'), [3, 3]); + 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 }); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + assert.deepEqual((await menuOf(page))?.labels, ['Copy', 'Select all']); + assert.equal(await page.evaluate(() => document.querySelector('#a textarea').readOnly), true); + await page.close(); + }); + + test("the menu's Copy puts all 3000 selected lines on the clipboard", async () => { + const { page } = await open(); + if (engine === chromium) + await page.context().grantPermissions(['clipboard-read', 'clipboard-write']); + const text = lines(3000); + await editor(page, 'a', text); + await recordClipboard(page); + await longPress(page, 'a', await pointAt(page, 'a', 1, 1)); + await pressMenu(page, 'Select all'); + await pressMenu(page, 'Copy'); + assert.deepEqual(await page.evaluate(() => window.copied), [text]); + if (engine === chromium) + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), text); + assert.equal(await menuOf(page), null); + await page.close(); + }); + + test("the menu's Cut removes the selection in one undo step", async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await recordClipboard(page); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + await pressMenu(page, 'Cut'); + assert.equal(await textOf(page, 'a'), 'alpha gamma'); + assert.deepEqual(await page.evaluate(() => window.copied), ['beta']); + assert.equal(await menuOf(page), null); + await page.keyboard.press('ControlOrMeta+z'); + assert.equal(await textOf(page, 'a'), 'alpha beta gamma'); + await page.close(); + }); + + test('Select all keeps the menu and moves it', async () => { + const { page } = await open(); + await editor(page, 'a', lines(40)); + await longPress(page, 'a', await pointAt(page, 'a', 6, 1)); + const before = await menuOf(page); + await pressMenu(page, 'Select all'); + const after = await menuOf(page); + assert.deepEqual(await selectionOf(page, 'a'), [0, lines(40).length]); + assert.ok( + after !== null && after.box.top !== before.box.top, + JSON.stringify({ before, after }), + ); + await page.close(); + }); + + test('the menu follows the selection on scroll and hides when it scrolls out', async () => { + const { page } = await open(); + await editor(page, 'a', lines(300)); + await longPress(page, 'a', await pointAt(page, 'a', 8, 1)); + const before = await menuOf(page); + const row = await page.evaluate(() => window.views.a.layout.rowHeight); + const scroll = (rows) => + page.evaluate(async (y) => { + document.querySelector('#a [data-scroller]').scrollTop = y; + await window.codepad.frames(3); + }, rows * row); + await scroll(2); + const moved = await menuOf(page); + assert.ok( + Math.abs(before.box.top - moved.box.top - 2 * row) <= 1, + JSON.stringify({ before, moved }), + ); + await scroll(20); + assert.equal(await menuOf(page), null); + await page.close(); + }); + + test('the menu over line 0 opens below the selection', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma\nsecond'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + const menu = await menuOf(page); + const line = await page.evaluate(() => + document.querySelector('#a [data-line="0"]').getBoundingClientRect().toJSON(), + ); + assert.ok(menu.box.top >= line.bottom, JSON.stringify({ menu, line })); + await page.close(); + }); + + test('the menu anchors to the end in view when the other end is scrolled out', async () => { + const { page } = await open(); + await editor(page, 'a', lines(300)); + await longPress(page, 'a', await pointAt(page, 'a', 2, 1)); + const end = await page.evaluate(async () => { + const v = window.views.a; + const head = v.core.lineStart(12) + 3; + v.apply(() => v.core.setSelection(v.core.lineStart(2), head)); + document.querySelector('#a [data-scroller]').scrollTop = v.layout.rowHeight * 5; + await window.codepad.frames(3); + const box = document.getElementById('a').firstElementChild.getBoundingClientRect(); + const r = v.caretRect(head); + return { x: r.x + box.left, top: r.y + box.top }; + }); + const menu = await menuOf(page); + assert.ok(Math.abs(menu.box.left - (await centredLeft(page, menu, end.x))) <= 1); + assert.ok(Math.abs(menu.box.bottom + 8 - end.top) <= 1, JSON.stringify({ menu, end })); + await page.close(); + }); + + test('a right click shows the menu at the pointer', async () => { + const { page } = await open(); + await editor(page, 'a', 'one\ntwo\nthree\nfour\nfive\nthis line runs on past the middle'); + const at = await pointAt(page, 'a', 5, 30); + await page.mouse.click(at.x, at.y, { button: 'right' }); + await settle(page); + const menu = await menuOf(page); + assert.deepEqual(menu?.labels, ['Paste', 'Select all']); + const width = menu.box.right - menu.box.left; + assert.ok(Math.abs(menu.box.left - (at.x - width / 2)) <= 1, JSON.stringify({ menu, at })); + assert.ok(Math.abs(menu.box.bottom + 8 - at.y) <= 1, JSON.stringify({ menu, at })); + assert.deepEqual(await selectionOf(page, 'a'), [54, 54]); + await page.close(); + }); + + test("showing the menu in one editor hides the other's and its Copy copies its own text", async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await editor(page, 'b', 'delta epsilon'); + await recordClipboard(page); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + await longPress(page, 'b', await pointAt(page, 'b', 0, 8)); + assert.equal((await menuOf(page))?.count, 1); + await pressMenu(page, 'Copy'); + assert.deepEqual(await page.evaluate(() => window.copied), ['epsilon']); + await page.close(); + }); + + test('a typed key hides the menu', async () => { + const { page } = await open(); + await editor(page, 'a', 'alpha beta gamma'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + assert.notEqual(await menuOf(page), null); + await page.keyboard.type('x'); + await settle(page); + assert.equal(await textOf(page, 'a'), 'alpha x gamma'); + assert.equal(await menuOf(page), null); + await page.close(); + }); + + test('Paste is missing when navigator.clipboard is', async () => { + const { page } = await open(); + await page.evaluate(() => + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }), + ); + await editor(page, 'a', 'alpha beta gamma'); + await longPress(page, 'a', await pointAt(page, 'a', 0, 7)); + assert.deepEqual((await menuOf(page))?.labels, ['Cut', 'Copy', 'Select all']); + 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');