An open source design system that's fully customizable and agent ready
TypeScript
feat(core): the keyboard module's docked ride, the scroller's reveal and the tap route (#9776)
Christopher Chedeaue245db5fb999
diff --git a/.changeset/keyboard-targets-docked-ride.md b/.changeset/keyboard-targets-docked-ride.mdnew file mode 100644index 0000000000..4e826a3948--- /dev/null+++ b/.changeset/keyboard-targets-docked-ride.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: Core's keyboard module keeps a field above the on-screen keyboard where its nearest scroller can bring it up: a field in scrolling content is scrolled into view by its nearest scroller, the document included, a field in a container fixed at the viewport's bottom moves that container up by the part of it the keyboard still covers, unless the container sets its own `translate`, the app is moving it itself, or it is taller than the room above the keyboard, where its scroller reveals the field instead, or with none it moves only as far as the field needs, and focus moves and first taps into those fields arrive without the browser's reveal. A field in a fixed container the app positions itself (a dialog or a sheet that fills the viewport, a bar floating above the bottom edge, or a bar with its own `translate`) is revealed by a scroller around it there, and with none keeps the browser's own reveal. Core's fields adopt it next; apps import nothing new.++@vjeuxdiff --git a/.changeset/tall-sheet-keyboard-hide-ride.md b/.changeset/tall-sheet-keyboard-hide-ride.mdnew file mode 100644index 0000000000..5cdfb79912--- /dev/null+++ b/.changeset/tall-sheet-keyboard-hide-ride.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet: in iOS Safari, which publishes no keyboard slide, when the on-screen keyboard closes, a Tall sheet's content rides down with it on UIKit's keyboard spring, instead of jumping back to its earlier scroll once the keyboard is gone. A field that takes focus again before the keyboard is down rides back up, and focus moving to a select, whose picker takes the keyboard's place, starts no ride. In Chrome on Android, a busy page that reads the keyboard's hide late no longer moves the content back up before it settles.++@vjeuxdiff --git a/docs/specs/AST-099-mobile-keyboard/spec.md b/docs/specs/AST-099-mobile-keyboard/spec.mdindex 0e5e987c90..a23d802690 100644--- a/docs/specs/AST-099-mobile-keyboard/spec.md+++ b/docs/specs/AST-099-mobile-keyboard/spec.md@@ -110,7 +110,15 @@ app to turn on.commits the resting value once to layout, as an offset, a padding, or aspacer, so nothing is hidden or unscrollable. How the motion is shared is`architecture:react-component-runtime` INV11; no public API or CSS custom- property exposes it.+ property exposes it. In Safari on iOS, which reports the keyboard only once+ it is down, a fully expanded sheet+ whose field loses focus to a control that brings up neither a keyboard nor a+ picker in the keyboard's place keeps its keyboard layout and moves its+ content to its resting scroll on the motion the keyboard's own hide plays+ (UIKit's keyboard spring), from the blur, as a translate with no JavaScript+ per frame. Once the visual viewport has recovered, the layout drops and the+ translate clears in one commit, so nothing moves. Under reduced motion+ nothing travels, and the change follows `design:reduced-motion` DR2.- **FR4 — Focus never pans the page.** Every route into a text-entry controlinside a keyboard-aware surface, including a tap, the keyboard'sprevious and next buttons, Tab, and programmatic focus, delivers focus@@ -320,9 +328,11 @@ app to turn on.No covered field meets FR9 on `main`. Each gap below is open.- **Gap 1 — The keyboard module.** Partly met: the keyboard module- (`packages/core/src/keyboard/`) measures the keyboard and keeps focus from- panning the page. BottomSheet's Tall sheet reads it. No covered field reads- it yet (Gaps 2–9), and ChatLayout's dock does not (Gap 11).+ (`packages/core/src/keyboard/`) measures the keyboard, keeps focus from+ panning the page, and keeps a focused field above the keyboard: it rides a+ docked container, scrolls a field's nearest scroller, and claims the first+ tap. BottomSheet's Tall sheet reads it. No covered field reads it yet (Gaps+ 2–9), and ChatLayout's dock does not (Gap 11).- **Gap 2 — TextInput, TextArea, and NumberInput.** None has keyboard focushandling. In the page, only the browser's own reveal scroll brings the fieldinto view, and nothing proves it stays above the keyboard.@@ -357,16 +367,21 @@ No covered field meets FR9 on `main`. Each gap below is open.app's own fixed or sticky bottom bar, in a fixed Toolbar, or in a BottomSheetthat is not a fully expanded Tall sheet, has no handling that keeps it abovethe keyboard.-- **Gap 11 — The docked ride and the page-content reveal.** No covered field- rides the keyboard outside a fully expanded Tall sheet. The keyboard module- (Gap 1) carries no docked ride: nothing moves an app's docked fixed container- to the keyboard's top, no field scrolls its nearest scroller to put itself 10 CSS px- above the keyboard in the frame the keyboard is reported, no field adds the- missing scroll range at its scroller's end, and ChatLayout's dock does not- apply the keyboard height. BottomSheet's inset stays local to its own sheet.- The missing scroll range is not added yet; until it is, an element that has- nothing to scroll does not count as a scroller (the field keeps the browser's- own reveal).+- **Gap 11 — The missing scroll range and ChatLayout's dock.** Partly met:+ the keyboard module moves an app's docked fixed container to the keyboard's+ top, and scrolls a field's nearest scroller to put it 10 CSS px above the+ keyboard in the frame the keyboard is reported+ (`packages/core/src/keyboard/keyboardTarget.ts`), but no covered field uses+ it yet (Gap 2). No field adds the missing scroll range at its scroller's end;+ until one does, an element that has nothing to scroll does not count as a+ scroller (the field keeps the browser's own reveal). ChatLayout's dock does+ not apply the keyboard height. BottomSheet's inset stays local to its own+ sheet.+- **Gap 12 — A fully expanded sheet's hide in Firefox for Android.** Firefox+ for Android reports no keyboard slide, so the sheet takes the same path as in+ Safari on iOS (`packages/core/src/keyboard/useMobileKeyboard.ts`). But+ Firefox reports the keyboard's hide once, at its end. The sheet's content+ moves at that report, in one frame, instead of riding from the blur (FR3).### Follow-up@@ -380,7 +395,7 @@ that sets its own `translate`, to the app.| -------- | ------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || FR1 | Source boundary check over Core and Lab plus a shared test that drives one keyboard change | each listed consumer; a new keyboard-aware component | Two components reading different heights for one keyboard, or a component measuring by a rule other than FR2 || FR2 | Module tests driving visual-viewport resize and scroll events | keyboard shown; hidden; page panned with the keyboard shown; offset without a keyboard; page pinch-zoomed with and without the keyboard | A pan that lowers the reported height, or a height when no keyboard is shown |-| FR3 | Consumer tests of computed layout, plus a public-surface check | keyboard shown and hidden; composer, bottom search field, tab bar search, Tall sheet; no animation running; a ride animation running with the composer, a scroll view, and a header together | A consumer whose layout ignores the height, layout that is only correct after an animation, riding surfaces out of sync on one keyboard change, per-frame layout work during a ride, content hidden or unscrollable at the resting value, or a public CSS custom property, export, or prop for the height |+| FR3 | Consumer tests of computed layout, plus a public-surface check | keyboard shown and hidden; composer, bottom search field, tab bar search, Tall sheet; no animation running; a ride animation running with the composer, a scroll view, and a header together; a Tall sheet's field blurred in Safari on iOS | A consumer whose layout ignores the height, layout that is only correct after an animation, riding surfaces out of sync on one keyboard change, per-frame layout work during a ride, content hidden or unscrollable at the resting value, or a public CSS custom property, export, or prop for the height; a Tall sheet's content jumping at a late keyboard report || FR4 | Focus-route tests with document scroll spies | tap, previous and next buttons, Tab, programmatic focus, Done then tap, app resume while scroll-locked | A route where the browser scrolls the document to reveal the focused control, or a slipped scroll left in place; FR9's own reveal scroll by the field's nearest scroller is not a failure || FR5 | Surface move tests | sheet drag between heights, drag to dismiss, close, with a focused field | The field stays focused after a move starts, or content jumps on the first frame || FR6 | Capability tests with the user agent varied | visual viewport shrinking with a fixed layout viewport; Chrome on Android reporting keyboard geometry; a desktop browser with the API and no on-screen keyboard; a page that is not a secure context; neither | Behavior that changes with the user agent alone, or a height taken from the browser's keyboard geometry report instead of FR2's measurement |diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsxindex 3c7377c4b1..d4ca3c6e40 100644--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx@@ -29,6 +29,7 @@ import {__resetInteractionModalityForTest} from '../utils/interactionModality';import {__focusTakeoverCallersForTest} from '../keyboard/keyboardHeight';import {__resetRevealsAtReportForTest} from '../keyboard/useMobileKeyboard';import {getKeyboardLayoutGuide} from '../keyboard/keyboardLayoutGuide';+import {animatorFor} from '../motion/animator';// A sheet has no stops unless its host asks for them, so the tests that// exercise detents pass their own. These three — a 14% peek, a half-height@@ -198,6 +199,26 @@ function mockPrimaryPointer(pointer: 'coarse' | 'fine') {);}+// A touch screen whose user asked for reduced motion.+function mockReducedMotionOnTouch() {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches:+ query === '(pointer: coarse)' ||+ query === '(prefers-reduced-motion: reduce)' ||+ query === '(prefers-reduced-motion: reduce) and (pointer: coarse)',+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+}+// A browser with its own keyboard geometry API (navigator.virtualKeyboard).// Desktop Chrome's visual viewport never shrinks for a keyboard. The module// measures Chrome on Android from its visual viewport, like every browser.@@ -2855,6 +2876,117 @@ describe('BottomSheet', () => {expect(subscribe).not.toHaveBeenCalled();subscribe.mockRestore();});++ describe('on a slow phone, whose reports of the hide come after Gboard\u2019s slide', () => {+ // One clock for event times and the guide's own reads, as in a+ // browser, so the guide's check after the slide runs on time.+ let restoreNow: (() => void) | null = null;+ beforeEach(() => {+ const now = vi+ .spyOn(window.performance, 'now')+ .mockImplementation(() => Date.now());+ restoreNow = () => now.mockRestore();+ });+ afterEach(() => {+ restoreNow?.();+ restoreNow = null;+ });+ const wait = async (ms: number) =>+ act(async () => {+ await new Promise(resolve => setTimeout(resolve, ms));+ });+ // Where the content is drawn at rest: its translate, less the body's+ // scroll.+ const drawnTopOf = (body: HTMLElement, content: HTMLElement) => {+ const [, y = '0px'] = content.style.translate.split(' ');+ return Number.parseFloat(y) - body.scrollTop;+ };++ it('keeps the content where the slide leaves it until the keyboard\u2019s report of its hide, then clears the room with nothing drawn moving', async () => {+ const {body, content, input, report} = renderChromeSheet({+ instantScrollBy: true,+ });+ act(() => input.focus());+ report(500);+ await afterTheSlide();+ expect(drawnTopOf(body, content)).toBe(-248);++ // Done: the field loses focus to nothing, and Gboard slides down. The+ // page is busy, as on a phone at a quarter of the speed. Chrome's+ // reports reach it 603 ms after the blur, with the keyboard partway down, and 1119 ms after it, with the keyboard gone.+ act(() => input.blur());+ // The slide has ended and Chrome has reported nothing yet. The+ // content stays where the scroll from before the keyboard draws it,+ // and the room and the scroll stay.+ await wait(250);+ expect(drawnTopOf(body, content)).toBe(0);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);+ // The keyboard partway down moves nothing.+ await wait(353);+ report(543);+ expect(drawnTopOf(body, content)).toBe(0);+ // The keyboard gone: in one commit the room drops, the scroll goes+ // back and the translate clears, so nothing drawn moves.+ await wait(516);+ report(800);+ expect(keyboardInsetOf(body)).toBe(0);+ expect(body.scrollTop).toBe(0);+ expect(content.style.translate).toBe('');+ expect(drawnTopOf(body, content)).toBe(0);+ await wait(400);+ expect(drawnTopOf(body, content)).toBe(0);+ expect(content.style.translate).toBe('');+ });++ it('rides the content back up with the keyboard when the field takes focus again before Chrome reports the hide', async () => {+ const {body, content, input, report} = renderChromeSheet({+ instantScrollBy: true,+ });+ act(() => input.focus());+ report(500);+ await afterTheSlide();++ act(() => input.blur());+ // After Gboard's slide, before any report, the field takes focus+ // again. The keyboard comes back, so the content rides back up with+ // it and stays there.+ await wait(250);+ act(() => input.focus());+ await wait(500);+ expect(drawnTopOf(body, content)).toBe(-248);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);+ expect(content.style.translate).toBe('');+ // Chrome's report that the keyboard is up again moves nothing.+ report(500);+ expect(drawnTopOf(body, content)).toBe(-248);+ });++ it('rides the content back up once the check after the slide reads the keyboard still up, when focus moves into a frame whose field keeps it', async () => {+ const {body, content, input, report} = renderChromeSheet({+ instantScrollBy: true,+ picker: <iframe key="f" title="Editor" sandbox="" />,+ });+ const frame = screen.getByTitle('Editor');+ act(() => input.focus());+ report(500);+ await afterTheSlide();+ expect(drawnTopOf(body, content)).toBe(-248);++ // The field inside the frame keeps the keyboard up, and Chrome+ // reports nothing. The guide cannot see that field, so the check+ // 150 ms after the slide believes the viewport.+ act(() => frame.focus());+ expect(document.activeElement).toBe(frame);+ await wait(250);+ expect(drawnTopOf(body, content)).toBe(0);+ await wait(550);+ expect(drawnTopOf(body, content)).toBe(-248);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(content.style.translate).toBe('');+ });+ });});it('subscribes no keyboard layout guide where the keyboard moves on Safari\u2019s schedule, whose transitions the sheet never rides (spec:AST-099 FR8)', () => {@@ -3415,6 +3547,300 @@ describe('BottomSheet', () => {expect(body.scrollTop).toBe(448);});+ describe('in iOS Safari, which reports the keyboard once it is gone (spec:AST-099 FR3)', () => {+ // A Tall sheet in iOS Safari: a visual viewport, no keyboard geometry+ // API, and a coarse pointer. Its body, from top 100 to bottom 800, holds+ // 800 px of content and the room after it. A reveal's scroll lands at+ // once.+ function renderIOSSheet({+ pointer = 'coarse',+ reducedMotion = false,+ picker,+ }: {+ pointer?: 'coarse' | 'fine';+ reducedMotion?: boolean;+ picker?: ReactNode;+ } = {}) {+ mockIOSWebKit();+ if (reducedMotion) {+ mockReducedMotionOnTouch();+ } else {+ mockPrimaryPointer(pointer);+ }+ mockWindowHeight(800);+ const viewport = mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ {picker}+ </BottomSheet>,+ );+ const body = getBody();+ const content = body.firstElementChild as HTMLElement;+ const input = screen.getByRole('textbox', {name: 'Comment'});+ let scrollTop = 0;+ const scrollHeight = () => 800 + keyboardInsetOf(body);+ const maxScroll = () => scrollHeight() - 700;+ Object.defineProperties(body, {+ clientHeight: {configurable: true, get: () => 700},+ scrollHeight: {configurable: true, get: scrollHeight},+ scrollTop: {+ configurable: true,+ get: () => Math.min(scrollTop, maxScroll()),+ set: (value: number) => {+ scrollTop = Math.max(0, Math.min(value, maxScroll()));+ },+ },+ });+ Object.defineProperty(body, 'scrollBy', {+ configurable: true,+ value: (options: ScrollToOptions) => {+ body.scrollTop += options.top ?? 0;+ },+ });+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 660 - body.scrollTop, bottom: 700 - body.scrollTop}),+ );+ const report = (height: number) => {+ viewport.height = height;+ act(() => {+ viewport.dispatchEvent(new Event('resize'));+ });+ };+ // Where the content is drawn at `time`: its layout's place, less the+ // body's scroll, moved by its translate.+ const drawnTop = (time?: number) =>+ animatorFor(content).get('y', time) - body.scrollTop;+ return {body, content, input, report, drawnTop};+ }++ const nextFrame = async () =>+ act(async () => {+ await new Promise(resolve => requestAnimationFrame(resolve));+ });+ const afterTheHide = async () =>+ act(async () => {+ await new Promise(resolve => setTimeout(resolve, 450));+ });++ it('rides the content down on the keyboard\u2019s spring from the blur, and the report then moves nothing', async () => {+ const {body, content, input, report, drawnTop} = renderIOSSheet();+ act(() => input.focus());+ report(500);+ expect(body.scrollTop).toBe(248);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(drawnTop()).toBe(-248);++ // Done: the field loses focus to nothing, and the keyboard goes down.+ const blurAt = performance.now();+ act(() => input.blur());+ await nextFrame();+ // Sampled every 16 ms through the keyboard's slide, the content moves+ // down a little each frame. It lands where the scroll from before the+ // keyboard draws it. No frame jumps.+ const samples = Array.from({length: 32}, (_, frame) =>+ drawnTop(blurAt + frame * 16),+ );+ for (let frame = 1; frame < samples.length; frame += 1) {+ const step = (samples[frame] ?? 0) - (samples[frame - 1] ?? 0);+ expect(step).toBeGreaterThanOrEqual(-0.01);+ expect(step).toBeLessThan(40);+ }+ expect(samples.at(-1)).toBeCloseTo(0, 0);+ // The room and the scroll stay until the keyboard is gone.+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);++ // iOS reports the keyboard gone about half a second after the blur.+ // In one commit the room drops, the scroll goes back and the+ // translate clears, so nothing drawn moves.+ await afterTheHide();+ const before = drawnTop();+ report(800);+ expect(keyboardInsetOf(body)).toBe(0);+ expect(body.scrollTop).toBe(0);+ expect(content.style.translate).toBe('');+ expect(drawnTop() - before).toBeCloseTo(0, 0);+ });++ it('rides nothing under a fine pointer: the content stays put until the report clears the room', async () => {+ const {body, input, report, drawnTop} = renderIOSSheet({+ pointer: 'fine',+ });+ act(() => input.focus());+ report(500);+ const settled = drawnTop();+ act(() => input.blur());+ await nextFrame();+ expect(drawnTop(performance.now() + 450)).toBe(settled);+ report(800);+ expect(keyboardInsetOf(body)).toBe(0);+ });++ it('dips the content out and back in at its resting place under Reduce Motion, and the report then moves nothing (design:reduced-motion DR2)', async () => {+ const {body, content, input, report, drawnTop} = renderIOSSheet({+ reducedMotion: true,+ });+ act(() => input.focus());+ report(500);+ act(() => input.blur());+ await nextFrame();+ // The cross-fade lands the content on a timer, so the samples are+ // read as the frames pass.+ const animator = animatorFor(content);+ const offsets: number[] = [];+ const opacities: number[] = [];+ for (let frame = 0; frame < 28; frame += 1) {+ offsets.push(animator.get('y'));+ opacities.push(animator.get('opacity'));+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 16));+ });+ }+ // Nothing travels. Each sample is where the content was or where it+ // rests, and it fades out and back in around the landing.+ expect(+ offsets.every(y => Math.abs(y) < 0.5 || Math.abs(y - 248) < 0.5),+ ).toBe(true);+ expect(offsets.at(-1)).toBeCloseTo(248, 0);+ expect(Math.min(...opacities)).toBeLessThan(0.5);+ expect(opacities.at(-1)).toBeCloseTo(1, 2);++ await afterTheHide();+ const before = drawnTop();+ report(800);+ expect(keyboardInsetOf(body)).toBe(0);+ expect(drawnTop() - before).toBeCloseTo(0, 0);+ });++ it('starts no ride when focus moves from a field to a select, whose picker iOS puts where the keyboard was', async () => {+ const {body, input, report, drawnTop} = renderIOSSheet({+ picker: (+ <select aria-label="Picker">+ <option>One</option>+ </select>+ ),+ });+ act(() => input.focus());+ report(500);+ const settled = drawnTop();+ act(() => screen.getByLabelText('Picker').focus());+ await nextFrame();+ expect(drawnTop(performance.now() + 450)).toBe(settled);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);+ });++ // A field the sheet cannot see: one in an open shadow host or in a frame.+ // Focus on it leaves `document.activeElement` on its holder.+ const hiddenFields = [+ ['an open shadow host', 'shadow host'],+ ['a frame', 'frame'],+ ] as const;+ function renderWithHiddenField(kind: 'shadow host' | 'frame') {+ const sheet = renderIOSSheet({+ picker:+ kind === 'frame' ? (+ <iframe title="Editor" sandbox="" />+ ) : (+ <div title="Editor" />+ ),+ });+ const holder = screen.getByTitle('Editor');+ const field: HTMLElement =+ kind === 'frame'+ ? holder+ : holder+ .attachShadow({mode: 'open'})+ .appendChild(document.createElement('input'));+ const focusHiddenField = () => {+ act(() => field.focus());+ expect(document.activeElement).toBe(holder);+ };+ return {...sheet, focusHiddenField};+ }++ it.each(hiddenFields)(+ 'starts no ride when focus moves from a field into %s, whose own field can keep the keyboard up',+ async (_, kind) => {+ const {body, input, report, drawnTop, focusHiddenField} =+ renderWithHiddenField(kind);+ act(() => input.focus());+ report(500);+ const settled = drawnTop();+ focusHiddenField();+ await nextFrame();+ expect(drawnTop(performance.now() + 450)).toBe(settled);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);+ },+ );++ it('rides the content back up when a field takes focus before the keyboard is gone', async () => {+ const {body, input, report, drawnTop} = renderIOSSheet();+ act(() => input.focus());+ report(500);+ act(() => input.blur());+ await nextFrame();+ // Focus comes back to the field mid-slide, so the keyboard stays.+ act(() => input.focus());+ await nextFrame();+ expect(drawnTop(performance.now() + 450)).toBeCloseTo(-248, 0);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);+ });++ it.each(hiddenFields)(+ 'rides the content back up when focus moves into %s before the keyboard is gone',+ async (_, kind) => {+ const {body, input, report, drawnTop, focusHiddenField} =+ renderWithHiddenField(kind);+ act(() => input.focus());+ report(500);+ act(() => input.blur());+ await nextFrame();+ // Focus moves to a field inside the holder mid-slide, so the+ // keyboard stays.+ focusHiddenField();+ await nextFrame();+ expect(drawnTop(performance.now() + 450)).toBeCloseTo(-248, 0);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);+ },+ );++ it('glides the content to its new place when the keyboard goes while its field keeps focus, as a downward dismissal leaves it', () => {+ const {body, input, report, drawnTop} = renderIOSSheet();+ act(() => input.focus());+ report(500);+ expect(drawnTop()).toBe(-248);+ // The clock holds still through the report, so the glide starts at+ // `reportAt` however slowly the test runs.+ const reportAt = performance.now();+ const clock = vi+ .spyOn(window.performance, 'now')+ .mockReturnValue(reportAt);+ try {+ report(800);+ } finally {+ clock.mockRestore();+ }+ expect(keyboardInsetOf(body)).toBe(0);+ expect(body.scrollTop).toBe(0);+ // Drawn where it was at the report, then down on the keyboard's spring:+ // two frames in, it has hardly moved.+ expect(drawnTop(reportAt + 32)).toBeLessThan(-200);+ expect(drawnTop(reportAt + 450)).toBeCloseTo(0, 0);+ });+ });+it('retains Tall keyboard scroll space during travel until the viewport recovers', () => {const viewport = mockVisualViewport(500);render(diff --git a/packages/core/src/Outline/useScrollSpy.ts b/packages/core/src/Outline/useScrollSpy.tsindex 2144542215..bffbb34aa4 100644--- a/packages/core/src/Outline/useScrollSpy.ts+++ b/packages/core/src/Outline/useScrollSpy.ts@@ -35,6 +35,7 @@*/import {useCallback, useEffect, useRef, useState} from 'react';+import {scrollingAncestor} from '../utils/scrollingAncestor';import type {OutlineItem} from './types';/**@@ -57,30 +58,6 @@ const SCROLL_KEYS = new Set(['Spacebar',]);-function getScrollableAncestor(- element: HTMLElement | null,-): HTMLElement | null {- let current = element?.parentElement ?? null;-- while (current != null) {- const computedStyle = window.getComputedStyle(current);- const overflowY = computedStyle.overflowY;- const isScrollable =- (overflowY === 'auto' ||- overflowY === 'scroll' ||- overflowY === 'overlay') &&- current.scrollHeight > current.clientHeight;-- if (isScrollable) {- return current;- }-- current = current.parentElement;- }-- return null;-}-/** The element's own `scroll-margin-top` in px (0 when unset). */function getScrollMarginTop(element: HTMLElement): number {return (@@ -271,7 +248,8 @@ export function useScrollSpy({*/const getScrollRoot = useCallback((): HTMLElement | null => {return (- scrollContainerRef?.current ?? getScrollableAncestor(rootRef.current)+ scrollContainerRef?.current ??+ (rootRef.current == null ? null : scrollingAncestor(rootRef.current)));}, [rootRef, scrollContainerRef]);diff --git a/packages/core/src/keyboard/README.md b/packages/core/src/keyboard/README.mdindex c4bc77f9f9..c55c9e579a 100644--- a/packages/core/src/keyboard/README.md+++ b/packages/core/src/keyboard/README.md@@ -43,6 +43,14 @@ that times motion with it. Everything here is internal toagain. Every caller in a document shares one listener, which lives onlywhile a caller does; BottomSheet's hook installs it only under a coarseprimary pointer.+- **The tap route (FR4):** a first tap moves focus from nothing, so no+ `blur` claims it. `claimTapFocus(region, {claim, deliver})` takes a+ one-finger tap the browser would turn into focus, cancels the tap's+ default, lets the click guard (utils/clickGuard.ts) take the mouse events+ Safari may still send, and lets `deliver` focus the field.+ `focusAtPoint(field, x, y)` focuses it with `preventScroll` and puts the+ caret under the finger. A touch past 10 px is+ the browser's to scroll.- **The browser's own reveal pan (FR4):** `watchRevealPan(window, {owns})`is the one building block every keyboard-aware surface uses for a browserthat pans the visual viewport to a focused field after the keyboard's@@ -57,6 +65,54 @@ that times motion with it. Everything here is internal towhile a surface watches. BottomSheet's hook watches while its sheet is presentedunder a coarse primary pointer; under a fine one it registers no touchlistener.+- **Keyboard targets (`keyboardTarget.ts`):** a target keeps the focused field+ inside it above the keyboard, and registers so a field inside moves nothing+ itself (`registerKeyboardTarget`, `isInsideKeyboardTarget`).+ `followKeyboard(target, {move, offset})` is a target that moves no inset:+ `'ride'` moves the target with the keyboard, on the guide's slide where one is+ published and at each report elsewhere; `'reveal'` scrolls the field into+ place in the target, a scroller. A reveal comes when the keyboard's height+ changes or focus moves, so a pan or a scroll leaves the field where the person+ put it. `keepFieldAboveKeyboard(field)` is a field's own path. When the field+ gains focus it decides where it is from its nearest+ fixed-position ancestor (`fixedContainerOf`). Docked at the viewport's bottom+ edge by its layout, without any transform, that container moves up by the part+ of it the keyboard still covers; one taller than the room above the keyboard,+ such as a full-height drawer, never rides its whole overlap: its scroller+ there reveals the field instead, and with none it rides only as far as the+ focused field needs to clear the keyboard, so a field near its top stays on+ screen. In a fixed container that fills the viewport, the field's scroller+ there reveals it. In scrolling content, the field's nearest scroller, the+ document included, brings it into view on both edges (`distanceIntoBand`,+ shared with the Tall sheet's reveal), `FIELD_OFFSET` (10 px) above the+ keyboard while one shows. Nothing else moves. A scroller does not gain the+ missing scroll range at its end yet (`spec:AST-099` Gap 11), so a field it+ cannot scroll far enough stays partly covered, and an element with nothing to+ scroll yet, the document included, does not count as a scroller: the browser's+ own reveal stays there. In a fixed container the app positions (one that+ fills the viewport, floats above the bottom edge, or sets its own `translate`,+ which the ride would replace), a scroller between the field and the container+ reveals the field. Inside a keyboard target, or in such a container with no+ scroller around the field, the path does nothing and the browser's own reveal+ stays. A+ ride places its target on the frame after each report, slide or focus move,+ once every listener of that event has run, and measures what the keyboard+ still covers after any move the app makes itself: a bar the app already moves+ with the keyboard is not moved, one the app lifts part of the way moves the+ rest, and one the app is moving itself at that moment (a running CSS+ transition or animation on its position) is left to the app; a script+ animation is not seen, so an app that moves its bar from script keeps it clear+ with its own `translate`. The ride writes the CSS `translate`, which adds to+ an app's `transform`, writes nothing on an element it never moved, and on an+ app's element only while that element stays docked. A Core host's ride moves+ its own element and keeps its focused field `offset` above the keyboard. A+ target lifts only while a field inside it has focus, and rides back down once+ focus leaves; one ride moves a target at a time. Where the path places the+ field, focus moves and first taps arrive without the browser's reveal; a+ claimed tap raises the tap's click on the field afterwards, a synthetic touch+ `PointerEvent` (a `MouseEvent` where none exists), so a caller's `onClick`+ still runs once. A pan the browser makes on its own after a report, as after a+ script's `focus()` that no claim saw, is put back (`watchRevealPan`).- **The surface hook (FR4, FR5):** `useMobileKeyboard(targetRef, options)`(`useMobileKeyboard.ts`) keeps a focused field in a target above thekeyboard. BottomSheet passes its panel with `{move: 'ride', inset: true}`@@ -75,10 +131,26 @@ that times motion with it. Everything here is internal tokeyboard's top, and the content box then rides the rest of the show'scurve. Through the hide the inset stays and the content box rides down towhere the body's scroll rests. At rest the inset drops, the scroll is put- back and the translate clears in one commit. Under a fine pointer, and in a- browser without the VirtualKeyboard API (iOS Safari, Firefox for Android),- nothing of the ride attaches: no guide subscription, and the inset follows- the reports. Safari's and Firefox's reveals are unchanged.+ back and the translate clears in one commit. A busy page reads Chrome's+ report of the keyboard gone after the slide. Until then the content box+ stays where the slide leaves it, and that report commits. Under a fine+ pointer nothing of+ the ride attaches: no guide subscription, and the inset follows the+ reports. A browser without the VirtualKeyboard API (iOS Safari, Firefox for+ Android) publishes no slide: iOS Safari reports the keyboard gone about half+ a second after a blur, once it is down. There, under a coarse pointer, a+ blur that takes the keyboard down rides the content box to where the body's+ scroll rests, on UIKit's keyboard spring (`KEYBOARD_SPRING`) from the blur,+ while the inset stays. The report then drops the inset and puts the scroll+ back in one commit with the translate, so nothing moves. A report of the+ keyboard gone with no ride under way, as after a downward dismissal, glides+ the content to its place on the same spring. A field focused before the+ keyboard is down rides it back up. Focus moving to a select starts no ride:+ iOS puts the select's picker where the keyboard was. Nor does focus moving+ into a frame, an open shadow host or a custom element, whose own field can+ keep the keyboard up. Firefox for Android takes the same path, but reports+ the hide once, at its end, and the content moves at that report (AST-099+ Gap 12). Safari's and Firefox's reveals are unchanged.- **When the keyboard goes:** the body's scroll goes back to where it waswhen the keyboard came up, within the range left once the inset drops. Afield that keeps focus, as after iOS's downward keyboard dismissal, is then@@ -156,8 +228,13 @@ keyboard module measures them from the visual viewport, as in every browserthe keyboard instead of being covered until the report.- Hide: Gboard starts down about `androidKeyboard.hideAfterBlurMs` after theblur and leaves in about 167 ms; the `resize` comes mid-slide. The guide- starts the hide at the blur and takes the `resize` as its confirmation; a- hide nothing predicted (Back, which keeps the focus) rides from its report,+ starts the hide at the blur and takes the `resize` as its confirmation. A+ busy page reads that `resize` after the slide. Until the report of the+ keyboard gone, a report of it partway down, or still up, starts nothing.+ Focus that comes back still turns the hide around. Focus in a frame, an+ open shadow host or a custom element, whose field the guide cannot see,+ leaves the viewport to decide. A hide nothing predicted (Back, which keeps+ the focus) rides from its report,dated back `hideReportLagMs`, the lag measured on blurs. Chrome can reportBack later in the slide, so on Back the content starts down after thekeyboard does.@@ -188,6 +265,8 @@ keyboard module measures them from the visual viewport, as in every browser| ------------------------ | --------------------------------------------------------------------------------------------------------------------- || `keyboardHeight.ts` | The keyboard module: the height, its listeners, the focus routes. || `useMobileKeyboard.ts` | Keeps a focused field in a target above the keyboard: the inset, the reveal, the ride and the dismiss. |+| `keyboardTarget.ts` | The targets: their registry, a docked or scrolling target, and a field's own path. |+| `revealBand.ts` | `distanceIntoBand`: the scroll that brings a box inside a band, shared by the field's and the sheet's reveals. || `keyboardModel.ts` | The clock-free core of the guide: transitions from keyboard reports and focus changes. || `keyboardLayoutGuide.ts` | One guide per window, fed by the keyboard module: the verification timer, the focus handoff. || `rideKeyboard.ts` | Moves an element with the keyboard on the curve its transition publishes, or at once (tests: `rideKeyboard.test.ts`). |diff --git a/packages/core/src/keyboard/__tests__/keyboardTestDouble.ts b/packages/core/src/keyboard/__tests__/keyboardTestDouble.tsnew file mode 100644index 0000000000..1b5568440c--- /dev/null+++ b/packages/core/src/keyboard/__tests__/keyboardTestDouble.ts@@ -0,0 +1,109 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardTestDouble.ts+ * @input vitest, the window's visual viewport and matchMedia+ * @output installKeyboardTestDouble: a stand-in on-screen keyboard that a+ * field's keyboard test drives with one call per keyboard change+ * @position Test helper for the keyboard module and the fields it covers+ */++import {vi} from 'vitest';+import {act} from '@testing-library/react';+import {__resetLayoutViewportForTest} from '../../utils/layoutViewport';++/** A stand-in keyboard over the window's layout viewport. */+export interface KeyboardTestDouble {+ /** The keyboard now covers `cover` px of the layout viewport's bottom. */+ show(cover: number): void;+ /** The keyboard has gone. */+ hide(): void;+ /** Runs the animation frames asked for since, as before a paint. */+ frame(): void;+ /** Puts the window back as it was. */+ restore(): void;+}++/**+ * Installs a visual viewport that shrinks for the keyboard, as Mobile Safari+ * and Chrome on Android do. It also installs a coarse primary pointer unless+ * `coarse` is false. Each change reports in the visual viewport's own `resize`,+ * and the animation frames asked for during it run right after, as before a+ * paint.+ */+export function installKeyboardTestDouble({+ coarse = true,+}: {coarse?: boolean} = {}): KeyboardTestDouble {+ const viewport = Object.assign(new EventTarget(), {+ height: window.innerHeight,+ offsetTop: 0,+ scale: 1,+ });+ Object.defineProperty(window, 'visualViewport', {+ configurable: true,+ value: viewport,+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: query.includes('pointer: coarse') ? coarse : false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ // The page scrolls, so a field in it is revealed by the document.+ const page = document.scrollingElement ?? document.documentElement;+ Object.defineProperty(page, 'scrollHeight', {+ configurable: true,+ value: 3000,+ });+ Object.defineProperty(page, 'clientHeight', {+ configurable: true,+ value: window.innerHeight,+ });+ const frames = new Map<number, FrameRequestCallback>();+ let nextFrame = 1;+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ const id = nextFrame++;+ frames.set(id, callback);+ return id;+ });+ vi.stubGlobal('cancelAnimationFrame', (id: number) => {+ frames.delete(id);+ });+ const frame = () => {+ act(() => {+ for (let round = 0; round < 5 && frames.size > 0; round++) {+ const due = [...frames.values()];+ frames.clear();+ for (const callback of due) {+ callback(performance.now());+ }+ }+ });+ };+ const report = (height: number) => {+ viewport.height = height;+ act(() => {+ viewport.dispatchEvent(new Event('resize'));+ });+ frame();+ };+ return {+ show: cover => report(window.innerHeight - cover),+ hide: () => report(window.innerHeight),+ frame,+ restore: () => {+ Reflect.deleteProperty(page, 'scrollHeight');+ Reflect.deleteProperty(page, 'clientHeight');+ Reflect.deleteProperty(window, 'visualViewport');+ __resetLayoutViewportForTest();+ vi.unstubAllGlobals();+ },+ };+}diff --git a/packages/core/src/keyboard/keyboardChromium.test.ts b/packages/core/src/keyboard/keyboardChromium.test.tsindex 0636167b45..8fa8db3f20 100644--- a/packages/core/src/keyboard/keyboardChromium.test.ts+++ b/packages/core/src/keyboard/keyboardChromium.test.ts@@ -79,6 +79,7 @@ describe('the keyboard layout guide on Chrome', () => {Reflect.deleteProperty(window, 'visualViewport');Reflect.deleteProperty(window.navigator, 'virtualKeyboard');vi.unstubAllGlobals();+ vi.restoreAllMocks();vi.useRealTimers();});@@ -155,8 +156,49 @@ describe('the keyboard layout guide on Chrome', () => {expect(seen.at(-1)).toBe(hide);});- it('checks a prediction Chrome never confirms 150 ms after its slide ends', () => {- // One clock for event times and the guide's own reads, as in a browser.+ it.each([+ ['a frame', () => document.createElement('iframe')],+ [+ 'a shadow host',+ () => {+ const host = document.createElement('x-editor');+ host+ .attachShadow({mode: 'open'})+ .append(document.createElement('input'));+ return host;+ },+ ],+ ] as const)(+ 'checks a prediction Chrome never confirms 150 ms after its slide ends when focus moves into %s, whose own field the guide cannot see',+ (_, make) => {+ // One clock for event times and the guide's own reads, as in a browser.+ vi.spyOn(window.performance, 'now').mockImplementation(() => Date.now());+ const container = make();+ document.body.append(container);+ a.focus();+ report(312);+ vi.advanceTimersByTime(1000);+ const inner = container.shadowRoot?.querySelector('input');+ if (inner != null) {+ inner.focus();+ } else {+ container.focus();+ }+ expect(document.activeElement).toBe(container);+ const hide = seen.at(-1);+ expect(hide).toMatchObject({kind: 'hide', to: 0, predicted: true});+ // The keyboard stays up for the field inside: Chrome never reports the+ // hide. Once the slide should have ended, and 150 ms more, the guide+ // believes the viewport.+ const due = (hide?.start ?? 0) + androidKeyboard.hideMs + 150;+ vi.advanceTimersByTime(due - Date.now() - 1);+ expect(seen.at(-1)).toBe(hide);+ vi.advanceTimersByTime(2);+ expect(seen.at(-1)).toMatchObject({kind: 'show', to: 312});+ },+ );++ it('turns nothing back once a hide it predicted from a blur has started: Chrome’s late reports of the keyboard partway down or still up wait for its report of the keyboard gone', () => {vi.spyOn(window.performance, 'now').mockImplementation(() => Date.now());a.focus();report(312);@@ -164,13 +206,21 @@ describe('the keyboard layout guide on Chrome', () => {a.blur();const hide = seen.at(-1);expect(hide).toMatchObject({kind: 'hide', to: 0, predicted: true});- // The keyboard stays up: Chrome never reports the hide. Once the slide- // should have ended, and 150 ms more, the guide believes the viewport.- const due = (hide?.start ?? 0) + androidKeyboard.hideMs + 150;- vi.advanceTimersByTime(due - Date.now() - 1);+ // Chrome can report the keyboard partway down during the slide.+ vi.advanceTimersByTime(60);+ report(290);+ expect(seen.at(-1)).toBe(hide);+ // A busy page reads Chrome's reports late, after the slide has ended.+ vi.advanceTimersByTime(340);+ report(268);+ expect(seen.at(-1)).toBe(hide);+ // The check after the slide reads that report, not a keyboard coming up.+ vi.advanceTimersByTime(androidKeyboard.hideMs + 200);expect(seen.at(-1)).toBe(hide);- vi.advanceTimersByTime(2);- expect(seen.at(-1)).toMatchObject({kind: 'show', to: 312});+ // Chrome's report of the keyboard gone confirms the hide.+ report(0);+ expect(seen.at(-1)).toBe(hide);+ expect(getKeyboardLayoutGuide(window).transition.predicted).toBe(false);});it('rides a hide nothing predicted (Back) down from its report, dated back to Gboard’s start', () => {@@ -193,6 +243,39 @@ describe('the keyboard layout guide on Chrome', () => {);});+ it('waits for Chrome’s report of the keyboard gone when focus moves to a select, whose picker Chrome opens over the page', () => {+ vi.spyOn(window.performance, 'now').mockImplementation(() => Date.now());+ const select = document.createElement('select');+ select.append(new Option('One'), new Option('Two'));+ document.body.append(select);+ a.focus();+ report(312);+ vi.advanceTimersByTime(1000);+ select.focus();+ const hide = seen.at(-1);+ expect(hide).toMatchObject({kind: 'hide', to: 0, predicted: true});+ // The picker brings no keyboard back. A busy page reads Chrome's report+ // of the keyboard partway down after the slide and the check.+ vi.advanceTimersByTime(400);+ report(268);+ expect(seen.at(-1)).toBe(hide);+ report(0);+ expect(seen.at(-1)).toBe(hide);+ expect(getKeyboardLayoutGuide(window).transition.predicted).toBe(false);+ });++ it('rides a keyboard back up after a hide Chrome reported (Back), when the field that kept focus brings it back', () => {+ a.focus();+ report(312);+ vi.advanceTimersByTime(1000);+ report(0);+ expect(seen.at(-1)).toMatchObject({kind: 'hide', to: 0, predicted: false});+ vi.advanceTimersByTime(1000);+ // A tap on the focused field brings the keyboard back with no focus event.+ report(312);+ expect(seen.at(-1)).toMatchObject({kind: 'show', to: 312, animated: true});+ });+it.each([['a select',diff --git a/packages/core/src/keyboard/keyboardHeight.test.ts b/packages/core/src/keyboard/keyboardHeight.test.tsindex 81b6d5d69d..d621313f1f 100644--- a/packages/core/src/keyboard/keyboardHeight.test.ts+++ b/packages/core/src/keyboard/keyboardHeight.test.ts@@ -14,12 +14,18 @@ import path from 'node:path';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {act} from '@testing-library/react';import {bringsUpKeyboard, getKeyboardLayoutGuide} from './keyboardLayoutGuide';+import {+ __resetClickGuardForTest,+ CLICK_GUARD_WINDOW_MS,+} from '../utils/clickGuard';import {__resetLayoutViewportForTest,layoutViewportHeight,} from '../utils/layoutViewport';import {+ claimTapFocus,findTextEntryControl,+ focusAtPoint,getKeyboardHeight,isKeyboardMeasurable,isTextEntryControl,@@ -65,6 +71,7 @@ afterEach(() => {Reflect.deleteProperty(document.documentElement, key);}__resetLayoutViewportForTest();+ __resetClickGuardForTest();vi.unstubAllGlobals();vi.restoreAllMocks();vi.unstubAllGlobals();@@ -774,3 +781,255 @@ describe('the text-entry predicate', () => {}});});++describe('the tap route (FR4)', () => {+ // A touch event as the browser raises it: its fingers, and cancelable.+ const touchEvent = (+ type: string,+ points: {x: number; y: number}[],+ changed = points,+ ) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const list = (ps: {x: number; y: number}[]) =>+ ps.map((p, identifier) => ({identifier, clientX: p.x, clientY: p.y}));+ Object.assign(event, {+ touches: list(points),+ changedTouches: list(changed),+ });+ return event;+ };++ function setup() {+ const region = document.createElement('div');+ const field = document.createElement('div');+ region.append(field);+ document.body.append(region);+ const deliver = vi.fn();+ const stop = claimTapFocus(region, {+ claim: target => (target === field ? field : null),+ deliver,+ });+ return {region, field, deliver, stop};+ }++ it('delivers a tap on a claimed field itself, and cancels the browser\u2019s', () => {+ const {region, field, deliver, stop} = setup();+ field.dispatchEvent(touchEvent('touchstart', [{x: 10, y: 10}]));+ const end = touchEvent('touchend', [], [{x: 12, y: 11}]);+ field.dispatchEvent(end);+ expect(end.defaultPrevented).toBe(true);+ expect(deliver).toHaveBeenCalledWith(field, 12, 11, expect.anything());+ stop();+ region.remove();+ });++ it('leaves a touch that moves past the scroll slop, or a second finger, to the browser', () => {+ const {region, field, deliver, stop} = setup();+ field.dispatchEvent(touchEvent('touchstart', [{x: 10, y: 10}]));+ field.dispatchEvent(touchEvent('touchmove', [{x: 10, y: 30}]));+ const moved = touchEvent('touchend', [], [{x: 10, y: 30}]);+ field.dispatchEvent(moved);+ expect(moved.defaultPrevented).toBe(false);++ field.dispatchEvent(+ touchEvent('touchstart', [+ {x: 10, y: 10},+ {x: 40, y: 10},+ ]),+ );+ const pinch = touchEvent('touchend', [], [{x: 10, y: 10}]);+ field.dispatchEvent(pinch);+ expect(pinch.defaultPrevented).toBe(false);+ expect(deliver).not.toHaveBeenCalled();+ stop();+ region.remove();+ });++ it('listens on the region only, and follows a touch only while it is down', () => {+ const {region, field, stop} = setup();+ const add = vi.spyOn(region, 'addEventListener');+ const remove = vi.spyOn(region, 'removeEventListener');+ const documentAdd = vi.spyOn(document, 'addEventListener');+ field.dispatchEvent(touchEvent('touchstart', [{x: 10, y: 10}]));+ expect(add.mock.calls.map(([type]) => type)).toEqual([+ 'touchmove',+ 'touchend',+ 'touchcancel',+ ]);+ field.dispatchEvent(touchEvent('touchend', [], [{x: 10, y: 10}]));+ expect(remove.mock.calls.map(([type]) => type)).toEqual([+ 'touchmove',+ 'touchend',+ 'touchcancel',+ ]);+ // No document listener: the swallower of the mouse events Safari may+ // still send rides the window's one shared input stream.+ expect(documentAdd).not.toHaveBeenCalled();+ stop();+ region.remove();+ });++ it('swallows the mouse events Safari still sends for a delivered tap, wherever they land, until its click', () => {+ const {region, field, deliver, stop} = setup();+ const elsewhere = document.createElement('button');+ document.body.append(elsewhere);+ const pressed = vi.fn();+ elsewhere.addEventListener('mousedown', pressed);+ elsewhere.addEventListener('click', pressed);+ // Safari's events for a tap carry its click count.+ const mouse = (type: string) => {+ const event = new MouseEvent(type, {+ bubbles: true,+ cancelable: true,+ detail: 1,+ });+ elsewhere.dispatchEvent(event);+ return event;+ };+ field.dispatchEvent(touchEvent('touchstart', [{x: 10, y: 10}]));+ field.dispatchEvent(touchEvent('touchend', [], [{x: 12, y: 11}]));+ expect(deliver).toHaveBeenCalledTimes(1);+ // Aimed at what is under the finger now.+ expect(mouse('mousedown').defaultPrevented).toBe(true);+ expect(mouse('click').defaultPrevented).toBe(true);+ expect(pressed).not.toHaveBeenCalled();+ // The tap's click ends it.+ expect(mouse('click').defaultPrevented).toBe(false);+ expect(pressed).toHaveBeenCalledTimes(1);+ stop();+ elsewhere.remove();+ region.remove();+ });++ it('lets go when no click comes and a new press starts, or after the click guard’s window', () => {+ const {region, field, stop} = setup();+ const mousedown = () => {+ const event = new MouseEvent('mousedown', {+ bubbles: true,+ cancelable: true,+ detail: 1,+ });+ document.body.dispatchEvent(event);+ return event.defaultPrevented;+ };+ field.dispatchEvent(touchEvent('touchstart', [{x: 10, y: 10}]));+ field.dispatchEvent(touchEvent('touchend', [], [{x: 10, y: 10}]));+ // A new press anywhere: a touch's or a mouse's, which starts with its+ // pointerdown.+ document.body.dispatchEvent(new Event('pointerdown', {bubbles: true}));+ expect(mousedown()).toBe(false);++ field.dispatchEvent(touchEvent('touchstart', [{x: 10, y: 10}]));+ field.dispatchEvent(touchEvent('touchend', [], [{x: 10, y: 10}]));+ // A key's own click (detail 0) goes through.+ const keyClick = new MouseEvent('click', {bubbles: true, cancelable: true});+ document.body.dispatchEvent(keyClick);+ expect(keyClick.defaultPrevented).toBe(false);++ // The guard ends after its window, also when the route goes first.+ vi.useFakeTimers();+ field.dispatchEvent(touchEvent('touchstart', [{x: 10, y: 10}]));+ field.dispatchEvent(touchEvent('touchend', [], [{x: 10, y: 10}]));+ stop();+ expect(mousedown()).toBe(true);+ vi.advanceTimersByTime(CLICK_GUARD_WINDOW_MS);+ expect(mousedown()).toBe(false);+ vi.useRealTimers();+ region.remove();+ });++ it('leaves a touch outside what the caller claims to the browser', () => {+ const {region, deliver, stop} = setup();+ region.dispatchEvent(touchEvent('touchstart', [{x: 10, y: 10}]));+ const end = touchEvent('touchend', [], [{x: 10, y: 10}]);+ region.dispatchEvent(end);+ expect(end.defaultPrevented).toBe(false);+ expect(deliver).not.toHaveBeenCalled();+ stop();+ region.remove();+ });+});++describe('the caret a claimed tap places', () => {+ // Installs (or, with undefined, removes) one caret-from-point API on the+ // document, as each engine has its own.+ function stubCaretApi(+ name: 'caretPositionFromPoint' | 'caretRangeFromPoint',+ value: unknown,+ ) {+ Object.defineProperty(document, name, {configurable: true, value});+ }++ function editable(): {element: HTMLElement; text: Text} {+ const element = document.createElement('div');+ element.setAttribute('contenteditable', 'true');+ // jsdom does not compute isContentEditable.+ Object.defineProperty(element, 'isContentEditable', {value: true});+ const text = document.createTextNode('Hello there');+ element.append(text);+ document.body.append(element);+ return {element, text};+ }++ afterEach(() => {+ Reflect.deleteProperty(document, 'caretPositionFromPoint');+ Reflect.deleteProperty(document, 'caretRangeFromPoint');+ document.body.replaceChildren();+ });++ it('reads the standard caretPositionFromPoint, the only one Firefox has', () => {+ const {element, text} = editable();+ stubCaretApi(+ 'caretPositionFromPoint',+ vi.fn(() => ({offsetNode: text, offset: 3})),+ );++ focusAtPoint(element, 20, 10);++ expect(document.activeElement).toBe(element);+ const selection = document.getSelection();+ expect(selection?.anchorNode).toBe(text);+ expect(selection?.anchorOffset).toBe(3);+ expect(selection?.isCollapsed).toBe(true);+ });++ it('puts a text control\u2019s caret where the browser maps the point into it, or after its text', () => {+ const textarea = document.createElement('textarea');+ textarea.value = 'A long draft';+ document.body.append(textarea);+ const focus = vi.spyOn(textarea, 'focus');+ stubCaretApi(+ 'caretPositionFromPoint',+ vi.fn(() => ({offsetNode: textarea, offset: 3})),+ );+ focusAtPoint(textarea, 20, 10);+ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ expect(document.activeElement).toBe(textarea);+ expect([textarea.selectionStart, textarea.selectionEnd]).toEqual([3, 3]);++ textarea.blur();+ stubCaretApi(+ 'caretPositionFromPoint',+ vi.fn(() => null),+ );+ focusAtPoint(textarea, 20, 10);+ expect([textarea.selectionStart, textarea.selectionEnd]).toEqual([12, 12]);+ });++ it('falls back to caretRangeFromPoint where only WebKit\u2019s exists', () => {+ const {element, text} = editable();+ stubCaretApi(+ 'caretRangeFromPoint',+ vi.fn(() => {+ const range = document.createRange();+ range.setStart(text, 5);+ range.collapse(true);+ return range;+ }),+ );++ focusAtPoint(element, 20, 10);++ expect(document.getSelection()?.anchorOffset).toBe(5);+ });+});diff --git a/packages/core/src/keyboard/keyboardHeight.ts b/packages/core/src/keyboard/keyboardHeight.tsindex ef4cb6c8d4..da7fc06b0b 100644--- a/packages/core/src/keyboard/keyboardHeight.ts+++ b/packages/core/src/keyboard/keyboardHeight.ts@@ -16,9 +16,11 @@* SYNC: When modified, update /packages/core/src/keyboard/README.md*/+import {armClickGuard} from '../utils/clickGuard';import {subscribeInput} from '../utils/inputStream';import {isNode} from '../utils/nodeType';import {layoutViewportHeight} from '../utils/layoutViewport';+import {caretAt} from '../utils/selectionLock';// A shortfall smaller than this is rounding, not a keyboard.export const KEYBOARD_EPSILON = 1;@@ -537,3 +539,169 @@ export function watchRevealPan(stop: stopTouchStarts,};}++// A touch that moves this far is the browser's to scroll, not a tap on a+// field. Safari claims a touch for scrolling past 10 px.+const TAP_SLOP_PX = 10;++/** The caller's rules for claimTapFocus. */+export interface ClaimTapFocusOptions {+ /** The control a touch on `target` would focus, when this caller claims it. */+ claim: (target: EventTarget | null) => HTMLElement | null;+ /**+ * Focuses the claimed control for a tap that ended at (x, y) in the+ * viewport. `touch` is the tap's finger: its screen point and identifier.+ */+ deliver: (+ control: HTMLElement,+ x: number,+ y: number,+ touch: {screenX: number; screenY: number; identifier: number},+ ) => void;+}++/**+ * The tap route. `deliver` focuses a one-finger tap on `region` that `claim`+ * accepts, such as a field without focus, instead of the browser. The+ * browser's own focus would reveal the field by scrolling the document. The+ * route prevents the tap's default at its end. The shared click guard then+ * takes the mouse events Safari may still send for the tap. The browser keeps a+ * touch that moves past the scroll slop, and a second finger. Returns a+ * cleanup.+ *+ * @example+ * ```+ * const stop = claimTapFocus(region, {+ * claim: target => editableWithoutFocus(target),+ * deliver: (field, x, y) => focusAtPoint(field, x, y),+ * });+ * ```+ */+export function claimTapFocus(+ region: HTMLElement,+ {claim, deliver}: ClaimTapFocusOptions,+): () => void {+ // The touch the route follows, and the listeners that follow it: on the+ // region only, and only while that touch is down.+ let start: {x: number; y: number; control: HTMLElement} | null = null;+ // On the iOS simulator, a tap held about 250 ms still gets its mousedown and+ // click. They come a few ms after its touchend, though the route cancelled+ // that touchend. They go to whatever is under the finger by then, which can+ // take the focus the tap delivered. The click guard takes them+ // (utils/clickGuard.ts).+ const stopFollowing = () => {+ start = null;+ region.removeEventListener('touchmove', onMove);+ region.removeEventListener('touchend', onEnd);+ region.removeEventListener('touchcancel', stopFollowing);+ };+ function onMove(event: TouchEvent) {+ const touch = event.touches[0];+ if (+ start == null ||+ event.touches.length !== 1 ||+ touch == null ||+ Math.hypot(touch.clientX - start.x, touch.clientY - start.y) > TAP_SLOP_PX+ ) {+ stopFollowing();+ }+ }+ function onEnd(event: TouchEvent) {+ const touch = event.changedTouches[0];+ const tap = start;+ stopFollowing();+ // Still the same field, still without focus.+ if (+ tap == null ||+ touch == null ||+ !event.cancelable ||+ claim(tap.control) !== tap.control+ ) {+ return;+ }+ event.preventDefault();+ deliver(tap.control, touch.clientX, touch.clientY, touch);+ armClickGuard(region.ownerDocument, {takesLateMouse: true});+ }+ const onStart = (event: TouchEvent) => {+ if (start != null) {+ // Another finger joined the one the route follows: not a tap.+ stopFollowing();+ return;+ }+ const touch = event.touches[0];+ const control =+ event.touches.length === 1 && touch != null ? claim(event.target) : null;+ if (control == null || touch == null) {+ return;+ }+ start = {x: touch.clientX, y: touch.clientY, control};+ region.addEventListener('touchmove', onMove, {passive: true});+ // Not passive: only the end of the touch can still cancel the browser's+ // focus and its reveal.+ region.addEventListener('touchend', onEnd);+ region.addEventListener('touchcancel', stopFollowing);+ };+ region.addEventListener('touchstart', onStart, {passive: true});+ return () => {+ stopFollowing();+ region.removeEventListener('touchstart', onStart);+ };+}++function isTextControl(+ element: Element,+): element is HTMLTextAreaElement | HTMLInputElement {+ return (+ element instanceof HTMLTextAreaElement ||+ element instanceof HTMLInputElement+ );+}++/**+ * A text control's caret for a tap at (x, y). It is where the browser maps+ * the point inside the control. Where the browser maps none, it is after the+ * text, the convention for a focus without a point. A control with no text+ * selection stays as it is.+ */+function placeTextControlCaret(+ control: HTMLTextAreaElement | HTMLInputElement,+ x: number,+ y: number,+) {+ if (control.selectionStart == null) {+ return;+ }+ const caret = caretAt(control.ownerDocument, x, y, []);+ const offset =+ caret != null && caret.node === control+ ? caret.offset+ : control.value.length;+ control.setSelectionRange(offset, offset);+}++/**+ * Focuses without Safari's reveal and puts the caret under the finger.+ * Exported for its tests.+ */+export function focusAtPoint(editable: HTMLElement, x: number, y: number) {+ editable.focus({preventScroll: true});+ if (isTextControl(editable)) {+ placeTextControlCaret(editable, x, y);+ return;+ }+ const doc = editable.ownerDocument;+ const caret = caretAt(doc, x, y, []);+ if (+ caret != null &&+ editable.isContentEditable &&+ editable.contains(caret.node)+ ) {+ const range = doc.createRange();+ range.setStart(caret.node, caret.offset);+ range.collapse(true);+ const selection = doc.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ }+}diff --git a/packages/core/src/keyboard/keyboardLayoutGuide.ts b/packages/core/src/keyboard/keyboardLayoutGuide.tsindex 5bcd168a62..af83cf609a 100644--- a/packages/core/src/keyboard/keyboardLayoutGuide.ts+++ b/packages/core/src/keyboard/keyboardLayoutGuide.ts@@ -96,6 +96,22 @@ function opensPickerOverPage(target: EventTarget | null): boolean {);}+/**+ * Whether `target` can hold a field the page cannot see: a frame, an open+ * shadow host or a custom element. Focus on a field inside one leaves+ * `document.activeElement` on it.+ */+export function hidesField(target: Element): boolean {+ return (+ target.tagName === 'IFRAME' ||+ target.tagName === 'FRAME' ||+ target.tagName === 'OBJECT' ||+ target.tagName === 'EMBED' ||+ target.shadowRoot != null ||+ target.tagName.includes('-')+ );+}+const guides = new WeakMap<Window, KeyboardLayoutGuide>();/**@@ -117,6 +133,14 @@ const guides = new WeakMap<Window, KeyboardLayoutGuide>();* reported while a field that just got focus still has it waits until the* move settles.*+ * A busy page reads Chrome's reports late, after Gboard's slide. So once a+ * hide predicted from a blur is under way, a report of the keyboard partway+ * down, or still up, starts nothing. Only the report of the keyboard gone+ * confirms the hide. Focus that comes back still turns it around. Focus in a+ * frame, an open shadow host or a custom element can keep up a keyboard the+ * guide cannot see. There the viewport decides, as before. A closed shadow+ * root on a built-in element reads as nothing focused.+ ** @example* ```* const guide = getKeyboardLayoutGuide(window);@@ -140,6 +164,25 @@ function createGuide(win: Window): KeyboardLayoutGuide {let model: KeyboardModel = createKeyboardModel(getKeyboardHeight(win));let verifyTimer: ReturnType<typeof setTimeout> | null = null;let detach: (() => void) | null = null;+ // Whether focusing `target` keeps an input view where the keyboard is. On+ // iOS, a select's picker or a date or time field's picker takes the+ // keyboard's place. Chrome on Android opens it over the page, and the+ // keyboard goes away.+ const keepsInputView = (target: EventTarget | null): boolean =>+ bringsUpKeyboard(target) &&+ !(profile === 'chromium' && opensPickerOverPage(target));+ // Whether a hide predicted from a blur is under way with nothing focused+ // that can keep a keyboard up. Then only Chrome's report of the keyboard+ // gone counts.+ const awaitsHide = (): boolean => {+ const active = win.document.activeElement;+ return (+ model.transition.kind === 'hide' &&+ model.transition.predicted &&+ !keepsInputView(active) &&+ !(active != null && hidesField(active))+ );+ };const publish = (transition: KeyboardTransition | null) => {if (transition == null) {@@ -161,7 +204,11 @@ function createGuide(win: Window): KeyboardLayoutGuide {verifyTimer = setTimeout(() => {verifyTimer = null;- publish(model.verify(getKeyboardHeight(win), win.performance.now()));+ const inset = getKeyboardHeight(win);+ if (inset != null && inset > 0.5 && awaitsHide()) {+ return;+ }+ publish(model.verify(inset, win.performance.now()));},Math.max(0, due - win.performance.now()),);@@ -170,13 +217,6 @@ function createGuide(win: Window): KeyboardLayoutGuide {const attach = () => {profile = keyboardProfileOf(win);model = createKeyboardModel(getKeyboardHeight(win));- // Whether focusing `target` keeps an input view where the keyboard is. On- // iOS, a select's picker or a date or time field's picker takes the- // keyboard's place. Chrome on Android opens it over the page, and the- // keyboard goes away.- const keepsInputView = (target: EventTarget | null): boolean =>- bringsUpKeyboard(target) &&- !(profile === 'chromium' && opensPickerOverPage(target));// When a field that brings up a keyboard last gained focus.let keyboardFocusAt = -Infinity;let handoffTimer: ReturnType<typeof setTimeout> | null = null;@@ -205,6 +245,9 @@ function createGuide(win: Window): KeyboardLayoutGuide {}, settled - time);return null;}+ if (height > 0.5 && awaitsHide()) {+ return null;+ }return model.report(height, time);};const onReport = (event: KeyboardHeightEvent) => {diff --git a/packages/core/src/keyboard/keyboardTarget.guide.test.ts b/packages/core/src/keyboard/keyboardTarget.guide.test.tsnew file mode 100644index 0000000000..7577b78ae5--- /dev/null+++ b/packages/core/src/keyboard/keyboardTarget.guide.test.ts@@ -0,0 +1,156 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardTarget.guide.test.ts+ * @input keyboardTarget.ts with a stand-in layout guide and a stand-in+ * animator, a stand-in visual viewport and stubbed boxes+ * @output Proves a docked ride on the guide's slides. A field that loses+ * focus while the keyboard shows rides its bar down on the hide's slide. No+ * set cuts the slide at its start+ * @position Keyboard module tests+ */++import {afterEach, beforeEach, expect, it, vi} from 'vitest';+import {act} from '@testing-library/react';+import {keyboard as androidKeyboard} from '../motion/android';+import type {KeyboardTransition} from './keyboardModel';+import type * as LayoutGuideModule from './keyboardLayoutGuide';+import type * as AnimatorModule from '../motion/animator';+import {+ installKeyboardTestDouble,+ type KeyboardTestDouble,+} from './__tests__/keyboardTestDouble';++const guideListeners = new Set<(transition: KeyboardTransition) => void>();+// The inset the stand-in guide reports: the last published slide's end.+const guideState = {inset: 0};+// A stand-in animator that keeps the y it was last sent, and draws it on the+// bar as the real one does.+const animator = vi.hoisted(() => {+ const state = {y: 0, element: null as HTMLElement | null};+ const draw = (y: number) => {+ state.y = y;+ if (state.element != null) {+ state.element.style.translate = y === 0 ? '' : `0px ${y}px`;+ }+ };+ return {+ state,+ set: vi.fn((values: {y?: number}) => draw(values.y ?? state.y)),+ play: vi.fn(+ (curves: {y?: {duration: number; at: (t: number) => number}}) => {+ if (curves.y != null) {+ draw(curves.y.at(curves.y.duration));+ }+ return {finished: Promise.resolve(true)};+ },+ ),+ animate: vi.fn(() => ({finished: Promise.resolve(true)})),+ get: vi.fn(() => state.y),+ };+});++vi.mock('./keyboardLayoutGuide', async importOriginal => {+ const actual = await importOriginal<typeof LayoutGuideModule>();+ return {+ ...actual,+ keyboardProfileOf: () => 'chromium',+ getKeyboardLayoutGuide: () => ({+ get inset() {+ return guideState.inset;+ },+ subscribe: (listener: (transition: KeyboardTransition) => void) => {+ guideListeners.add(listener);+ return () => guideListeners.delete(listener);+ },+ }),+ };+});++vi.mock('../motion/animator', async importOriginal => {+ const actual = await importOriginal<typeof AnimatorModule>();+ return {...actual, animatorFor: () => animator};+});++const {keepFieldAboveKeyboard} = await import('./keyboardTarget');++let keyboard: KeyboardTestDouble;++const slide = (kind: 'show' | 'hide', to: number): KeyboardTransition => ({+ kind,+ from: kind === 'show' ? 0 : 300,+ to,+ start: 1000,+ velocity: 0,+ animated: true,+ predicted: false,+ curve:+ kind === 'show'+ ? {durationMs: androidKeyboard.showMs, points: androidKeyboard.showCurve}+ : {durationMs: androidKeyboard.hideMs, points: androidKeyboard.hideCurve},+});++function publish(transition: KeyboardTransition) {+ guideState.inset = transition.to;+ act(() => {+ for (const listener of [...guideListeners]) {+ listener(transition);+ }+ });+ keyboard.frame();+}++beforeEach(() => {+ keyboard = installKeyboardTestDouble();+ vi.spyOn(performance, 'now').mockReturnValue(1000);+});++afterEach(() => {+ keyboard.restore();+ guideListeners.clear();+ guideState.inset = 0;+ animator.state.y = 0;+ animator.state.element = null;+ document.body.innerHTML = '';+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++it("rides a blurred field's bar down on the hide's slide, never cutting it with a set", () => {+ const bottom = window.innerHeight;+ const bar = document.createElement('div');+ bar.style.position = 'fixed';+ const input = document.createElement('input');+ bar.append(input);+ document.body.append(bar);+ animator.state.element = bar;+ // Where the bar and its field draw: their layout, moved by the ride.+ vi.spyOn(bar, 'getBoundingClientRect').mockImplementation(+ () => new DOMRect(0, bottom - 60 + animator.state.y, 300, 60),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(+ () => new DOMRect(0, bottom - 50 + animator.state.y, 300, 40),+ );+ const stop = keepFieldAboveKeyboard(input);+ act(() => input.focus());+ keyboard.frame();+ publish(slide('show', 300));+ expect(animator.play).toHaveBeenCalled();+ // The field loses focus while the keyboard still shows, and that moves+ // nothing until the keyboard goes.+ keyboard.show(300);+ animator.set.mockClear();+ animator.play.mockClear();+ act(() => input.blur());+ expect(animator.set).not.toHaveBeenCalled();+ expect(animator.play).not.toHaveBeenCalled();+ publish(slide('hide', 0));+ // The bar rides to rest on the hide's slide, and nothing sets it there at+ // the slide's start.+ expect(animator.play).toHaveBeenCalledTimes(1);+ expect(animator.set).not.toHaveBeenCalled();+ // The stopped ride no longer listens: a later slide moves nothing.+ publish(slide('show', 300));+ expect(animator.play).toHaveBeenCalledTimes(1);+ stop();+});diff --git a/packages/core/src/keyboard/keyboardTarget.test.ts b/packages/core/src/keyboard/keyboardTarget.test.tsnew file mode 100644index 0000000000..ac2992601a--- /dev/null+++ b/packages/core/src/keyboard/keyboardTarget.test.ts@@ -0,0 +1,1300 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardTarget.test.ts+ * @input keyboardTarget.ts, a stand-in visual viewport, stubbed boxes and a+ * coarse pointer+ * @output Tests for the keyboard targets: where a field is, the reveal by its+ * scroller, the docked ride, the stand-down inside a target and the claim+ * @position Keyboard module tests+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {act} from '@testing-library/react';+import {animatorFor} from '../motion/animator';+import {__resetLayoutViewportForTest} from '../utils/layoutViewport';+import {+ FIELD_OFFSET,+ coveredBy,+ dockedAncestor,+ followKeyboard,+ keepFieldAboveKeyboard,+ nearestScroller,+ registerKeyboardTarget,+} from './keyboardTarget';++type FakeViewport = EventTarget & {+ height: number;+ offsetTop: number;+ scale: number;+};++let viewport: FakeViewport;+let isCoarse = true;+const stops: (() => void)[] = [];+const frames = new Map<number, FrameRequestCallback>();+let nextFrame = 1;++/** Runs the frames the module asked for, as the browser does before paint. */+function runFrames() {+ act(() => {+ for (let round = 0; round < 5 && frames.size > 0; round++) {+ const due = [...frames.values()];+ frames.clear();+ for (const callback of due) {+ callback(performance.now());+ }+ }+ });+}++/** The keyboard now covers `cover` px of the layout viewport's bottom. */+function keyboard(cover: number) {+ viewport.height = window.innerHeight - cover;+ act(() => {+ viewport.dispatchEvent(new Event('resize'));+ });+ runFrames();+}++/** Focuses `element`, then lets the next frame run. */+function focusOn(element: HTMLElement) {+ act(() => element.focus());+ runFrames();+}++// A box laid out from `data-top` and `data-height`, moved by its own inline+// translate and its ancestors', as a browser draws a ridden element.+function translateY(element: Element | null): number {+ let y = 0;+ for (+ let node = element;+ node instanceof HTMLElement;+ node = node.parentElement+ ) {+ const match = /^\S+\s+(-?[\d.]+)px/.exec(node.style.translate);+ y += match == null ? 0 : Number(match[1]);+ // A transform the app sets, as the matrix a browser computes.+ const matrix = /^matrix\(([^)]*)\)$/.exec(node.style.transform);+ y += matrix == null ? 0 : Number((matrix[1] ?? '').split(',')[5]);+ }+ return y;+}++// How far the element's scrolling ancestors have scrolled it up.+function scrolledBy(element: Element): number {+ let y = 0;+ for (+ let node = element.parentElement;+ node != null;+ node = node.parentElement+ ) {+ if (node.hasAttribute('data-top')) {+ y += node.scrollTop;+ }+ }+ return y;+}++function boxOf(element: Element): DOMRect {+ const top = Number(element.getAttribute('data-top') ?? 0);+ const height = Number(element.getAttribute('data-height') ?? 0);+ const y = top + translateY(element) - scrolledBy(element);+ return new DOMRect(0, y, 300, height);+}++function element(+ tag: string,+ box: {top: number; height: number} | null,+ style: Partial<CSSStyleDeclaration> = {},+): HTMLElement {+ const node = document.createElement(tag);+ if (box != null) {+ node.setAttribute('data-top', String(box.top));+ node.setAttribute('data-height', String(box.height));+ }+ Object.assign(node.style, style);+ return node;+}++function track(stop: () => void) {+ stops.push(stop);+ return stop;+}++beforeEach(() => {+ isCoarse = true;+ frames.clear();+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ const id = nextFrame++;+ frames.set(id, callback);+ return id;+ });+ vi.stubGlobal('cancelAnimationFrame', (id: number) => {+ frames.delete(id);+ });+ viewport = Object.assign(new EventTarget(), {+ height: window.innerHeight,+ offsetTop: 0,+ scale: 1,+ });+ Object.defineProperty(window, 'visualViewport', {+ configurable: true,+ value: viewport,+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: query.includes('pointer: coarse') ? isCoarse : false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(+ function (this: Element) {+ return boxOf(this);+ },+ );+ pageScrollRange(3000);+});++/** The page's own scroll range: its content `height` in a viewport-tall box. */+function pageScrollRange(height: number) {+ const page = document.scrollingElement ?? document.documentElement;+ Object.defineProperty(page, 'scrollHeight', {+ configurable: true,+ value: height,+ });+ Object.defineProperty(page, 'clientHeight', {+ configurable: true,+ value: window.innerHeight,+ });+}++afterEach(() => {+ for (const stop of stops.splice(0)) {+ stop();+ }+ document.body.innerHTML = '';+ const page = document.scrollingElement ?? document.documentElement;+ Reflect.deleteProperty(page, 'scrollHeight');+ Reflect.deleteProperty(page, 'clientHeight');+ Reflect.deleteProperty(window, 'visualViewport');+ __resetLayoutViewportForTest();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('where a field is', () => {+ it('finds its nearest scroller, or else the document', () => {+ const list = element('div', {top: 0, height: 400}, {overflowY: 'auto'});+ const input = element('input', {top: 100, height: 40});+ list.append(input);+ document.body.append(list);+ Object.defineProperty(list, 'scrollHeight', {value: 900});+ Object.defineProperty(list, 'clientHeight', {value: 400});+ expect(nearestScroller(input)).toBe(list);++ const loose = element('input', {top: 100, height: 40});+ document.body.append(loose);+ expect(nearestScroller(loose)).toBe(+ document.scrollingElement ?? document.documentElement,+ );+ });++ it("counts a fixed bar whose bottom sits at the viewport's bottom as docked, and not one floating above it", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ expect(dockedAncestor(input)).toBe(bar);++ const floating = element(+ 'div',+ {top: bottom - 70, height: 50},+ {position: 'fixed'},+ );+ const inner = element('input', {top: bottom - 65, height: 40});+ floating.append(inner);+ document.body.append(floating);+ expect(dockedAncestor(inner)).toBeNull();+ });++ it('never counts a container that fills the viewport, or a fixed header at the top, as docked', () => {+ const dialog = element(+ 'div',+ {top: 0, height: window.innerHeight},+ {position: 'fixed'},+ );+ const field = element('input', {top: 600, height: 40});+ dialog.append(field);+ const header = element('div', {top: 0, height: 60}, {position: 'fixed'});+ const search = element('input', {top: 10, height: 40});+ header.append(search);+ document.body.append(dialog, header);+ expect(dockedAncestor(field)).toBeNull();+ expect(dockedAncestor(search)).toBeNull();+ });++ it('measures how far an edge sits under the keyboard, with the offset, and nothing without a keyboard', () => {+ const top = window.innerHeight - 300;+ expect(coveredBy(top + 10, 300, 0, window)).toBe(10);+ expect(coveredBy(top - 30, 300, FIELD_OFFSET, window)).toBe(0);+ expect(coveredBy(top, 300, FIELD_OFFSET, window)).toBe(FIELD_OFFSET);+ expect(coveredBy(window.innerHeight, 0, FIELD_OFFSET, window)).toBe(0);+ });+});++describe('keepFieldAboveKeyboard', () => {+ it('scrolls the page until a field in it sits the offset above the keyboard, in the report itself', () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const input = element('input', {top: 660, height: 40});+ document.body.append(input);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ const keyboardTop = window.innerHeight - 300;+ expect(scrollBy).toHaveBeenCalledTimes(1);+ expect(scrollBy).toHaveBeenCalledWith({+ top: 700 + FIELD_OFFSET - keyboardTop,+ behavior: 'instant',+ });+ });++ it('scrolls its own scroller when it sits in one, and leaves the page alone', () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const list = element('div', {top: 0, height: 760}, {overflowY: 'auto'});+ Object.defineProperty(list, 'scrollHeight', {value: 2000});+ Object.defineProperty(list, 'clientHeight', {value: 760});+ const input = element('input', {top: 600, height: 40});+ list.append(input);+ document.body.append(list);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(list.scrollTop).toBe(+ 640 + FIELD_OFFSET - (window.innerHeight - 300),+ );+ expect(scrollBy).not.toHaveBeenCalled();+ });++ it("reveals at a change of the keyboard's height, not at a report of the same height, so a field the person scrolled away stays there", () => {+ vi.stubGlobal('scrollBy', vi.fn());+ const list = element('div', {top: 0, height: 760}, {overflowY: 'auto'});+ Object.defineProperty(list, 'scrollHeight', {value: 2000});+ Object.defineProperty(list, 'clientHeight', {value: 760});+ const input = element('input', {top: 600, height: 40});+ list.append(input);+ document.body.append(list);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(list.scrollTop).toBe(+ 640 + FIELD_OFFSET - (window.innerHeight - 300),+ );+ // The person scrolls the list back, so the field sits under the keyboard.+ // The visual viewport then reports a scroll at the same keyboard height.+ list.scrollTop = 0;+ act(() => {+ viewport.dispatchEvent(new Event('scroll'));+ });+ runFrames();+ expect(list.scrollTop).toBe(0);+ // A zoom moves the measured height by under a pixel: still no reveal.+ keyboard(300.4);+ expect(list.scrollTop).toBe(0);+ // A change of the keyboard's height reveals the field again.+ keyboard(320);+ expect(list.scrollTop).toBe(+ 640 + FIELD_OFFSET - (window.innerHeight - 320),+ );+ });++ it('scrolls only its nearest scroller, and nothing else, when that scroller cannot scroll far enough', () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const list = element('div', {top: 0, height: 760}, {overflowY: 'auto'});+ Object.defineProperty(list, 'scrollHeight', {value: 900});+ Object.defineProperty(list, 'clientHeight', {value: 760});+ // The list has 140 px of range left.+ let listTop = 0;+ Object.defineProperty(list, 'scrollTop', {+ configurable: true,+ get: () => listTop,+ set: (value: number) => {+ listTop = Math.max(0, Math.min(140, value));+ },+ });+ const input = element('input', {top: 660, height: 40});+ list.append(input);+ document.body.append(list);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(list.scrollTop).toBe(140);+ // The page stays where it is; the rest of the field stays covered.+ expect(scrollBy).not.toHaveBeenCalled();+ });++ it('moves its docked bar up by the part of it the keyboard covers, and back once the keyboard has gone', () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ // The bar's bottom edge ends at the keyboard's top: the part of the bar+ // the keyboard covered, and no more.+ expect(animatorFor(bar).get('y')).toBe(-300);+ // Leaving the field for nothing while the keyboard still shows moves+ // nothing until the keyboard goes.+ act(() => input.blur());+ expect(animatorFor(bar).get('y')).toBe(-300);+ keyboard(0);+ expect(animatorFor(bar).get('y')).toBe(0);+ // At rest the ridden bar carries no translate of its own.+ expect(['', 'none']).toContain(bar.style.translate);+ });++ it("keeps the bar up when focus moves to another field in it, even as the first field's path detaches", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const first = element('input', {top: bottom - 50, height: 40});+ const second = element('input', {top: bottom - 50, height: 40});+ bar.append(first, second);+ document.body.append(bar);+ const stopFirst = keepFieldAboveKeyboard(first);+ track(keepFieldAboveKeyboard(second));+ focusOn(first);+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBe(-300);+ focusOn(second);+ expect(animatorFor(bar).get('y')).toBe(-300);+ stopFirst();+ expect(animatorFor(bar).get('y')).toBe(-300);+ });++ it('reveals a field in a container that fills the viewport through its scroller there, and never moves the container', () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const dialog = element(+ 'div',+ {top: 0, height: window.innerHeight},+ {position: 'fixed'},+ );+ const body = element(+ 'div',+ {top: 0, height: window.innerHeight},+ {overflowY: 'auto'},+ );+ Object.defineProperty(body, 'scrollHeight', {value: 1600});+ Object.defineProperty(body, 'clientHeight', {value: window.innerHeight});+ let bodyTop = 0;+ Object.defineProperty(body, 'scrollTop', {+ configurable: true,+ get: () => bodyTop,+ set: (value: number) => {+ bodyTop = Math.max(0, Math.min(1600 - window.innerHeight, value));+ },+ });+ const other = element('input', {top: 10, height: 40});+ const input = element('input', {top: 640, height: 40});+ body.append(other, input);+ dialog.append(body);+ document.body.append(dialog);+ track(keepFieldAboveKeyboard(input));+ focusOn(other);+ const focus = vi.spyOn(input, 'focus');+ focusOn(input);+ // The focus move is claimed: the dialog's own scroller reveals the field.+ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ keyboard(300);+ const keyboardTop = window.innerHeight - 300;+ expect(body.scrollTop).toBe(640 + 40 - (keyboardTop - FIELD_OFFSET));+ expect(scrollBy).not.toHaveBeenCalled();+ expect(animatorFor(dialog).get('y')).toBe(0);+ });++ it("leaves a field in a container that fills the viewport with no scroller around it to the browser's own reveal", () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const dialog = element(+ 'div',+ {top: 0, height: window.innerHeight},+ {position: 'fixed'},+ );+ const other = element('input', {top: 10, height: 40});+ const input = element('input', {top: 640, height: 40});+ dialog.append(other, input);+ document.body.append(dialog);+ track(keepFieldAboveKeyboard(input));+ focusOn(other);+ const focus = vi.spyOn(input, 'focus');+ focusOn(input);+ // The focus move is not claimed: the browser's own focus step runs.+ expect(focus).not.toHaveBeenCalledWith({preventScroll: true});+ keyboard(300);+ expect(scrollBy).not.toHaveBeenCalled();+ expect(dialog.style.translate).toBe('');+ });++ it('lifts a docked container taller than the room above the keyboard with no scroller only as far as its focused field needs', () => {+ const bottom = window.innerHeight;+ // A full-height drawer below a 56 px header, with no scroller of its own.+ const drawer = element(+ 'div',+ {top: 56, height: bottom - 56},+ {position: 'fixed'},+ );+ const top = element('input', {top: 80, height: 40});+ const low = element('input', {top: bottom - 68, height: 40});+ drawer.append(top, low);+ document.body.append(drawer);+ track(keepFieldAboveKeyboard(top));+ track(keepFieldAboveKeyboard(low));+ // A field near its top already clears the keyboard: nothing moves, so+ // the field stays on screen.+ focusOn(top);+ keyboard(300);+ expect(drawer.style.translate).toBe('');+ // A field near its bottom moves up only to sit `FIELD_OFFSET` above the+ // keyboard, less than the drawer's own 300 px overlap.+ focusOn(low);+ runFrames();+ const keyboardTop = bottom - 300;+ expect(animatorFor(drawer).get('y')).toBe(+ -(bottom - 28 + FIELD_OFFSET - keyboardTop),+ );+ });++ it('keeps the guards for a too-tall container with no scroller: an app moving it, or a text field outside with focus, gets no lift', () => {+ const bottom = window.innerHeight;+ const drawer = element(+ 'div',+ {top: 56, height: bottom - 56},+ {position: 'fixed'},+ );+ const header = element('input', {top: 8, height: 40});+ const low = element('input', {top: bottom - 68, height: 40});+ drawer.append(low);+ document.body.append(header, drawer);+ let running: unknown[] = [+ {playState: 'running', transitionProperty: 'transform'},+ ];+ Object.defineProperty(drawer, 'getAnimations', {+ configurable: true,+ value: () => running,+ });+ track(keepFieldAboveKeyboard(low));+ focusOn(low);+ keyboard(300);+ // The app is moving the drawer itself.+ expect(drawer.style.translate).toBe('');+ running = [];+ keyboard(300);+ expect(animatorFor(drawer).get('y')).toBe(+ -(bottom - 28 + FIELD_OFFSET - (bottom - 300)),+ );+ // A text field outside the drawer takes focus: the drawer rests, so it+ // never covers that field.+ focusOn(header);+ expect(animatorFor(drawer).get('y')).toBe(0);+ });++ it('keeps a docked container taller than the room above the keyboard in place, and reveals its field through its scroller there', () => {+ const bottom = window.innerHeight;+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ // A full-height drawer below a 56 px header, docked to the bottom edge.+ const drawer = element(+ 'div',+ {top: 56, height: bottom - 56},+ {position: 'fixed'},+ );+ const list = element(+ 'div',+ {top: 56, height: bottom - 56},+ {overflowY: 'auto'},+ );+ Object.defineProperty(list, 'scrollHeight', {value: 1400});+ Object.defineProperty(list, 'clientHeight', {value: bottom - 56});+ let listTop = 0;+ Object.defineProperty(list, 'scrollTop', {+ configurable: true,+ get: () => listTop,+ set: (value: number) => {+ listTop = Math.max(0, Math.min(1400 - (bottom - 56), value));+ },+ });+ const input = element('input', {top: bottom - 68, height: 40});+ list.append(input);+ drawer.append(list);+ document.body.append(drawer);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(drawer.style.translate).toBe('');+ const keyboardTop = bottom - 300;+ expect(list.scrollTop).toBe(bottom - 28 - (keyboardTop - FIELD_OFFSET));+ expect(scrollBy).not.toHaveBeenCalled();+ });++ it('reads every box before it moves a container that turns too tall, and reveals its field from where the move leaves it', () => {+ const bottom = window.innerHeight;+ vi.stubGlobal('scrollBy', vi.fn());+ // A full-height drawer below a 56 px header, docked to the bottom edge.+ const drawer = element(+ 'div',+ {top: 56, height: bottom - 56},+ {position: 'fixed'},+ );+ const list = element(+ 'div',+ {top: 56, height: bottom - 56},+ {overflowY: 'auto'},+ );+ Object.defineProperty(list, 'scrollHeight', {value: 1400});+ Object.defineProperty(list, 'clientHeight', {value: bottom - 56});+ // Each layout read records the drawer's translate at that moment.+ const reads: string[] = [];+ let listTop = 0;+ Object.defineProperty(list, 'scrollTop', {+ configurable: true,+ get: () => {+ reads.push(drawer.style.translate);+ return listTop;+ },+ set: (value: number) => {+ listTop = Math.max(0, Math.min(1400 - (bottom - 56), value));+ },+ });+ const input = element('input', {top: bottom - 68, height: 40});+ list.append(input);+ drawer.append(list);+ document.body.append(drawer);+ vi.mocked(Element.prototype.getBoundingClientRect).mockImplementation(+ function (this: Element) {+ if (this === input || this === list) {+ reads.push(drawer.style.translate);+ }+ return boxOf(this);+ },+ );+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ // A short keyboard lifts the drawer by the part of it the keyboard covers.+ keyboard(40);+ const lifted = drawer.style.translate;+ expect(animatorFor(drawer).get('y')).toBeLessThan(0);+ // A tall keyboard leaves the drawer too tall. It goes back to rest, and+ // its scroller reveals the field. Every read comes before that move.+ reads.length = 0;+ keyboard(300);+ expect(drawer.style.translate).toBe('');+ expect(reads.length).toBeGreaterThan(0);+ expect(reads.filter(translate => translate !== lifted)).toEqual([]);+ const keyboardTop = bottom - 300;+ expect(listTop).toBe(bottom - 28 - (keyboardTop - FIELD_OFFSET));+ });++ it("leaves a field on a page with nothing to scroll to the browser's own reveal", () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ // A page no taller than the viewport.+ pageScrollRange(window.innerHeight);+ const other = element('input', {top: 10, height: 40});+ const input = element('input', {top: window.innerHeight - 60, height: 40});+ document.body.append(other, input);+ track(keepFieldAboveKeyboard(input));+ focusOn(other);+ const focus = vi.spyOn(input, 'focus');+ focusOn(input);+ // The focus move is not claimed: the browser's own focus step runs.+ expect(focus).not.toHaveBeenCalledWith({preventScroll: true});+ keyboard(300);+ expect(scrollBy).not.toHaveBeenCalled();+ });++ it('scrolls a field above the view down into it when it gains focus', () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const input = element('input', {top: -200, height: 40});+ document.body.append(input);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ expect(scrollBy).toHaveBeenCalledWith({top: -200, behavior: 'instant'});+ });++ it('scrolls a field below the view into it with no keyboard up, as a hardware Tab reaches it', () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const input = element('input', {top: window.innerHeight + 100, height: 40});+ document.body.append(input);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ expect(scrollBy).toHaveBeenCalledWith({top: 140, behavior: 'instant'});+ });++ it("raises the tap's click once after a claimed tap, so a listener on the field or an ancestor still runs", () => {+ const wrapper = element('div', null);+ const input = element('input', {top: 660, height: 40});+ wrapper.append(input);+ document.body.append(wrapper);+ const onField = vi.fn();+ const onAncestor = vi.fn();+ input.addEventListener('click', onField);+ wrapper.addEventListener('click', onAncestor);+ track(keepFieldAboveKeyboard(input));+ const touch = (type: string) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const point = {+ identifier: 0,+ clientX: 40,+ clientY: 680,+ screenX: 41,+ screenY: 742,+ };+ Object.assign(event, {+ touches: type === 'touchend' ? [] : [point],+ changedTouches: [point],+ });+ return event;+ };+ act(() => {+ input.dispatchEvent(touch('touchstart'));+ });+ act(() => {+ input.dispatchEvent(touch('touchend'));+ });+ expect(document.activeElement).toBe(input);+ expect(onField).toHaveBeenCalledTimes(1);+ expect(onAncestor).toHaveBeenCalledTimes(1);+ const click = onField.mock.calls[0][0] as PointerEvent;+ expect(click.isTrusted).toBe(false);+ expect(click.pointerType).toBe('touch');+ expect([+ click.clientX,+ click.clientY,+ click.screenX,+ click.screenY,+ click.detail,+ ]).toEqual([40, 680, 41, 742, 1]);+ });++ it('puts back a pan the browser makes on its own after a focus no claim saw', () => {+ vi.stubGlobal('scrollBy', vi.fn());+ const scrollIntoView = vi.fn();+ Object.defineProperty(Element.prototype, 'scrollIntoView', {+ configurable: true,+ value: scrollIntoView,+ });+ const input = element('input', {top: 300, height: 40});+ document.body.append(input);+ track(keepFieldAboveKeyboard(input));+ // A script focuses the field while nothing has focus: no blur, no tap.+ focusOn(input);+ keyboard(300);+ expect(scrollIntoView).not.toHaveBeenCalled();+ // The browser pans the visual viewport down to the field by itself.+ viewport.offsetTop = 120;+ act(() => {+ viewport.dispatchEvent(new Event('scroll'));+ });+ expect(scrollIntoView).toHaveBeenCalledTimes(1);+ Reflect.deleteProperty(Element.prototype, 'scrollIntoView');+ });++ it('moves nothing inside a keyboard target, which keeps its own fields clear', () => {+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const sheet = element('div', {top: 300, height: 468});+ const input = element('input', {top: 700, height: 40});+ sheet.append(input);+ document.body.append(sheet);+ track(registerKeyboardTarget(sheet));+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(scrollBy).not.toHaveBeenCalled();+ expect(animatorFor(sheet).get('y')).toBe(0);+ });++ it('takes a focus move into the field without the browser reveal', () => {+ const other = element('input', {top: 10, height: 40});+ const input = element('input', {top: 660, height: 40});+ document.body.append(other, input);+ track(keepFieldAboveKeyboard(input));+ focusOn(other);+ const focus = vi.spyOn(input, 'focus');+ focusOn(input);+ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ expect(document.activeElement).toBe(input);+ });++ it("takes a first tap on the field itself, so the browser's tap focus cannot pan the page", () => {+ const input = element('input', {top: 660, height: 40});+ document.body.append(input);+ track(keepFieldAboveKeyboard(input));+ const focus = vi.spyOn(input, 'focus');+ const touch = (type: string) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const points =+ type === 'touchend' ? [] : [{identifier: 0, clientX: 40, clientY: 680}];+ Object.assign(event, {+ touches: points,+ changedTouches: [{identifier: 0, clientX: 40, clientY: 680}],+ });+ return event;+ };+ act(() => {+ input.dispatchEvent(touch('touchstart'));+ });+ const end = touch('touchend');+ act(() => {+ input.dispatchEvent(end);+ });+ expect(end.defaultPrevented).toBe(true);+ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ expect(document.activeElement).toBe(input);+ });++ it('attaches nothing under a mouse or a trackpad', () => {+ isCoarse = false;+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const input = element('input', {top: 660, height: 40});+ document.body.append(input);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(scrollBy).not.toHaveBeenCalled();+ });+});++describe('followKeyboard', () => {+ it("rides a Core host's own docked element, sticky or fixed, and registers it, so the field's own path stands down", () => {+ const bottom = window.innerHeight;+ const dock = element(+ 'div',+ {top: bottom - 80, height: 80},+ {position: 'sticky'},+ );+ const input = element('textarea', {top: bottom - 64, height: 48});+ dock.append(input);+ document.body.append(dock);+ track(followKeyboard(dock, {move: 'ride', offset: 8}));+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(320);+ // The dock's bottom edge reaches the keyboard's top; the field already+ // keeps 8 px above it.+ expect(animatorFor(dock).get('y')).toBe(-320);+ });++ it("moves nothing on an app's elements but the focused field's fixed ancestor docked at the viewport's bottom", () => {+ const bottom = window.innerHeight;+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ // An app's sticky bar is no fixed container: it never moves.+ const sticky = element(+ 'div',+ {top: bottom - 80, height: 80},+ {position: 'sticky'},+ );+ const inSticky = element('textarea', {top: bottom - 64, height: 48});+ sticky.append(inSticky);+ // An app's fixed bar floating above the bottom edge is not docked.+ const floating = element(+ 'div',+ {top: bottom - 140, height: 60},+ {position: 'fixed'},+ );+ const inFloating = element('input', {top: bottom - 130, height: 40});+ floating.append(inFloating);+ // The docked bar moves, and only it: not its page wrapper.+ const wrapper = element('div', null);+ const docked = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const inDocked = element('input', {top: bottom - 50, height: 40});+ docked.append(inDocked);+ wrapper.append(docked);+ document.body.append(sticky, floating, wrapper);+ for (const field of [inSticky, inFloating, inDocked]) {+ track(keepFieldAboveKeyboard(field));+ }+ focusOn(inSticky);+ keyboard(300);+ focusOn(inFloating);+ focusOn(inDocked);+ expect(animatorFor(docked).get('y')).toBeLessThan(0);+ const moved = [...document.querySelectorAll<HTMLElement>('*')].filter(+ node => node.style.translate !== '' && node.style.translate !== 'none',+ );+ expect(moved).toEqual([docked]);+ });++ it("sets an app's raised bar to rest once it leaves the bottom edge, even after focus left for nothing", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ act(() => input.blur());+ expect(animatorFor(bar).get('y')).toBeLessThan(0);+ bar.setAttribute('data-top', String(bottom - 200));+ input.setAttribute('data-top', String(bottom - 190));+ keyboard(200);+ expect(animatorFor(bar).get('y')).toBe(0);+ });++ it("stops moving an app's bar the moment it is no longer docked at the viewport's bottom", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBeLessThan(0);+ // The app moves its bar up the page: it no longer sits on the bottom edge.+ bar.setAttribute('data-top', String(bottom - 200));+ input.setAttribute('data-top', String(bottom - 190));+ keyboard(320);+ expect(animatorFor(bar).get('y')).toBe(0);+ });++ it("never moves an app's bar the app already moves with the keyboard, even when its listener runs after the module's", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ // The app follows the keyboard with its own transform, from a listener+ // added after the module's, so it runs later in each report.+ const follow = () => {+ const cover = window.innerHeight - viewport.height;+ bar.style.transform = `matrix(1, 0, 0, 1, 0, ${-cover})`;+ };+ viewport.addEventListener('resize', follow);+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBe(0);+ expect(bar.style.translate).toBe('');+ expect(bar.style.transform).toBe('matrix(1, 0, 0, 1, 0, -300)');+ viewport.removeEventListener('resize', follow);+ });++ it("never moves an app's bar the app already moves with the keyboard from a listener that runs before the module's", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ // The app's listener is added before the module subscribes, so it runs+ // first in each report.+ const follow = () => {+ const cover = window.innerHeight - viewport.height;+ bar.style.transform = `matrix(1, 0, 0, 1, 0, ${-cover})`;+ };+ viewport.addEventListener('resize', follow);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBe(0);+ expect(bar.style.translate).toBe('');+ viewport.removeEventListener('resize', follow);+ });++ it("moves an app's bar the app lifts part of the way only by the rest, and keeps the app's transform", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ const liftPart = () => {+ bar.style.transform = 'matrix(1, 0, 0, 1, 0, -100)';+ };+ viewport.addEventListener('resize', liftPart);+ keyboard(300);+ // The keyboard still covered 200 px of the bar after the app's 100.+ expect(animatorFor(bar).get('y')).toBe(-200);+ expect(bar.style.transform).toBe('matrix(1, 0, 0, 1, 0, -100)');+ expect(boxOf(bar).bottom).toBe(bottom - 300);+ viewport.removeEventListener('resize', liftPart);+ });++ it("leaves an app's docked bar that positions itself with its own translate exactly as it is", () => {+ const bottom = window.innerHeight;+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ // A bar the app centres with `translate`.+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed', translate: '-50% 0'},+ );+ const other = element('input', {top: 10, height: 40});+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(other, bar);+ track(keepFieldAboveKeyboard(input));+ focusOn(other);+ const focus = vi.spyOn(input, 'focus');+ focusOn(input);+ // No claim: the browser's own focus step runs, as without Core.+ expect(focus).not.toHaveBeenCalledWith({preventScroll: true});+ keyboard(300);+ expect(bar.style.translate).toBe('-50% 0');+ expect(scrollBy).not.toHaveBeenCalled();+ keyboard(0);+ expect(bar.style.translate).toBe('-50% 0');+ });++ it("leaves an app's bar the app is moving itself, a transition or animation running on its position, to the app", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ // A CSS transition the app runs on the bar's transform.+ let running: unknown[] = [+ {playState: 'running', transitionProperty: 'transform'},+ ];+ Object.defineProperty(bar, 'getAnimations', {+ configurable: true,+ value: () => running,+ });+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBe(0);+ expect(bar.style.translate).toBe('');+ // A CSS animation of its bottom edge is the app's move too.+ running = [+ {+ playState: 'running',+ animationName: 'rise',+ effect: {+ getKeyframes: () => [+ {offset: 0, bottom: '0px'},+ {offset: 1, bottom: '300px'},+ ],+ },+ },+ ];+ keyboard(320);+ expect(bar.style.translate).toBe('');+ // Once the app's move ends, the bar rides by what the keyboard covers.+ running = [];+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBe(-300);+ });++ it("keeps its lift on a bar whose own `transition: all` animates the ride's translate", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed', transition: 'all 300ms'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ let running: unknown[] = [];+ Object.defineProperty(bar, 'getAnimations', {+ configurable: true,+ value: () => running,+ });+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBe(-300);+ // The ride's write starts the bar's own transition on `translate`.+ running = [{playState: 'running', transitionProperty: 'translate'}];+ keyboard(310);+ expect(animatorFor(bar).get('y')).toBe(-310);+ });++ it("rides a bar the app moves only with a script animation, which a CSS motion alone marks as the app's", () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ Object.defineProperty(bar, 'getAnimations', {+ configurable: true,+ value: () => [+ // The app's own script animation of the bar's transform.+ {+ playState: 'running',+ effect: {+ getKeyframes: () => [+ {offset: 0, transform: 'none'},+ {offset: 1, transform: 'translateY(-40px)'},+ ],+ },+ },+ ],+ });+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBe(-300);+ });++ it('still rides a bar whose running animations are only its own ride or no move at all', () => {+ const bottom = window.innerHeight;+ const bar = element(+ 'div',+ {top: bottom - 60, height: 60},+ {position: 'fixed'},+ );+ const input = element('input', {top: bottom - 50, height: 40});+ bar.append(input);+ document.body.append(bar);+ Object.defineProperty(bar, 'getAnimations', {+ configurable: true,+ value: () => [+ // The ride's own script animation of `translate`.+ {+ playState: 'running',+ effect: {+ getKeyframes: () => [+ {offset: 0, translate: '0px 0px'},+ {offset: 1, translate: '0px -300px'},+ ],+ },+ },+ // An app fade, which moves nothing.+ {playState: 'running', transitionProperty: 'opacity'},+ // A finished move.+ {playState: 'finished', transitionProperty: 'transform'},+ ],+ });+ track(keepFieldAboveKeyboard(input));+ focusOn(input);+ keyboard(300);+ expect(animatorFor(bar).get('y')).toBe(-300);+ });++ it.each([+ [+ 'a fixed bar floating above the bottom edge',+ (bottom: number) =>+ element('div', {top: bottom - 600, height: 500}, {position: 'fixed'}),+ '',+ ],+ [+ 'a docked bar that sets its own translate',+ (bottom: number) =>+ element(+ 'div',+ {top: bottom - 500, height: 500},+ {position: 'fixed', translate: '-50% 0'},+ ),+ '-50% 0',+ ],+ ] as const)(+ 'reveals a field in %s through the scroller around it, and never moves the container',+ (_, container, translate) => {+ const bottom = window.innerHeight;+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const fixed = container(bottom);+ const box = fixed.getBoundingClientRect();+ const list = element(+ 'div',+ {top: box.top, height: 500},+ {overflowY: 'auto'},+ );+ Object.defineProperty(list, 'scrollHeight', {value: 1500});+ Object.defineProperty(list, 'clientHeight', {value: 500});+ let listTop = 0;+ Object.defineProperty(list, 'scrollTop', {+ configurable: true,+ get: () => listTop,+ set: (value: number) => {+ listTop = Math.max(0, Math.min(1000, value));+ },+ });+ const other = element('input', {top: 10, height: 40});+ const input = element('input', {top: box.bottom - 60, height: 40});+ list.append(input);+ fixed.append(list);+ document.body.append(other, fixed);+ track(keepFieldAboveKeyboard(input));+ focusOn(other);+ const focus = vi.spyOn(input, 'focus');+ focusOn(input);+ // The focus move is claimed: the scroller in the container reveals the+ // field, and the page is not panned.+ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ keyboard(300);+ const keyboardTop = bottom - 300;+ expect(list.scrollTop).toBe(+ box.bottom - 20 - (keyboardTop - FIELD_OFFSET),+ );+ expect(scrollBy).not.toHaveBeenCalled();+ expect(fixed.style.translate).toBe(translate);+ },+ );++ it("leaves a field in a fixed bar floating above the bottom edge to the browser's own reveal", () => {+ const bottom = window.innerHeight;+ const scrollBy = vi.fn();+ vi.stubGlobal('scrollBy', scrollBy);+ const floating = element(+ 'div',+ {top: bottom - 140, height: 60},+ {position: 'fixed'},+ );+ const other = element('input', {top: 10, height: 40});+ const input = element('input', {top: bottom - 130, height: 40});+ floating.append(input);+ document.body.append(other, floating);+ track(keepFieldAboveKeyboard(input));+ focusOn(other);+ const focus = vi.spyOn(input, 'focus');+ focusOn(input);+ expect(focus).not.toHaveBeenCalledWith({preventScroll: true});+ keyboard(300);+ expect(scrollBy).not.toHaveBeenCalled();+ expect(floating.style.translate).toBe('');+ });++ it('reveals the next field at once when focus moves with the keyboard up, with no new report', () => {+ const list = element('div', {top: 0, height: 760}, {overflowY: 'auto'});+ Object.defineProperty(list, 'scrollHeight', {value: 2000});+ Object.defineProperty(list, 'clientHeight', {value: 760});+ const first = element('input', {top: 100, height: 40});+ const next = element('input', {top: 640, height: 40});+ list.append(first, next);+ document.body.append(list);+ track(followKeyboard(list, {move: 'reveal', offset: FIELD_OFFSET}));+ focusOn(first);+ keyboard(300);+ expect(list.scrollTop).toBe(0);+ focusOn(next);+ expect(list.scrollTop).toBe(+ 680 + FIELD_OFFSET - (window.innerHeight - 300),+ );+ });++ it('lifts a ridden target only while focus is inside it, so it never covers a field outside', () => {+ const bottom = window.innerHeight;+ const page = element('input', {top: 300, height: 40});+ const dock = element(+ 'div',+ {top: bottom - 80, height: 80},+ {position: 'fixed'},+ );+ const input = element('textarea', {top: bottom - 64, height: 48});+ dock.append(input);+ document.body.append(page, dock);+ track(followKeyboard(dock, {move: 'ride', offset: 8}));+ focusOn(page);+ keyboard(320);+ expect(animatorFor(dock).get('y')).toBe(0);+ focusOn(input);+ expect(animatorFor(dock).get('y')).toBe(-320);+ focusOn(page);+ expect(animatorFor(dock).get('y')).toBe(0);+ });++ it('keeps a ridden target on the keyboard as it goes when focus leaves for nothing', () => {+ const bottom = window.innerHeight;+ const dock = element(+ 'div',+ {top: bottom - 80, height: 80},+ {position: 'fixed'},+ );+ const input = element('textarea', {top: bottom - 64, height: 48});+ dock.append(input);+ document.body.append(dock);+ track(followKeyboard(dock, {move: 'ride', offset: 8}));+ focusOn(input);+ keyboard(320);+ expect(animatorFor(dock).get('y')).toBe(-320);+ act(() => input.blur());+ expect(animatorFor(dock).get('y')).toBe(-320);+ keyboard(120);+ expect(animatorFor(dock).get('y')).toBe(-120);+ keyboard(0);+ expect(animatorFor(dock).get('y')).toBe(0);+ });++ it('reveals the focused field inside a scrolling target', () => {+ const list = element('div', {top: 0, height: 760}, {overflowY: 'auto'});+ Object.defineProperty(list, 'scrollHeight', {value: 2000});+ Object.defineProperty(list, 'clientHeight', {value: 760});+ const input = element('input', {top: 620, height: 40});+ list.append(input);+ document.body.append(list);+ track(followKeyboard(list, {move: 'reveal', offset: FIELD_OFFSET}));+ focusOn(input);+ keyboard(300);+ expect(list.scrollTop).toBe(+ 660 + FIELD_OFFSET - (window.innerHeight - 300),+ );+ });+});diff --git a/packages/core/src/keyboard/keyboardTarget.ts b/packages/core/src/keyboard/keyboardTarget.tsnew file mode 100644index 0000000000..8c9014925c--- /dev/null+++ b/packages/core/src/keyboard/keyboardTarget.ts@@ -0,0 +1,899 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardTarget.ts+ * @input The keyboard module's reports and focus claim, the layout guide,+ * rideKeyboard and the shared animator+ * @output The keyboard targets: their registry, followKeyboard for a docked+ * or scrolling target, and keepFieldAboveKeyboard, a covered field's path+ * @position Keyboard module, internal to core. useMobileKeyboard calls it.+ *+ * SYNC: When modified, update /packages/core/src/keyboard/README.md+ */++import {animatorFor, type Animator} from '../motion/animator';+import {isCoarsePointer} from '../utils/coarsePointer';+import {subscribeInput} from '../utils/inputStream';+import {layoutViewportHeight} from '../utils/layoutViewport';+import {scrollingAncestor} from '../utils/scrollingAncestor';+import {+ KEYBOARD_EPSILON,+ claimTapFocus,+ findTextEntryControl,+ focusAtPoint,+ getKeyboardHeight,+ isKeyboardMeasurable,+ isTextEntryControl,+ refuseFocusReveal,+ subscribeKeyboardHeight,+ watchRevealPan,+} from './keyboardHeight';+import {getKeyboardLayoutGuide, keyboardProfileOf} from './keyboardLayoutGuide';+import type {KeyboardTransition} from './keyboardModel';+import {distanceIntoBand} from './revealBand';+import {rideKeyboard} from './rideKeyboard';++/**+ * How a target keeps a focused field above the keyboard: `'reveal'` scrolls+ * the field into place, and `'ride'` moves the target with the keyboard.+ */+export type KeyboardMove = 'reveal' | 'ride';++/**+ * The gap a field keeps above the keyboard's top edge, CSS px: the same+ * clearance a layer keeps above the keyboard.+ */+export const FIELD_OFFSET = 10;++// Targets that keep their own fields above the keyboard. A field inside one+// moves nothing itself, so nothing moves twice.+const targets = new WeakSet<Element>();++/** Registers `element` as a keyboard target until the returned call. */+export function registerKeyboardTarget(element: Element): () => void {+ targets.add(element);+ return () => {+ targets.delete(element);+ };+}++/** Whether a registered target holds `element`. */+export function isInsideKeyboardTarget(element: Element): boolean {+ for (+ let node = element.parentElement;+ node != null;+ node = node.parentElement+ ) {+ if (targets.has(node)) {+ return true;+ }+ }+ return false;+}++/**+ * The element that scrolls `element` into view: its nearest ancestor that+ * scrolls on the block axis, or else the document's scroller.+ */+export function nearestScroller(element: Element): Element {+ const doc = element.ownerDocument;+ const scroller = scrollingAncestor(element);+ return scroller == null ||+ scroller === doc.body ||+ scroller === doc.documentElement+ ? (doc.scrollingElement ?? doc.documentElement)+ : scroller;+}++// The element's bottom edge where layout puts it, without the ride's move.+function restingBottom(element: Element, animator: Animator): number {+ return element.getBoundingClientRect().bottom - animator.get('y');+}++/**+ * How far a ride has moved `element` from where its layout puts it, as the+ * page draws it now, CSS px. Reading the style creates no animator.+ */+export function drawnOffsetOf(element: Element): number {+ const view = element.ownerDocument.defaultView;+ const translate = view?.getComputedStyle(element).translate ?? '';+ return parseFloat(translate.split(' ')[1] ?? '') || 0;+}++/** Where an element sits among fixed containers (see fixedContainerOf). */+export type FixedContainer =+ {docked: HTMLElement} | 'fills-viewport' | 'floating' | null;++/**+ * How the nearest fixed-position ancestor of `element` meets the keyboard. It+ * is docked when its layout puts its bottom at the layout viewport's bottom+ * edge. It can also fill the viewport, as a dialog does, or float above the+ * bottom edge. Null with no fixed ancestor, as in page content.+ */+export function fixedContainerOf(element: Element): FixedContainer {+ const view = element.ownerDocument.defaultView;+ const node = nearestFixedAncestor(element);+ if (view == null || node == null) {+ return null;+ }+ const dock = dockOf(node, view);+ return dock === 'docked' ? {docked: node} : dock;+}++// The nearest fixed-position ancestor of `element`, or null.+function nearestFixedAncestor(element: Element): HTMLElement | null {+ const view = element.ownerDocument.defaultView;+ if (view == null) {+ return null;+ }+ for (+ let node = element.parentElement;+ node != null;+ node = node.parentElement+ ) {+ if (view.getComputedStyle(node).position === 'fixed') {+ return node;+ }+ }+ return null;+}++// How far the element's own `transform` moves it down, CSS px: the+// translation of its computed matrix. An app may lift its bar this way.+function transformOffsetOf(element: Element, view: Window): number {+ const transform = view.getComputedStyle(element).transform;+ const matrix = /^matrix(3d)?\(([^)]*)\)$/.exec(transform);+ if (matrix == null) {+ return 0;+ }+ const values = (matrix[2] ?? '').split(',').map(Number);+ const y = matrix[1] == null ? values[5] : values[13];+ return y != null && Number.isFinite(y) ? y : 0;+}++// How a fixed-position `node` meets the keyboard, by its layout box: without+// the ride's translate or any transform the app sets on it.+function dockOf(+ node: HTMLElement,+ view: Window,+): 'docked' | 'fills-viewport' | 'floating' {+ const viewportBottom = layoutViewportHeight(view);+ const box = node.getBoundingClientRect();+ if (box.height >= viewportBottom - KEYBOARD_EPSILON) {+ return 'fills-viewport';+ }+ const bottom =+ box.bottom - drawnOffsetOf(node) - transformOffsetOf(node, view);+ return Math.abs(viewportBottom - bottom) <= KEYBOARD_EPSILON+ ? 'docked'+ : 'floating';+}++// The animator each ridden target moves with. A translate it draws is the+// ride's, not the app's.+const riddenAnimators = new WeakMap<HTMLElement, Animator>();++// Whether the app positions `node` with its own `translate`, such as `-50% 0`+// to centre it. A translate the ride draws is not the app's.+function hasOwnTranslate(node: HTMLElement, view: Window): boolean {+ const translate = view.getComputedStyle(node).translate;+ if (translate === '' || translate === 'none') {+ return false;+ }+ const ride = riddenAnimators.get(node);+ return ride == null || ride.get('y') === 0;+}++// The properties that move a bar on the page.+const POSITION_PROPERTIES = new Set([+ 'transform',+ 'translate',+ 'top',+ 'bottom',+ 'inset',+ 'inset-block',+ 'inset-block-start',+ 'inset-block-end',+]);++const KEYFRAME_FIELDS = new Set([+ 'offset',+ 'computedOffset',+ 'easing',+ 'composite',+]);++// The CSS properties a running animation changes, in their CSS names.+function animatedProperties(animation: Animation): string[] {+ if ('transitionProperty' in animation) {+ return [String(animation.transitionProperty)];+ }+ const effect = animation.effect;+ if (effect == null || !('getKeyframes' in effect)) {+ return [];+ }+ const names = new Set<string>();+ for (const frame of (effect as KeyframeEffect).getKeyframes()) {+ for (const key of Object.keys(frame)) {+ if (!KEYFRAME_FIELDS.has(key)) {+ names.add(key.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`));+ }+ }+ }+ return [...names];+}++// Whether the app is moving `node` itself right now with a CSS transition or+// animation on its position. A script animation is not seen: an app that moves+// its bar from script keeps it clear with its own `translate`. On a target the+// ride moves, a transition of `translate` alone is the ride's. The target's+// `transition` starts it when the ride writes the property. The app sets no+// `translate` on a target the ride moves.+function isMovedByApp(node: HTMLElement): boolean {+ if (typeof node.getAnimations !== 'function') {+ return false;+ }+ const isRidden = riddenAnimators.has(node);+ return node.getAnimations().some(animation => {+ if (animation.playState !== 'running') {+ return false;+ }+ const isTransition = 'transitionProperty' in animation;+ if (!isTransition && !('animationName' in animation)) {+ return false;+ }+ const properties = animatedProperties(animation);+ if (+ isRidden &&+ isTransition &&+ properties.every(property => property === 'translate')+ ) {+ return false;+ }+ return properties.some(property => POSITION_PROPERTIES.has(property));+ });+}++// Whether `node` is a fixed container docked to the viewport's bottom edge.+function isDockedContainer(node: HTMLElement): boolean {+ const view = node.ownerDocument.defaultView;+ return (+ view != null &&+ view.getComputedStyle(node).position === 'fixed' &&+ dockOf(node, view) === 'docked'+ );+}++/**+ * The fixed container docked at the viewport's bottom edge that holds+ * `element`, or null. A container that fills the viewport or floats above+ * the bottom edge is never one.+ */+export function dockedAncestor(element: Element): HTMLElement | null {+ const container = fixedContainerOf(element);+ return container != null && typeof container === 'object'+ ? container.docked+ : null;+}++/**+ * How far a bottom edge at `bottom` sits under the keyboard's top, plus+ * `offset`, CSS px; 0 when it clears it. An overlap under one CSS px is the+ * viewport's rounding, not an obstruction.+ */+export function coveredBy(+ bottom: number,+ height: number,+ offset: number,+ win: Window,+): number {+ const covered = bottom + offset - (layoutViewportHeight(win) - height);+ return height > 0 && covered > KEYBOARD_EPSILON ? covered : 0;+}++// The lift of a ridden target. A Core host (`isHostOwned`) clears the keyboard+// with a focused field inside, the field `offset` above it. An app's docked+// container moves only by the part of it the keyboard still covers. That part+// is measured after any lift the app gives it. So a bar the app already moves+// with the keyboard is not moved again. It is not moved at all once its layout+// leaves the bottom edge. Nor is it moved while the app runs its own CSS+// transition or animation on its position. When a field outside has focus, the+// target rests under the keyboard, so it never covers that field. When focus+// left for nothing, a lifted target rides down with the keyboard, and one at+// rest stays there.+function liftFor(+ target: HTMLElement,+ animator: Animator,+ height: number,+ offset: number,+ win: Window,+ isHostOwned: boolean,+): number {+ // An app's bar it is moving itself is left to the app, never lifted twice.+ if (!isHostOwned && (!isDockedContainer(target) || isMovedByApp(target))) {+ return 0;+ }+ const targetCovered = coveredBy(+ restingBottom(target, animator),+ height,+ 0,+ win,+ );+ const field = focusedFieldIn(target);+ if (field != null) {+ if (!isHostOwned) {+ return targetCovered;+ }+ const fieldCovered = coveredBy(+ restingBottom(field, animator),+ height,+ offset,+ win,+ );+ return Math.max(targetCovered, fieldCovered);+ }+ if (isTextEntryControl(target.ownerDocument.activeElement)) {+ return 0;+ }+ return animator.get('y') < 0 ? targetCovered : 0;+}++// Scrolls `scroller` by `distance` px, up or down, at once. A smooth scroll+// would leave the field covered when Chrome checks it.+function scrollBy(scroller: Element, distance: number, win: Window): void {+ const doc = scroller.ownerDocument;+ if (scroller === (doc.scrollingElement ?? doc.documentElement)) {+ win.scrollBy({top: distance, behavior: 'instant'});+ } else {+ scroller.scrollTop += distance;+ }+}++// How far `field` sits outside the band it must be in. The band is inside its+// scroller's box and the viewport, and `offset` above the keyboard while one+// shows. A move not yet written shifts the field and its scroller by `shift`.+function revealDistance(+ field: Element,+ scroller: Element,+ height: number,+ offset: number,+ win: Window,+ shift = 0,+): number {+ const doc = field.ownerDocument;+ const keyboardTop = layoutViewportHeight(win) - height;+ let safeTop = 0;+ let safeBottom =+ height > KEYBOARD_EPSILON ? keyboardTop - offset : keyboardTop;+ if (scroller !== (doc.scrollingElement ?? doc.documentElement)) {+ const box = scroller.getBoundingClientRect();+ safeTop = Math.max(safeTop, box.top + shift);+ safeBottom = Math.min(safeBottom, box.bottom + shift);+ }+ const box = field.getBoundingClientRect();+ return distanceIntoBand(+ box.top + shift,+ box.bottom + shift,+ safeTop,+ safeBottom,+ );+}++// Scrolls `field` into its band with its nearest scroller, the document+// included. Nothing else moves: a scroller that cannot scroll far enough+// leaves the rest of the field covered.+function reveal(+ field: Element,+ scroller: Element,+ height: number,+ offset: number,+ win: Window,+): void {+ const distance = revealDistance(field, scroller, height, offset, win);+ if (Math.abs(distance) > KEYBOARD_EPSILON) {+ scrollBy(scroller, distance, win);+ }+}++// Focuses the tapped field without the browser's reveal, then raises the+// tap's click. The claimed tap's cancelled `touchend` raises none, and a+// caller's `onClick` still runs once. The click is synthetic: its `isTrusted`+// is false. Like a real tap's click in Chrome and Safari, it is a touch+// `PointerEvent`, or a `MouseEvent` where no `PointerEvent` exists.+function deliverTap(+ control: HTMLElement,+ x: number,+ y: number,+ touch: {screenX: number; screenY: number; identifier: number},+): void {+ focusAtPoint(control, x, y);+ // The field's own window's constructors, as a click in a frame has.+ const view = control.ownerDocument.defaultView;+ const init: MouseEventInit = {+ bubbles: true,+ cancelable: true,+ composed: true,+ detail: 1,+ clientX: x,+ clientY: y,+ screenX: touch.screenX,+ screenY: touch.screenY,+ };+ const PointerClick = view?.PointerEvent;+ const click =+ typeof PointerClick === 'function'+ ? new PointerClick('click', {+ ...init,+ pointerType: 'touch',+ isPrimary: true,+ pointerId: touch.identifier,+ })+ : new (view?.MouseEvent ?? MouseEvent)('click', init);+ control.dispatchEvent(click);+}++// Puts back a pan the browser makes on its own after a keyboard report. This+// happens, for example, after a focus no claim saw: a script's `focus()` while+// nothing has focus. The field sits in place already, so the pan only displaces+// the page.+function watchPans(win: Window, owns: (focused: Element) => boolean) {+ const watch = watchRevealPan(win, {owns});+ let lastHeight = getKeyboardHeight(win);+ return {+ report(height: number): void {+ if (height !== lastHeight) {+ lastHeight = height;+ watch.report();+ } else if (watch.isRevealPan(height)) {+ watch.putBack();+ }+ },+ stop: () => watch.stop(),+ };+}++function focusedFieldIn(target: Element): HTMLElement | null {+ const active = target.ownerDocument.activeElement;+ return active != null &&+ active !== target &&+ target.contains(active) &&+ isTextEntryControl(active)+ ? active+ : null;+}++// Whether this window keeps fields above a keyboard at all: a top-level+// document whose visual viewport shrinks for the keyboard, under a finger.+function followsKeyboard(win: Window | null): win is Window {+ return win != null && isKeyboardMeasurable(win) && isCoarsePointer(win);+}++/** How followKeyboard moves its target. */+export interface FollowKeyboardOptions {+ move: KeyboardMove;+ /** The gap kept between the focused field and the keyboard, CSS px. */+ offset: number;+}++/**+ * Keeps the focused field inside `target` above the keyboard until the+ * returned call. `'ride'` moves `target` with the keyboard, on its slide+ * where the browser reports one. `'reveal'` scrolls the field into place in+ * `target`, a scroller. The target claims focus moves into its fields, so the+ * browser never pans the page to them, and it registers as a keyboard target.+ *+ * @example+ * ```+ * const stop = followKeyboard(dock, {move: 'ride', offset: FIELD_OFFSET});+ * ```+ */+export function followKeyboard(+ target: HTMLElement,+ {move, offset}: FollowKeyboardOptions,+): () => void {+ const doc = target.ownerDocument;+ const win = doc.defaultView;+ if (!followsKeyboard(win)) {+ return () => {};+ }+ const unregister = registerKeyboardTarget(target);+ const stopClaim = refuseFocusReveal(doc, {+ claim: destination =>+ destination instanceof win.HTMLElement &&+ destination !== target &&+ target.contains(destination) &&+ isTextEntryControl(destination)+ ? destination+ : null,+ });+ // A first tap moves focus from nothing, so no blur claims it. The tap+ // route focuses the field itself, without the browser's reveal.+ const stopTaps = claimTapFocus(target, {+ claim: touched => {+ const control = findTextEntryControl(touched, target);+ return control != null && control !== doc.activeElement ? control : null;+ },+ deliver: deliverTap,+ });+ const stopMoving: (isFinal?: boolean) => void =+ move === 'ride'+ ? rideWithKeyboard(target, offset, win, true)+ : revealWithKeyboard(+ target,+ () => focusedFieldIn(target),+ target,+ offset,+ win,+ );+ return () => {+ stopMoving(true);+ stopTaps();+ stopClaim();+ unregister();+ };+}++// Reveals the focused field `field()` returns through `scroller` when the+// keyboard's height changes, now, and when focus moves into `region` with the+// keyboard already up. Returns the call that stops it.+function revealWithKeyboard(+ region: Element,+ field: () => Element | null,+ scroller: Element,+ offset: number,+ win: Window,+): () => void {+ const revealNow = (height: number) => {+ const focused = field();+ if (focused != null) {+ reveal(focused, scroller, height, offset, win);+ }+ };+ const pans = watchPans(win, focused => focused === field());+ // A report within a pixel of the last height comes from a pan, a scroll or+ // a zoom's rounding. The field stays where the person put it.+ let lastHeight = getKeyboardHeight(win);+ const stopReports = subscribeKeyboardHeight(win, event => {+ if (event.type === 'viewport') {+ if (Math.abs(event.height - lastHeight) > KEYBOARD_EPSILON) {+ lastHeight = event.height;+ revealNow(event.height);+ }+ pans.report(event.height);+ }+ });+ const onFocusIn = () => revealNow(getKeyboardHeight(win));+ region.addEventListener('focusin', onFocusIn);+ revealNow(getKeyboardHeight(win));+ return () => {+ stopReports();+ pans.stop();+ region.removeEventListener('focusin', onFocusIn);+ };+}++// Whether `container`'s drawn box is taller than the room above a keyboard+// `height` px tall. A move to the keyboard's top would then push it off the+// top.+function exceedsRoom(+ container: HTMLElement,+ height: number,+ win: Window,+): boolean {+ return (+ height > KEYBOARD_EPSILON &&+ container.getBoundingClientRect().height >+ layoutViewportHeight(win) - height + KEYBOARD_EPSILON+ );+}++// The focused text field in `container` and its scroller there, or null+// when no field inside has focus or no scroller sits between them.+function focusedScrollerIn(+ container: HTMLElement,+): {field: Element; scroller: Element} | null {+ const field = focusedFieldIn(container);+ const scroller = field == null ? null : scrollingAncestor(field, container);+ return field == null || scroller == null ? null : {field, scroller};+}++// The lift of a container taller than the room above the keyboard with no+// scroller around its focused field. It lifts only as far as that field needs+// to sit `offset` above the keyboard. It never lifts past the container's own+// overlap, so a field near its top stays on screen. It keeps liftFor's guards:+// a container that left the bottom edge or that the app is moving gets none.+// When focus left for nothing it never rises and rides down as the keyboard+// goes.+function fieldLift(+ target: HTMLElement,+ animator: Animator,+ height: number,+ offset: number,+ win: Window,+): number {+ if (!isDockedContainer(target) || isMovedByApp(target)) {+ return 0;+ }+ const overlap = coveredBy(restingBottom(target, animator), height, 0, win);+ const field = focusedFieldIn(target);+ if (field == null) {+ // A text field outside has focus: the container rests under the keyboard.+ return isTextEntryControl(target.ownerDocument.activeElement)+ ? 0+ : Math.min(Math.max(0, -animator.get('y')), overlap);+ }+ const need = coveredBy(restingBottom(field, animator), height, offset, win);+ return Math.min(need, overlap);+}++// The ride that moves each target. A new ride on the same target takes over,+// whether the old one still rides or waits for the keyboard to go. So two never+// move one target, and the one taken over never moves it again.+const currentRides = new WeakMap<HTMLElement, () => void>();++// Rides `target` with the keyboard until the returned call (see liftFor).+// `isHostOwned` is true for a Core host's own element, and false for an app's+// docked container. Where the guide publishes the keyboard's slide, the+// target moves on it; elsewhere it takes each report's place. A blur's stop+// waits for the keyboard to go, so the target never drops under a keyboard+// still showing. A final stop, on detach, returns it at once.+function rideWithKeyboard(+ target: HTMLElement,+ offset: number,+ win: Window,+ isHostOwned: boolean,+): (isFinal?: boolean) => void {+ currentRides.get(target)?.();+ const animator = animatorFor(target);+ riddenAnimators.set(target, animator);+ const guide =+ keyboardProfileOf(win) === 'chromium' ? getKeyboardLayoutGuide(win) : null;+ // A ride moves the target while it rides or waits for the keyboard to go.+ // Once it ends, by itself or by a takeover, it never moves the target.+ let state: 'riding' | 'waiting' | 'ended' = 'riding';+ let stopReports: (() => void) | null = null;+ let stopGuide: (() => void) | null = null;+ const pans = watchPans(win, focused => target.contains(focused));+ let frame = 0;+ let pendingSlide: KeyboardTransition | null = null;+ const end = () => {+ state = 'ended';+ stopReports?.();+ stopGuide?.();+ stopReports = null;+ stopGuide = null;+ pans.stop();+ stopFocusIns();+ if (frame !== 0) {+ win.cancelAnimationFrame(frame);+ frame = 0;+ }+ if (currentRides.get(target) === end) {+ currentRides.delete(target);+ }+ };+ currentRides.set(target, end);+ const place = (height: number, transition: KeyboardTransition | null) => {+ if (state === 'ended') {+ return;+ }+ // An app's container taller than the room above the keyboard never rides+ // the whole overlap. A scroller in it reveals the focused field instead.+ // With none, it rides only as far as that field needs.+ const isTooTall = !isHostOwned && exceedsRoom(target, height, win);+ const inside = isTooTall ? focusedScrollerIn(target) : null;+ const lift = !isTooTall+ ? liftFor(target, animator, height, offset, win, isHostOwned)+ : inside == null+ ? fieldLift(target, animator, height, offset, win)+ : 0;+ // Rest is y 0, never -0, so the animator releases its translate there.+ const y = lift > 0 ? -lift : 0;+ // Every box is read before anything is written. The scroller moves with+ // the container, so the reveal measures the field where the move leaves+ // it.+ const revealBy =+ inside == null+ ? 0+ : revealDistance(+ inside.field,+ inside.scroller,+ height,+ offset,+ win,+ y - animator.get('y'),+ );+ if (inside != null && Math.abs(revealBy) > KEYBOARD_EPSILON) {+ scrollBy(inside.scroller, revealBy, win);+ }+ if (y !== 0 || animator.get('y') !== 0) {+ if (transition == null) {+ animator.set({y});+ } else {+ rideKeyboard(animator, {y}, transition);+ }+ }+ // The target is now at rest, or rides there on the keyboard's slide, so+ // a stopped ride only stops listening. A set here would cut the slide.+ if (state === 'waiting' && height <= KEYBOARD_EPSILON) {+ end();+ }+ };+ // A report, a slide or a focus move places the target on the next frame, once+ // every listener of that event has run. An app that moves its own bar in its+ // listener has moved it by then. So the lift measures only what the keyboard+ // still covers, and never stacks on the app's.+ const placeOnNextFrame = (slide: KeyboardTransition | null) => {+ if (slide != null) {+ pendingSlide = slide;+ }+ if (frame !== 0) {+ return;+ }+ frame = win.requestAnimationFrame(() => {+ frame = 0;+ const next = pendingSlide;+ pendingSlide = null;+ place(next?.to ?? guide?.inset ?? getKeyboardHeight(win), next);+ });+ };+ if (guide != null) {+ stopGuide = guide.subscribe(placeOnNextFrame);+ } else {+ stopReports = subscribeKeyboardHeight(win, event => {+ if (event.type === 'viewport') {+ placeOnNextFrame(null);+ pans.report(event.height);+ }+ });+ }+ // A field gaining focus with the keyboard up places the target. A blur to+ // nothing waits for the keyboard's own report or slide, so the target rides+ // down from where it is.+ const stopFocusIns = subscribeInput(win, 'focusin', () =>+ placeOnNextFrame(null),+ );+ placeOnNextFrame(null);+ return (isFinal = false) => {+ if (state === 'ended') {+ return;+ }+ if (isFinal || getKeyboardHeight(win) <= KEYBOARD_EPSILON) {+ end();+ if (animator.get('y') !== 0) {+ animator.set({y: 0});+ }+ } else {+ state = 'waiting';+ }+ };+}++/** How keepFieldAboveKeyboard keeps its field clear. */+export interface KeepFieldAboveKeyboardOptions {+ /** The gap kept between the field and the keyboard, CSS px. */+ offset?: number;+}++// The placement of `field` when it gains focus. A docked container rides.+// Page content, or a fixed container the app positions, reveals the field+// through a scroller. Null keeps the browser's reveal: inside a keyboard+// target, or with no such scroller.+function placementOf(+ field: HTMLElement,+): {ride: HTMLElement} | {reveal: Element} | null {+ if (isInsideKeyboardTarget(field)) {+ return null;+ }+ const container = fixedContainerOf(field);+ if (container === 'floating' || container === 'fills-viewport') {+ return revealWithin(field, nearestFixedAncestor(field));+ }+ if (container == null) {+ // A page with nothing to scroll keeps the browser's own reveal: a claim+ // there would leave the field under the keyboard.+ const scroller = nearestScroller(field);+ return scroller.scrollHeight > scroller.clientHeight+ ? {reveal: scroller}+ : null;+ }+ // A bar the app positions with its own `translate` does not ride: the ride+ // would replace that translate.+ const view = field.ownerDocument.defaultView;+ return view != null && hasOwnTranslate(container.docked, view)+ ? revealWithin(field, container.docked)+ : {ride: container.docked};+}++// A reveal by the scroller between `field` and the fixed `container` the app+// positions, or null when no scroller sits between them.+function revealWithin(+ field: HTMLElement,+ container: HTMLElement | null,+): {reveal: Element} | null {+ const scroller =+ container == null ? null : scrollingAncestor(field, container);+ return scroller == null ? null : {reveal: scroller};+}++/**+ * A field's own path until the returned call. When the field gains focus, it+ * decides where it is. Docked at the viewport's bottom, its fixed container+ * moves up by the part of it the keyboard still covers. In scrolling content,+ * its nearest scroller, the document included, brings it into view, above the+ * keyboard while one shows. A docked container taller than the room above the+ * keyboard never rides its whole overlap. Its scroller there brings the field+ * up instead, and with none it rides only as far as the field needs. A fixed+ * container the app positions fills the viewport, floats above the bottom edge,+ * or sets its own `translate`. In one, a scroller between the field and the+ * container brings it up. A focus move or a tap into the field arrives without+ * the browser's reveal there, so the page never pans for it. Inside a keyboard+ * target, or in such a container with no scroller around the field, the path+ * does nothing and the browser's own reveal stays.+ *+ * @example+ * ```+ * const stop = keepFieldAboveKeyboard(input);+ * ```+ */+export function keepFieldAboveKeyboard(+ field: HTMLElement,+ {offset = FIELD_OFFSET}: KeepFieldAboveKeyboardOptions = {},+): () => void {+ const doc = field.ownerDocument;+ const win = doc.defaultView;+ if (!followsKeyboard(win)) {+ return () => {};+ }+ const stopClaim = refuseFocusReveal(doc, {+ claim: destination =>+ destination === field && placementOf(field) != null ? field : null,+ });+ // A first tap moves focus from nothing, so no blur claims it.+ const stopTaps = claimTapFocus(field, {+ claim: () =>+ doc.activeElement !== field && placementOf(field) != null ? field : null,+ deliver: deliverTap,+ });+ let stopSession: ((isFinal?: boolean) => void) | null = null;+ // A ride a blur stopped can still wait for the keyboard to go; a detach+ // ends it at once.+ let stoppedSession: ((isFinal?: boolean) => void) | null = null;+ const onFocus = () => {+ // A claimed focus move raises a second focus event; the session stands.+ if (stopSession != null) {+ return;+ }+ const placement = placementOf(field);+ if (placement == null) {+ return;+ }+ stopSession =+ 'ride' in placement+ ? rideWithKeyboard(placement.ride, offset, win, false)+ : revealWithKeyboard(+ field,+ () => (doc.activeElement === field ? field : null),+ placement.reveal,+ offset,+ win,+ );+ };+ const onBlur = () => {+ stopSession?.();+ stoppedSession = stopSession ?? stoppedSession;+ stopSession = null;+ };+ field.addEventListener('focus', onFocus);+ field.addEventListener('blur', onBlur);+ return () => {+ field.removeEventListener('focus', onFocus);+ field.removeEventListener('blur', onBlur);+ stopSession?.(true);+ stoppedSession?.(true);+ stopSession = null;+ stoppedSession = null;+ stopTaps();+ stopClaim();+ };+}diff --git a/packages/core/src/keyboard/revealBand.test.ts b/packages/core/src/keyboard/revealBand.test.tsnew file mode 100644index 0000000000..4e00521901--- /dev/null+++ b/packages/core/src/keyboard/revealBand.test.ts@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file revealBand.test.ts+ * @input revealBand.ts+ * @output Tests for distanceIntoBand: both edges, a box that fits, a box+ * taller than the band and an empty band+ * @position Keyboard module tests+ */++import {describe, expect, it} from 'vitest';+import {distanceIntoBand} from './revealBand';++describe('distanceIntoBand', () => {+ it('scrolls a box below the band up by how far its bottom overhangs', () => {+ expect(distanceIntoBand(500, 540, 0, 451)).toBe(89);+ });++ it('scrolls a box above the band down by how far its top overhangs', () => {+ expect(distanceIntoBand(-120, -80, 0, 451)).toBe(-120);+ expect(distanceIntoBand(40, 80, 64, 451)).toBe(-24);+ });++ it('leaves a box that fits', () => {+ expect(distanceIntoBand(100, 140, 0, 451)).toBe(0);+ });++ it('keeps a box taller than the band by its bottom edge', () => {+ expect(distanceIntoBand(-50, 600, 0, 451)).toBe(149);+ });++ it('moves nothing when the band is empty', () => {+ expect(distanceIntoBand(500, 540, 300, 300)).toBe(0);+ expect(distanceIntoBand(500, 540, 300, 200)).toBe(0);+ });+});diff --git a/packages/core/src/keyboard/revealBand.ts b/packages/core/src/keyboard/revealBand.tsnew file mode 100644index 0000000000..f30201d457--- /dev/null+++ b/packages/core/src/keyboard/revealBand.ts@@ -0,0 +1,38 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file revealBand.ts+ * @input A box's top and bottom edges and a band's, CSS px+ * @output distanceIntoBand, the scroll that brings the box inside the band+ * @position Keyboard module, internal to core. A field's reveal and the+ * Tall sheet's reveal share it.+ */++/**+ * How far content must scroll so a box from `top` to `bottom` sits inside the+ * band from `safeTop` to `safeBottom`, CSS px. A positive distance scrolls it+ * up and a negative one down. It is 0 when the box fits or the band is empty. A+ * box taller than the band keeps its bottom edge in it.+ *+ * @example+ * ```+ * const distance = distanceIntoBand(rect.top, rect.bottom, 0, keyboardTop - 17);+ * ```+ */+export function distanceIntoBand(+ top: number,+ bottom: number,+ safeTop: number,+ safeBottom: number,+): number {+ if (safeBottom <= safeTop) {+ return 0;+ }+ if (bottom > safeBottom) {+ return bottom - safeBottom;+ }+ if (top < safeTop) {+ return top - safeTop;+ }+ return 0;+}diff --git a/packages/core/src/keyboard/useMobileKeyboard.target.test.tsx b/packages/core/src/keyboard/useMobileKeyboard.target.test.tsxnew file mode 100644index 0000000000..b1d253196d--- /dev/null+++ b/packages/core/src/keyboard/useMobileKeyboard.target.test.tsx@@ -0,0 +1,117 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useMobileKeyboard.target.test.tsx+ * @input useMobileKeyboard on a field, a stand-in visual viewport and a+ * pointer query that changes+ * @output Proves a field's keyboard path follows the primary pointer: a+ * docked mouse drops the tap route, and a finger brings it back+ * @position Keyboard module tests+ */++import {useRef} from 'react';+import {afterEach, beforeEach, expect, it, vi} from 'vitest';+import {act, render, screen} from '@testing-library/react';+import {__resetLayoutViewportForTest} from '../utils/layoutViewport';+import {useMobileKeyboard} from './useMobileKeyboard';++let isCoarse = true;+const listeners = new Set<() => void>();++function Field() {+ const ref = useRef<HTMLInputElement | null>(null);+ useMobileKeyboard(ref);+ return <input ref={ref} aria-label="Name" />;+}++beforeEach(() => {+ isCoarse = true;+ // The page scrolls, so a field in it takes the field path's reveal.+ const page = document.scrollingElement ?? document.documentElement;+ Object.defineProperty(page, 'scrollHeight', {+ configurable: true,+ value: 3000,+ });+ Object.defineProperty(page, 'clientHeight', {+ configurable: true,+ value: window.innerHeight,+ });+ Object.defineProperty(window, 'visualViewport', {+ configurable: true,+ value: Object.assign(new EventTarget(), {+ height: window.innerHeight,+ offsetTop: 0,+ scale: 1,+ }),+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ get matches() {+ return query.includes('pointer: coarse') ? isCoarse : false;+ },+ media: query,+ onchange: null,+ addEventListener: (_type: string, listener: () => void) =>+ listeners.add(listener),+ removeEventListener: (_type: string, listener: () => void) =>+ listeners.delete(listener),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+});++afterEach(() => {+ listeners.clear();+ const page = document.scrollingElement ?? document.documentElement;+ Reflect.deleteProperty(page, 'scrollHeight');+ Reflect.deleteProperty(page, 'clientHeight');+ Reflect.deleteProperty(window, 'visualViewport');+ __resetLayoutViewportForTest();+ vi.unstubAllGlobals();+});++// Whether a one-finger tap on `element` had its default cancelled.+function tapIsClaimed(element: HTMLElement): boolean {+ const touch = (type: string) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const point = {identifier: 0, clientX: 20, clientY: 10};+ Object.assign(event, {+ touches: type === 'touchend' ? [] : [point],+ changedTouches: [point],+ });+ return event;+ };+ act(() => {+ element.dispatchEvent(touch('touchstart'));+ });+ const end = touch('touchend');+ act(() => {+ element.dispatchEvent(end);+ });+ return end.defaultPrevented;+}++function pointerChanges(coarse: boolean) {+ isCoarse = coarse;+ act(() => {+ for (const listener of [...listeners]) {+ listener();+ }+ });+}++it('drops the tap route when a mouse becomes the primary pointer, and takes it back for a finger', () => {+ render(<Field />);+ const input = screen.getByRole('textbox');+ expect(tapIsClaimed(input)).toBe(true);+ act(() => input.blur());++ pointerChanges(false);+ expect(tapIsClaimed(input)).toBe(false);++ pointerChanges(true);+ expect(tapIsClaimed(input)).toBe(true);+});diff --git a/packages/core/src/keyboard/useMobileKeyboard.ts b/packages/core/src/keyboard/useMobileKeyboard.tsindex c753b2c74f..b5348d35f2 100644--- a/packages/core/src/keyboard/useMobileKeyboard.ts+++ b/packages/core/src/keyboard/useMobileKeyboard.ts@@ -17,7 +17,12 @@ import {useCallback, useEffect, useRef, useState, type RefObject} from 'react';import {flushSync} from 'react-dom';import {useAttachment} from '../hooks/useAttachment';import {useMediaQuery} from '../hooks/useMediaQuery';-import {animatorFor, type Animator} from '../motion/animator';+import {+ animatorFor,+ type Animator,+ type MotionHandle,+} from '../motion/animator';+import {KEYBOARD_SPRING} from '../motion/uikit/springs';import {subscribeInput} from '../utils/inputStream';import {layoutViewportHeight} from '../utils/layoutViewport';import {isDocument, isNode} from '../utils/nodeType';@@ -33,8 +38,22 @@ import {subscribeKeyboardHeight,watchRevealPan,} from './keyboardHeight';-import {getKeyboardLayoutGuide, keyboardProfileOf} from './keyboardLayoutGuide';+import {+ bringsUpKeyboard,+ getKeyboardLayoutGuide,+ hidesField,+ keyboardProfileOf,+} from './keyboardLayoutGuide';import type {KeyboardTransition} from './keyboardModel';+import {+ FIELD_OFFSET,+ drawnOffsetOf,+ followKeyboard,+ keepFieldAboveKeyboard,+ registerKeyboardTarget,+ type KeyboardMove,+} from './keyboardTarget';+import {distanceIntoBand} from './revealBand';import {rideKeyboard} from './rideKeyboard';// Chrome on Android pans the page itself if the keyboard still covers the@@ -47,10 +66,13 @@ const FIELD_CLEARANCE_AT_REPORT = 4;/** How a target keeps a focused field above the on-screen keyboard. */export interface MobileKeyboardOptions {/**- * How the target moves the field: `'ride'` reveals it with the scroller- * and rides the scroller's content on the keyboard's slide.+ * How the target moves the field. `'ride'` moves the target with the+ * keyboard; with `inset`, it reveals the field with the scroller and rides+ * the scroller's content instead. `'reveal'` scrolls the field into place+ * in the target, a scroller. Without `move`, the target is a field itself,+ * which decides where it is when it gains focus.*/- move: 'ride';+ move?: KeyboardMove;/*** Reserves the keyboard's inset at the end of the target's scroll area,* the first element inside it that `useScrollableArea` marks with@@ -58,15 +80,15 @@ export interface MobileKeyboardOptions {*/inset?: boolean;/** The gap kept between the focused field and the keyboard, CSS px. */- offset: number;+ offset?: number;/** Whether the target follows the keyboard at all. */- isEnabled: boolean;+ isEnabled?: boolean;/** Whether the target is at its full height, where it reveals fields. */- isExpanded: boolean;+ isExpanded?: boolean;/** Whether the target is open. Focus that leaves for nothing parks on it. */- isOpen: boolean;+ isOpen?: boolean;/** Whether the page's own scroll is locked under the target. */- isPageScrollLocked: boolean;+ isPageScrollLocked?: boolean;}/** What useMobileKeyboard returns. */@@ -118,6 +140,13 @@ function isVisualViewportRecovered(): boolean {return getKeyboardHeight(window) <= 0.5;}+// Whether focus on `target` may keep the keyboard up. A control that brings+// one up does, and so can a frame, an open shadow host or a custom element,+// through its own field.+function mayKeepKeyboard(target: Element | null): boolean {+ return target != null && (bringsUpKeyboard(target) || hidesField(target));+}+/*** Keeps a focused field in `targetRef`'s element above the on-screen* keyboard (see README.md). A sheet passes its panel, and the hook reserves@@ -133,13 +162,14 @@ function isVisualViewportRecovered(): boolean {export function useMobileKeyboard(targetRef: RefObject<HTMLElement | null>,{+ move,inset: reservesInset = false,- offset,- isEnabled,- isExpanded,- isOpen,- isPageScrollLocked,- }: MobileKeyboardOptions,+ offset = FIELD_OFFSET,+ isEnabled = true,+ isExpanded = true,+ isOpen = true,+ isPageScrollLocked = false,+ }: MobileKeyboardOptions = {},): MobileKeyboard {// The inset the keyboard takes at the end of the body's content, CSS px.// The target lays it out after its content box's children, through a@@ -192,6 +222,20 @@ export function useMobileKeyboard(}}, [dismiss, isEnabled, isOpen]);+ // A docked target, a scroller or a field, which moves no inset.+ useAttachment(+ targetRef,+ target => {+ if (!isEnabled || reservesInset || !isTouch) {+ return () => {};+ }+ return move == null+ ? keepFieldAboveKeyboard(target, {offset})+ : followKeyboard(target, {move, offset});+ },+ `${isEnabled}|${move}|${reservesInset}|${offset}|${isTouch}`,+ );+useAttachment(targetRef,sheet => {@@ -199,6 +243,8 @@ export function useMobileKeyboard(if (!isEnabled || !reservesInset || body == null) {return () => {};}+ // A field inside the sheet moves nothing itself.+ const unregister = registerKeyboardTarget(sheet);let keyboardGeometry: KeyboardGeometry | null = null;// Where a smooth reveal under way is taking the body's scrollTop.@@ -231,11 +277,7 @@ export function useMobileKeyboard(// frame.const rideOffset = () => {const content = body.firstElementChild;- if (!(content instanceof HTMLElement)) {- return 0;- }- const translate = getComputedStyle(content).translate;- return parseFloat(translate.split(' ')[1] ?? '') || 0;+ return content instanceof HTMLElement ? drawnOffsetOf(content) : 0;};// The keyboard's show the guide plays on its slide right now, if any. At// a report, a show whose slide has ended counts too. A busy page can read@@ -251,8 +293,13 @@ export function useMobileKeyboard(? transition: null;};- // A hide the hook holds the inset through (see holdInsetThrough).- let heldHide: {readonly release: () => void} | null = null;+ // A hide the hook holds the inset through (see holdInsetThrough and+ // holdThroughUnguidedHide). `onReveal` answers whether a reveal during+ // the hold goes on.+ let heldHide: {+ readonly release: () => void;+ readonly onReveal?: () => boolean;+ } | null = null;let documentScrollAtKeyboard: {x: number; y: number} | null = null;// The keyboard's top and the body's scroll when the keyboard came up. A// keyboard that closes puts the body back at that scroll.@@ -380,9 +427,6 @@ export function useMobileKeyboard(measuredBodyRect.bottom,obstructionTop - clearance,);- if (safeBottom <= safeTop) {- return;- }// Where the control will be once a smooth reveal under way lands. If// that lands the control, a second scroll would overshoot in Firefox.@@ -392,9 +436,15 @@ export function useMobileKeyboard(const pending = smoothDistanceLeft() + rideOffset();const controlBottom = measuredControlRect.bottom - pending;const controlTop = measuredControlRect.top - pending;- if (controlBottom > safeBottom) {+ const distance = distanceIntoBand(+ controlTop,+ controlBottom,+ safeTop,+ safeBottom,+ );+ if (distance > 0) {scrollBodyBy(- controlBottom - safeBottom,+ distance,smoothly,ride,Math.max(@@ -402,8 +452,8 @@ export function useMobileKeyboard(obstructionTop - safeBottom - FIELD_CLEARANCE_AT_REPORT,),);- } else if (controlTop < safeTop) {- scrollBodyBy(controlTop - safeTop, smoothly, ride);+ } else if (distance < 0) {+ scrollBodyBy(distance, smoothly, ride);}};@@ -456,7 +506,7 @@ export function useMobileKeyboard(const revealFocusedControl = (atReport = false) => {// Through a hide the sheet rides, its layout holds until the end.- if (heldHide != null) {+ if (heldHide != null && heldHide.onReveal?.() !== true) {return;}const obstructionTop = getObstructionTop();@@ -473,15 +523,30 @@ export function useMobileKeyboard(// restored body, because it may not be the field that opened the// keyboard.if (hasKeyboardLayoutRef.current && isVisualViewportRecovered()) {+ const settle = keepDrawnPlace();clearKeyboardLayout();if (isExpandedRef.current && focusedControl != null) {scrollControlIntoSafeArea(focusedControl, false);}+ settle();return;}if (!isExpandedRef.current || focusedControl == null) {if (retainKeyboardLayoutRef.current && keyboardGeometry) {+ const settle = keepDrawnPlace();applyKeyboardGeometry(keyboardGeometry);+ settle();+ // Focus left for a control that brings up no keyboard, so the+ // keyboard goes down now. A select's picker takes the keyboard's+ // place instead. A frame, an open shadow host or a custom element+ // can hold a field that keeps it up.+ if (+ isExpandedRef.current &&+ hasKeyboardLayoutRef.current &&+ !mayKeepKeyboard(document.activeElement)+ ) {+ holdThroughUnguidedHide();+ }return;}clearKeyboardLayout();@@ -580,11 +645,113 @@ export function useMobileKeyboard(return resting;};+ // Without the guide, as in iOS Safari and Firefox for Android, nothing+ // publishes the keyboard's slide down. iOS Safari sends one report once+ // the keyboard is gone, about half a second after a blur. Under a coarse+ // primary pointer, the content then moves on UIKit's keyboard spring,+ // never at once.+ const unguidedAnimator = (): Animator | null => {+ const content = body.firstElementChild;+ return ownsFocusTransitions &&+ guide == null &&+ content instanceof HTMLElement+ ? animatorFor(content)+ : null;+ };+ const rideKeyboardSpring = (+ animator: Animator,+ y: number,+ ): MotionHandle => {+ return animator.animate({y}, {spring: KEYBOARD_SPRING});+ };+ // Keeps the content drawn where it is across a change of the body's+ // scroll, then rides it to its new place on the keyboard's spring. A+ // report of the keyboard gone, with no ride under way, moves the content+ // this way.+ const keepDrawnPlace = (): (() => void) => {+ const animator = unguidedAnimator();+ if (animator == null) {+ return () => {};+ }+ const drawnBefore = animator.get('y') - body.scrollTop;+ return () => {+ const y = drawnBefore + body.scrollTop;+ if (Math.abs(y - animator.get('y')) < 0.5) {+ return;+ }+ animator.set({y});+ void rideKeyboardSpring(animator, 0);+ };+ };++ // A field that loses focus to nothing takes the keyboard down. Without+ // the guide, the content rides down to its resting scroll from the blur.+ // It rides on the keyboard's spring, as the keyboard does. The inset and+ // the scroll stay meanwhile. Once the keyboard is gone (its report), the+ // inset drops and the scroll goes back with the translate in one commit.+ // So nothing moves then. A ride not yet landed goes on from there at the+ // same speed. A control that takes focus first and brings up a keyboard+ // or a picker keeps that space covered, so the content rides back up.+ // Focus moving into a frame, an open shadow host or a custom element+ // does too: a field there can keep the keyboard.+ const holdThroughUnguidedHide = () => {+ const animator = unguidedAnimator();+ if (animator == null || heldHide != null) {+ return;+ }+ const drop = body.scrollTop - restingScrollTop();+ if (drop === 0) {+ return;+ }+ const hold = {+ release: () => {+ if (heldHide === hold) {+ heldHide = null;+ }+ },+ onReveal: () => {+ const active = document.activeElement;+ if (+ active instanceof HTMLElement &&+ body.contains(active) &&+ mayKeepKeyboard(active)+ ) {+ hold.release();+ void rideKeyboardSpring(animator, 0);+ return true;+ }+ if (isVisualViewportRecovered()) {+ hold.release();+ const y = animator.get('y');+ const velocity = animator.getVelocity('y');+ const scrollBefore = body.scrollTop;+ clearKeyboardLayout();+ // The scroll's drop moved the layout down by `shift`.+ const shift = scrollBefore - body.scrollTop;+ if (Math.abs(y - shift) < 0.5) {+ animator.set({y: 0});+ } else {+ animator.set({y: y - shift});+ void animator.animate(+ {y: 0},+ {spring: KEYBOARD_SPRING, velocity: {y: velocity}},+ );+ }+ }+ return false;+ },+ };+ heldHide = hold;+ void rideKeyboardSpring(animator, drop);+ };+// Through a hide on the keyboard's slide, the inset stays, so nothing// drops while the keyboard still covers the sheet's bottom. The content// rides down on the hide's curve by the scroll the body drops at rest. At// rest, the inset drops, the scroll goes back, and the translate clears in- // one commit.+ // one commit. A busy page reads Chrome's report of the keyboard gone+ // after the slide. Until then the content stays where the slide leaves+ // it, and the report commits.const holdInsetThrough = (transition: KeyboardTransition) => {heldHide?.release();const animator = contentAnimator();@@ -594,6 +761,11 @@ export function useMobileKeyboard(? rideKeyboard(animator, {y: drop}, transition): null;let timer: ReturnType<typeof setTimeout> | undefined;+ let landed = false;+ const commit = () => {+ revealFocusedControl();+ animator?.set({y: 0});+ };const hold = {release: () => {clearTimeout(timer);@@ -601,21 +773,31 @@ export function useMobileKeyboard(heldHide = null;}},+ onReveal: () => {+ if (landed && isVisualViewportRecovered()) {+ hold.release();+ commit();+ }+ return false;+ },};heldHide = hold;- const commit = () => {+ const land = () => {if (heldHide !== hold) {return;}- heldHide = null;- revealFocusedControl();- animator?.set({y: 0});+ landed = true;+ if (hasKeyboardLayoutRef.current && !isVisualViewportRecovered()) {+ return;+ }+ hold.release();+ commit();};if (handle == null) {const end = transition.start + (transition.curve?.durationMs ?? 0);- timer = setTimeout(commit, Math.max(0, end - performance.now()));+ timer = setTimeout(land, Math.max(0, end - performance.now()));} else {- void handle.finished.then(commit);+ void handle.finished.then(land);}};const unsubscribeGuide = guide?.subscribe(transition => {@@ -840,12 +1022,13 @@ export function useMobileKeyboard(scheduleReveal();return () => {+ unregister();cancelAnimationFrame(animationFrame);stopClaiming?.();unsubscribe();unsubscribeGuide?.();heldHide?.release();- contentAnimator()?.set({y: 0});+ (contentAnimator() ?? unguidedAnimator())?.set({y: 0});revealPan?.stop();body.removeEventListener('focusin', handleFocusIn);body.removeEventListener('focusout', handleFocusOut);diff --git a/packages/core/src/utils/clickGuard.ts b/packages/core/src/utils/clickGuard.tsindex 8bd9f8aa70..5ba2e68db8 100644--- a/packages/core/src/utils/clickGuard.ts+++ b/packages/core/src/utils/clickGuard.ts@@ -7,8 +7,9 @@* @output armClickGuard (and its ClickGuardOptions), disarmClickGuard,* isClickGuardArmed, withoutClickGuard and CLICK_GUARD_WINDOW_MS* @position The one guard for the browser's click after a gesture that- * already acted, shared by hooks/useMenuPress.ts, gestures/GestureHost.ts- * and utils/boxHold.ts+ * already acted, shared by hooks/useMenuPress.ts, gestures/GestureHost.ts,+ * utils/boxHold.ts and the keyboard module's tap route+ * (keyboard/keyboardHeight.ts)** SYNC: When modified, update clickGuard.test.ts, hooks/useMenuPress.ts,* gestures/GestureHost.ts and utils/boxHold.ts.diff --git a/packages/core/src/utils/scrollingAncestor.test.ts b/packages/core/src/utils/scrollingAncestor.test.tsnew file mode 100644index 0000000000..a9868cb9e9--- /dev/null+++ b/packages/core/src/utils/scrollingAncestor.test.ts@@ -0,0 +1,46 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, describe, expect, it} from 'vitest';+import {scrollingAncestor} from './scrollingAncestor';++// A box whose content is `content` px tall in a `height` px box.+function box(overflowY: string, height: number, content: number) {+ const node = document.createElement('div');+ node.style.overflowY = overflowY;+ Object.defineProperty(node, 'clientHeight', {value: height});+ Object.defineProperty(node, 'scrollHeight', {value: content});+ return node;+}++describe('scrollingAncestor', () => {+ afterEach(() => {+ document.body.replaceChildren();+ });++ it('finds the nearest ancestor that scrolls on the block axis, past one that clips and one with nothing to scroll', () => {+ const scroller = box('auto', 200, 600);+ const clipping = box('hidden', 200, 600);+ const short = box('scroll', 200, 200);+ const field = document.createElement('input');+ short.append(field);+ clipping.append(short);+ scroller.append(clipping);+ document.body.append(scroller);+ expect(scrollingAncestor(field)).toBe(scroller);+ });++ it('stops after the bound: a scroller beyond it does not count, and the bound itself does', () => {+ const outer = box('auto', 200, 600);+ const bound = box('visible', 200, 200);+ const field = document.createElement('input');+ bound.append(field);+ outer.append(bound);+ document.body.append(outer);+ expect(scrollingAncestor(field, bound)).toBeNull();+ const scrollingBound = box('auto', 200, 600);+ const inner = document.createElement('input');+ scrollingBound.append(inner);+ outer.append(scrollingBound);+ expect(scrollingAncestor(inner, scrollingBound)).toBe(scrollingBound);+ });+});diff --git a/packages/core/src/utils/scrollingAncestor.ts b/packages/core/src/utils/scrollingAncestor.tsnew file mode 100644index 0000000000..47369dc251--- /dev/null+++ b/packages/core/src/utils/scrollingAncestor.ts@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file scrollingAncestor.ts+ * @input An element, and an optional ancestor where the walk stops.+ * @output The element's nearest ancestor that scrolls on the block axis.+ * @position Shared by the keyboard module's reveals and Outline's scroll spy.+ */++import {SCROLLABLE_OVERFLOW} from './scrollView';++/**+ * The nearest ancestor of `element` that scrolls on the block axis: its+ * `overflow-y` lets it scroll and its content is taller than its box. The walk+ * ends after `bound` when one is given, and at the document's root otherwise.+ * Null when no ancestor in that range scrolls.+ */+export function scrollingAncestor(+ element: Element,+ bound?: Element | null,+): HTMLElement | null {+ const view = element.ownerDocument.defaultView;+ if (view == null) {+ return null;+ }+ for (+ let node = element.parentElement;+ node != null;+ node = node.parentElement+ ) {+ if (+ SCROLLABLE_OVERFLOW.has(view.getComputedStyle(node).overflowY) &&+ node.scrollHeight > node.clientHeight+ ) {+ return node;+ }+ if (node === bound) {+ return null;+ }+ }+ return null;+}diff --git a/packages/core/src/utils/selectionLock.ts b/packages/core/src/utils/selectionLock.tsindex 84e8c80d08..3344c2a649 100644--- a/packages/core/src/utils/selectionLock.ts+++ b/packages/core/src/utils/selectionLock.ts@@ -358,7 +358,7 @@ function isInButton(node: Node): boolean {}/** The caret position the engine puts at a point, by either query. */-function caretAt(+export function caretAt(doc: Document,x: number,y: number,