Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 101 additions & 7 deletions src/web/EditorView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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<string>();
private readonly refreshedFor = new Set<string>();
Expand Down Expand Up @@ -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;
Expand All @@ -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) : () => {};
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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++) {
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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}`;
Expand Down
15 changes: 14 additions & 1 deletion src/web/__tests__/keyboardInset.test.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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;
}
});
15 changes: 12 additions & 3 deletions src/web/input/keyboardInset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading