diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 1b950f0..115e4c1 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -27,7 +27,7 @@ import { HANDLE_HEIGHT, type HandleEnds, Handles } from './Handles'; import { CaretMover, type LineGeometry } from './input/CaretMover'; import type { HandleKind } from './input/GestureMachine'; import { InputHost } from './input/InputHost'; -import { overlapOf, visibleBottomIn, watchViewport } from './input/keyboardInset'; +import { keyboardTopIn, overlapOf, visibleBottomIn, watchViewport } from './input/keyboardInset'; import { keyCommand } from './input/keys'; import { type Box, PointerHost } from './input/PointerHost'; import { lineUnit } from './input/units'; @@ -100,6 +100,8 @@ const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mo const SNAPSHOT_INFO_INTS = 7; // How long an animated scrollToLine runs, as ScrollController.kt. const LINE_SCROLL_MS = 250; +// The keyboard top the core reads as no keyboard, INT32_MAX. +const NO_KEYBOARD = 2147483647; // How long the insertion handle shows after a tap, as Android. const INSERTION_HANDLE_MS = 4000; @@ -206,14 +208,25 @@ export class EditorView { this.invalidate(); }; private readonly onPageEvent = () => this.invalidate(); + // The window or the page scroller changed size: a page-mode editor shows its caret again. + private readonly onPageResize = () => { + this.pageReveal = true; + 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. + // The lowest textarea top in view coordinates that the keyboard leaves visible, and whether placeInput holds to it. private inputLimit = 0; + private clampInput = false; + // Page mode under avoidKeyboard: the keyboard top of the last reveal, a reveal due in this draw, the scroller watched. + private pageKeyboard = NO_KEYBOARD; + private pageReveal = false; + private pageWatched: Element | null = null; + private readonly pageResize: ResizeObserver | null; // 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(); @@ -410,6 +423,8 @@ export class EditorView { this.resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => this.invalidate()); this.resize?.observe(this.scroller); + this.pageResize = + typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(this.onPageResize); document.fonts?.ready.then(() => this.remeasure()); document.fonts?.addEventListener?.('loadingdone', this.remeasureEvent); this.lastSelection = this.core.selection; @@ -433,6 +448,11 @@ export class EditorView { before.lineNumbers !== this.o.lineNumbers || before.scrollEnabled !== this.o.scrollEnabled; if (before.scrollEnabled !== this.o.scrollEnabled) this.listenToPage(!this.o.scrollEnabled); + if ( + before.scrollEnabled !== this.o.scrollEnabled || + before.keyboardOffset !== this.o.keyboardOffset + ) + this.pageReveal = true; if (before.avoidKeyboard !== this.o.avoidKeyboard) { this.offViewport(); this.offViewport = this.o.avoidKeyboard ? watchViewport(this.onPageEvent) : () => {}; @@ -696,7 +716,7 @@ export class EditorView { // 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); + this.input.place(x, this.clampInput ? 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. @@ -1156,6 +1176,63 @@ export class EditorView { ); } + // The keyboard counts as up while the textarea holds the focus after a touch: with resizes-content no viewport shows it. + private keyboardUp(): boolean { + return this.touchMode && this.input.focused; + } + + // The keyboard's top in page coordinates for the core, NO_KEYBOARD while it is down. + private keyboardTop(): number { + return this.keyboardUp() ? Math.floor(Math.min(keyboardTopIn(), NO_KEYBOARD)) : NO_KEYBOARD; + } + + // Follows the page scroller's size while a focused page-mode editor keeps its caret in view. The window has resize. + private watchPageScroller(target: Element | null): void { + if (target === this.pageWatched) return; + this.pageResize?.disconnect(); + this.pageWatched = target; + if (target) this.pageResize?.observe(target); + } + + // Page mode under avoidKeyboard: scrolls the nearest scroller the least that shows the caret's row inside it and + // above the keyboard. True when it scrolled. + private revealInPage(): boolean { + const o = this.o; + if (o.scrollEnabled || !o.avoidKeyboard || !this.input.focused) return false; + const layout = this.layout; + const line = this.core.lineAt(this.core.selection.head); + const rowTop = + this.root.getBoundingClientRect().top + + layout.scrollY + + layout.lineTop(line) + + this.drawnCaretRow * this.rowHeight; + const host = this.pageScroller(); + let top = 0; + let bottom = window.innerHeight; + let up = window.scrollY; + let down = (document.scrollingElement ?? document.documentElement).scrollHeight - bottom - up; + if (host) { + top = host.getBoundingClientRect().top + host.clientTop; + bottom = top + host.clientHeight; + up = host.scrollTop; + down = host.scrollHeight - host.clientHeight - up; + } + const delta = this.m._cp_page_reveal_delta( + Math.floor(rowTop), + Math.ceil(rowTop + this.rowHeight), + Math.ceil(top), + Math.floor(bottom), + this.pageKeyboard, + Math.round(Math.max(0, o.keyboardOffset)), + Math.max(0, Math.floor(up)), + Math.max(0, Math.floor(down)), + ); + if (delta === 0) return false; + if (host) host.scrollTop += delta; + else window.scrollBy(0, delta); + return true; + } + // 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; @@ -1639,6 +1716,7 @@ export class EditorView { this.measuring.clear(); this.configure(); this.restaleRefreshed(); + const caretMoved = this.revealing; let moved = this.frame(); // A caret moved off screen scrolls into view before the paint: by row while its line is not drawn, then by x. for (let pass = 0; this.revealing && pass < 2; pass++) { @@ -1657,6 +1735,10 @@ export class EditorView { moved = this.frame(); } this.revealing = false; + if (caretMoved || this.pageReveal) { + this.pageReveal = false; + if (this.revealInPage()) moved = this.frame() || moved; + } if (moved) { this.syncScroll(); this.dirty = true; @@ -1693,6 +1775,7 @@ export class EditorView { this.listenToPage(false); this.offViewport(); this.resize?.disconnect(); + this.pageResize?.disconnect(); document.fonts?.removeEventListener?.('loadingdone', this.remeasureEvent); this.scroller.removeEventListener('scroll', this.onScrollEvent); this.scroller.removeEventListener('wheel', this.stopLineScrollEvent); @@ -1761,7 +1844,7 @@ export class EditorView { capture: true, passive: true, } as AddEventListenerOptions); - window[method]('resize', this.onPageEvent); + window[method]('resize', this.onPageResize); } private applyOptions(metrics: boolean): void { @@ -1818,11 +1901,22 @@ export class EditorView { if (this.layout.gutterWidth !== gutter) this.layout.gutterWidth = gutter; if (this.layout.textPadding !== o.textPadding) this.layout.textPadding = o.textPadding; this.layout.resize(width, height); - // An editor that sizes to its text leaves the keyboard to the page. - const keyboard = o.avoidKeyboard && o.scrollEnabled ? overlapOf(this.root) : 0; + // An editor that sizes to its text leaves the keyboard to the page, which revealInPage scrolls. + const pageMode = !o.scrollEnabled && o.avoidKeyboard; + let keyboard = o.avoidKeyboard && o.scrollEnabled ? overlapOf(this.root) : 0; + const raise = Math.max(0, o.keyboardOffset); + if (o.avoidKeyboard && o.scrollEnabled && raise > 0 && (keyboard > 0 || this.keyboardUp())) + keyboard = overlapOf(this.root, raise); if (keyboard > this.keyboard && this.input.focused) this.revealing = true; this.keyboard = keyboard; - if (keyboard > 0) this.inputLimit = visibleBottomIn(this.root) - this.rowHeight; + this.clampInput = keyboard > 0 || (pageMode && this.keyboardUp()); + if (this.clampInput) this.inputLimit = visibleBottomIn(this.root) - this.rowHeight; + const pageKeyboard = pageMode && this.input.focused ? this.keyboardTop() : NO_KEYBOARD; + if (pageKeyboard !== this.pageKeyboard) { + this.pageKeyboard = pageKeyboard; + this.pageReveal = true; + } + this.watchPageScroller(pageMode && this.input.focused ? this.pageScroller() : null); const bottom = (insets.bottom ?? 0) + keyboard; this.layout.setInsets(insets.top ?? 0, bottom, insets.left ?? 0, insets.right ?? 0); const placedAt = `${this.layout.textAreaLeft}:${this.layout.insetTop}`; diff --git a/src/web/__tests__/keyboardInset.test.ts b/src/web/__tests__/keyboardInset.test.ts index c3930a1..70dab0c 100644 --- a/src/web/__tests__/keyboardInset.test.ts +++ b/src/web/__tests__/keyboardInset.test.ts @@ -1,5 +1,5 @@ import { expect, test } from '@jest/globals'; -import { keyboardOverlap } from '../input/keyboardInset'; +import { keyboardOverlap, keyboardTopIn } from '../input/keyboardInset'; test('the keyboard covers what lies below the visual viewport', () => { expect(keyboardOverlap(800, 0, 500, 900)).toBe(300); @@ -11,3 +11,16 @@ test('an editor that runs past the window with no keyboard gets no inset', () => expect(keyboardOverlap(1100, 0, 900, 900)).toBe(0); expect(keyboardOverlap(1100, 0, 500, 900)).toBe(400); }); + +test('the keyboard top is out of reach with no visual viewport or a pinch zoom', () => { + const global = globalThis as { window?: unknown }; + expect(keyboardTopIn()).toBe(Number.MAX_SAFE_INTEGER); + global.window = { visualViewport: { scale: 2, offsetTop: 40, height: 300 } }; + try { + expect(keyboardTopIn()).toBe(Number.MAX_SAFE_INTEGER); + global.window = { visualViewport: { scale: 1, offsetTop: 40, height: 300 } }; + expect(keyboardTopIn()).toBe(340); + } finally { + delete global.window; + } +}); diff --git a/src/web/input/keyboardInset.ts b/src/web/input/keyboardInset.ts index 14d2a65..be1971d 100644 --- a/src/web/input/keyboardInset.ts +++ b/src/web/input/keyboardInset.ts @@ -10,13 +10,22 @@ export function keyboardOverlap( return Math.max(0, Math.min(editorBottom, layoutHeight) - (viewportTop + viewportHeight)); } -// The keyboard's overlap with an element's box, 0 where the page has no visual viewport or is pinch-zoomed. -export function overlapOf(el: HTMLElement): number { +// The keyboard's overlap with an element's box, with the keyboard's top raised by raise px. 0 where the page has no +// visual viewport or is pinch-zoomed. +export function overlapOf(el: HTMLElement, raise = 0): number { const vv = typeof window === 'undefined' ? undefined : window.visualViewport; if (!vv || Math.abs(vv.scale - 1) > 0.01) return 0; const bottom = el.getBoundingClientRect().bottom; const layout = document.documentElement.clientHeight; - return Math.round(keyboardOverlap(bottom, vv.offsetTop, vv.height, layout)); + return Math.round(keyboardOverlap(bottom, vv.offsetTop, vv.height - raise, layout)); +} + +// The visual viewport's bottom in page coordinates, where a keyboard's top sits. MAX_SAFE_INTEGER where the page has +// no visual viewport or is pinch-zoomed. +export function keyboardTopIn(): number { + const vv = typeof window === 'undefined' ? undefined : window.visualViewport; + if (!vv || Math.abs(vv.scale - 1) > 0.01) return Number.MAX_SAFE_INTEGER; + return vv.offsetTop + vv.height; } // The visual viewport's bottom in an element's own coordinates: the lowest point the keyboard leaves uncovered. diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 95ec85d..c17156c 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -705,6 +705,205 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + // A keyboard over all of the page but its top height px, as the existing keyboard tests stub it. + const setKeyboard = (page, height) => + page.evaluate(async (height) => { + Object.defineProperty(window.visualViewport, 'height', { + configurable: true, + get: () => height, + }); + window.visualViewport.dispatchEvent(new Event('resize')); + await window.codepad.frames(3); + }, height); + // The page-mode editor d in host sv, focused by a touch on a line low in the host, then a keyboard at 300 px. + async function pageKeyboard(page, options = {}, line = 12) { + await editor(page, 'd', lines(60), { scrollEnabled: false, avoidKeyboard: true, ...options }); + await tap(page, 'd', await pointAt(page, 'd', line, 2)); + await setKeyboard(page, 300); + } + // The caret's row in page coordinates, from its line's element (no soft wrap here). + const caretRow = (page, id) => + page.evaluate((id) => { + const v = window.views[id]; + const line = v.core.lineAt(v.core.selection.head); + const r = document.querySelector(`#${id} [data-line="${line}"]`).getBoundingClientRect(); + return { top: r.top, bottom: r.top + v.layout.rowHeight, rowHeight: v.layout.rowHeight }; + }, id); + const hostScroll = (page) => page.evaluate(() => document.getElementById('sv').scrollTop); + + test('in page mode under avoidKeyboard the page scrolls until the caret row clears the keyboard', async () => { + const { page, errors } = await open(); + await scrollingHost(page); + await pageKeyboard(page); + const row = await caretRow(page, 'd'); + assert.ok(row.bottom <= 300.5 && row.bottom > 300 - row.rowHeight, JSON.stringify(row)); + assert.equal(await page.evaluate(() => scrollY), 0); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('in page mode Enter on the row above the keyboard scrolls the page by one row', async () => { + const { page } = await open(); + await scrollingHost(page); + await pageKeyboard(page); + const before = await hostScroll(page); + await page.keyboard.press('End'); + await page.keyboard.press('Enter'); + await settle(page); + const row = await caretRow(page, 'd'); + const moved = (await hostScroll(page)) - before; + assert.ok( + before > 0 && Math.abs(moved - row.rowHeight) <= 1, + JSON.stringify({ before, moved }), + ); + await page.close(); + }); + + test('in page mode with no range left the page does not move', async () => { + const { page, errors } = await open(); + await scrollingHost(page); + await page.evaluate(() => { + const sv = document.getElementById('sv'); + sv.lastElementChild.remove(); + }); + await editor(page, 'd', lines(60), { scrollEnabled: false, avoidKeyboard: true }); + const end = await page.evaluate(() => { + const sv = document.getElementById('sv'); + sv.scrollTop = sv.scrollHeight; + return sv.scrollTop; + }); + await settle(page); + await tap(page, 'd', await pointAt(page, 'd', 58, 2)); + await setKeyboard(page, 300); + const row = await caretRow(page, 'd'); + assert.ok(row.bottom > 300, JSON.stringify(row)); + assert.equal(await hostScroll(page), end); + assert.deepEqual(errors, []); + await page.close(); + }); + + test('keyboardOffset keeps the caret row that far above the keyboard', async () => { + const { page } = await open(); + await scrollingHost(page); + await pageKeyboard(page, { keyboardOffset: 52 }); + const row = await caretRow(page, 'd'); + assert.ok(row.bottom <= 248.5 && row.bottom > 248 - row.rowHeight, JSON.stringify(row)); + await page.close(); + }); + + test('a page scroll by the user is never undone', async () => { + const { page } = await open(); + await scrollingHost(page); + await pageKeyboard(page); + const after = await page.evaluate(async () => { + const sv = document.getElementById('sv'); + sv.scrollTop -= 100; + sv.dispatchEvent(new Event('scroll')); + const at = sv.scrollTop; + await window.codepad.frames(3); + return { at, now: sv.scrollTop }; + }); + assert.ok(after.at > 0 && after.now === after.at, JSON.stringify(after)); + await page.close(); + }); + + test('a horizontal scroller between the editor and the page is skipped', async () => { + const { page } = await open(); + await scrollingHost(page); + await page.evaluate(() => { + const d = document.getElementById('d'); + const wrap = document.createElement('div'); + wrap.style.overflowX = 'auto'; + d.replaceWith(wrap); + wrap.append(d); + }); + await pageKeyboard(page); + const row = await caretRow(page, 'd'); + assert.ok((await hostScroll(page)) > 0 && row.bottom <= 300.5, JSON.stringify(row)); + await page.close(); + }); + + test('the page follows when the keyboard grows', async () => { + const { page } = await open(); + await scrollingHost(page); + await pageKeyboard(page); + await setKeyboard(page, 250); + const row = await caretRow(page, 'd'); + assert.ok(row.bottom <= 250.5 && row.bottom > 250 - row.rowHeight, JSON.stringify(row)); + await page.close(); + }); + + test('turning scrolling on with the keyboard up moves the keyboard into the inset', async () => { + const { page } = await open(); + await scrollingHost(page); + await page.evaluate(() => { + document.getElementById('d').style.height = '1200px'; + }); + await pageKeyboard(page); + const before = await hostScroll(page); + await page.evaluate(async () => { + window.views.d.setOptions({ scrollEnabled: true }); + await window.codepad.frames(3); + }); + const row = await caretRow(page, 'd'); + assert.ok(before > 0 && (await hostScroll(page)) === before, `host at ${before}`); + assert.ok(row.bottom <= 300.5, JSON.stringify(row)); + await page.close(); + }); + + test('in page mode the textarea stays above the keyboard', async () => { + const { page } = await open(); + await scrollingHost(page); + await page.evaluate(() => document.getElementById('sv').lastElementChild.remove()); + await editor(page, 'd', lines(60), { scrollEnabled: false, avoidKeyboard: true }); + await page.evaluate(() => { + const sv = document.getElementById('sv'); + sv.scrollTop = sv.scrollHeight; + }); + await settle(page); + await tap(page, 'd', await pointAt(page, 'd', 58, 2)); + await setKeyboard(page, 300); + const bottom = await page.evaluate( + () => document.querySelector('#d textarea').getBoundingClientRect().bottom, + ); + assert.ok(bottom <= 300, `textarea bottom at ${bottom}`); + await page.close(); + }); + + test('in page mode under avoidKeyboard the arrow keys keep the caret inside the scroller with no keyboard', async () => { + const { page } = await open(); + await scrollingHost(page); + await editor(page, 'd', lines(60), { scrollEnabled: false, avoidKeyboard: true }); + await clickAt(page, 'd', 12, 2); + for (let i = 0; i < 20; i++) await page.keyboard.press('ArrowDown'); + await settle(page); + const box = await hostBox(page); + const low = await caretRow(page, 'd'); + for (let i = 0; i < 32; i++) await page.keyboard.press('ArrowUp'); + await settle(page); + const high = await caretRow(page, 'd'); + assert.ok(Math.abs(low.bottom - box.bottom) <= 0.5, JSON.stringify({ low, box })); + assert.ok(Math.abs(high.top - box.top) <= 0.5, JSON.stringify({ high, box })); + await page.close(); + }); + + test('keyboardOffset covers a scrolling editor that ends just above the keyboard', async () => { + const { page } = await open(); + await page.evaluate(() => { + Object.assign(document.getElementById('a').style, { + position: 'absolute', + top: '0px', + height: '280px', + }); + }); + await editor(page, 'a', lines(60), { avoidKeyboard: true, keyboardOffset: 52 }); + await tap(page, 'a', await pointAt(page, 'a', 3, 2)); + await setKeyboard(page, 300); + // The raised line sits at 248, so 32 px of the 280 px editor count as covered. + assert.equal(await page.evaluate(() => window.views.a.layout.insetBottom), 32); + await page.close(); + }); + test('a touch tap still places the caret and focuses', async () => { const { page } = await open(); await editor(page, 'a', 'abcdef\nghijkl');