An open source design system that's fully customizable and agent ready
TypeScript
feat(core): one on-screen keyboard module; a Tall BottomSheet reads it and rides Gboard's slides (#8559)
Christopher Chedeau0588a1342837
diff --git a/.changeset/bottomsheet-rides-gboard.md b/.changeset/bottomsheet-rides-gboard.mdnew file mode 100644index 0000000000..37e9f251c6--- /dev/null+++ b/.changeset/bottomsheet-rides-gboard.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[feat] In Chrome on Android, on a touch screen, a Tall BottomSheet places the focused field just above the on-screen keyboard when Chrome reports it, then rides the rest of Gboard's slide; through the hide the sheet's scroll room stays while its content rides down, so nothing jumps while the keyboard is still on screen. Under Reduce Motion it cross-fades instead of moving. The browser-support guide says so.++@vjeuxdiff --git a/.changeset/browser-support-on-screen-keyboard.md b/.changeset/browser-support-on-screen-keyboard.mdnew file mode 100644index 0000000000..73b3eeb36e--- /dev/null+++ b/.changeset/browser-support-on-screen-keyboard.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] The browser-support guide has a section on the on-screen keyboard: a fully expanded Tall BottomSheet measures it as the layout viewport's height minus the visual viewport's, and keeps the focused field above it in Safari on iOS, Firefox for Android and Chrome on Android. In Chrome, by default (`interactive-widget=resizes-visual`), the sheet adds its scroll room once Chrome reports the keyboard; with `interactive-widget=resizes-content` Chrome shrinks the page for the keyboard itself and the sheet changes nothing. Your app owns its viewport `<meta>` element; Astryx never sets it.++@vjeuxdiff --git a/.changeset/keyboard-one-source.md b/.changeset/keyboard-one-source.mdnew file mode 100644index 0000000000..e23ca79fda--- /dev/null+++ b/.changeset/keyboard-one-source.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet reads the on-screen keyboard from core's shared keyboard module. It now takes over focus moves into a fully expanded Tall sheet wherever a top-level document has a visual viewport and the primary pointer is coarse, Chrome and Firefox on Android included, instead of only under an iOS user agent. A pinch zoom no longer reads as a keyboard, and a pinch-zoomed page still reads the keyboard's full height. The sheet lays its keyboard room out through its own style rather than a CSS custom property. The browser-support guide documents Chrome on Android's `interactive-widget` viewport setting.++@vjeuxdiff --git a/docs/specs/AST-099-mobile-keyboard/spec.md b/docs/specs/AST-099-mobile-keyboard/spec.mdindex e56402c7db..a7559aa516 100644--- a/docs/specs/AST-099-mobile-keyboard/spec.md+++ b/docs/specs/AST-099-mobile-keyboard/spec.md@@ -43,7 +43,11 @@ affects_consumer_docs:"packages/core/src/CommandPalette/**","packages/core/src/Chat/ChatComposer.tsx","packages/core/src/Chat/ChatComposerInput.tsx",- "packages/core/src/Chat/ChatLayout.tsx"+ "packages/core/src/Chat/ChatLayout.tsx",+ "packages/core/src/keyboard/**",+ "packages/core/src/motion/android/**",+ "packages/core/src/utils/layoutViewport.ts",+ "packages/core/src/utils/layoutViewport.test.ts"]}```@@ -142,7 +146,14 @@ app to turn on.keyboard-aware surfaces ride the keyboard on show and on hide: they move withthe keyboard's slide, within one frame of it on the measured keyboards, withno one-step jump and no surface left under the keyboard, no JavaScript per- frame, and one layout commit at rest (FR3). Under reduced motion nothing+ frame, and one layout commit at rest (FR3). Two exceptions apply (DEC-6). In+ Chrome on Android, at the keyboard's first report the content is placed in+ one frame so the focused field's bottom sits just above the keyboard's top,+ then rides the rest of the keyboard's slide. Chrome pans the page itself if+ the field is still below the keyboard about 100–170 ms after the report, so+ a slide cannot be relied on. In Chrome on Android, a hide nothing on the+ page predicts, such as Back, is reported partway through the keyboard's+ slide; the content rides down from that report. Under reduced motion nothingtravels with the keyboard, and the change follows `design:reduced-motion`DR2, a cross-fade on a touch screen. A Lab surface commits the resting value without riding(`architecture:react-component-runtime` INV11). Astryx never overrides@@ -256,15 +267,12 @@ app to turn on.## Current-state impact-- BottomSheet's internal keyboard hook implements FR2, FR4, and FR5 for a- fully expanded Tall sheet on iOS, detects iOS from the user agent, and writes- a private inset on the sheet body as the custom property- `--_sheet-keyboard-inset`, which retires: the sheet applies the height- through a functional style on its own element. It moves into Core's- keyboard module, `packages/core/src/keyboard/`, the single source- `architecture:react-component-runtime` INV11 names: FR6 replaces the- user-agent check, FR3 keeps the height internal, and BottomSheet consumes the- shared source (`component:BottomSheet`).+- BottomSheet's keyboard hook lives in Core's keyboard module,+ `packages/core/src/keyboard/`, the single source+ `architecture:react-component-runtime` INV11 names. It implements FR2, FR4,+ and FR5 for a fully expanded Tall sheet, decides by capability (FR6), and+ applies the height through a functional style on the sheet's own element+ (FR3). BottomSheet consumes it (`component:BottomSheet`).- No other component on `main` measures the keyboard; BaseTypeahead reads thevisual-viewport height only to size its list (Gap 4). A component that laterresponds to the keyboard uses the same height (FR1).@@ -297,14 +305,14 @@ app to turn on.- Layer caps do not account for the keyboard: `spec:AST-059` owns layergeometry, and keeping Popover and other anchor-mode layers above the keyboardis an amendment to that record that consumes this height.-- Today's hook omits FR2's zoom term, so a pinch-zoomed page reads as a- keyboard; FR2 corrects that.-- Today's hook gates only its focus claim on an iOS user agent. Under FR8, a- fully expanded Tall sheet in- Chrome on Android keeps the keyboard accommodation `BottomSheet.doc.mjs`- documents and moves with the keyboard, so no consumer loses behavior and no- breaking change applies; `BottomSheet.doc.mjs` states each platform's- behavior. Firefox for Android gets FR2–FR5.+- The keyboard module's height includes FR2's zoom term, so a pinch-zoomed+ page does not read as a keyboard.+- The hook claims focus under a coarse pointer wherever the keyboard can be+ measured; no user-agent check gates it. Under FR8, a fully expanded Tall+ sheet in Chrome on Android keeps the keyboard accommodation+ `BottomSheet.doc.mjs` documents and moves with the keyboard, so no consumer+ loses behavior and no breaking change applies; `BottomSheet.doc.mjs` states+ each platform's behavior. Firefox for Android gets FR2–FR5.- No public API exposes the keyboard height, and FR3 keeps it that way.- The consumer documentation gains the Android viewport setting (FR8).@@ -312,10 +320,10 @@ app to turn on.No covered field meets FR9 on `main`. Each gap below is open.-- **Gap 1 — The keyboard module.** `packages/core/src/keyboard/` does not- exist. The only keyboard handling is BottomSheet's internal hook, which acts- only in a fully expanded Tall sheet and gates its focus claim on an iOS user- agent.+- **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).- **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.@@ -327,19 +335,18 @@ No covered field meets FR9 on `main`. Each gap below is open.itself to size its list, outside the keyboard module.- **Gap 5 — Tokenizer's sheet search field.** Partly met: the field sits in aTall sheet, so BottomSheet's hook covers it only when the sheet is fully- expanded and only on an iOS user agent. Chrome and Firefox on Android, and a- partly expanded sheet, get nothing.+ expanded. A partly expanded sheet gets nothing.- **Gap 6 — The search row of Selector and MultiSelector.** On a coarsepointer the row sits in a `hug` BottomSheet, which BottomSheet's hook doesnot cover, and it has no keyboard handling of its own.- **Gap 7 — PowerSearch.** On a compact coarse-pointer screen its defaultpresentation is its sheet flow (`component:PowerSearch` DEC-3): Tall bottom- sheets, where BottomSheet's hook partly covers the search and value fields, as- Gap 5 states for Tokenizer. Its query input (Gap 4) and the text and number- fields of its popover value editor render there only with- `presentation="popover"`, and everywhere else by default; they have no- keyboard handling. Keeping the popover itself above the keyboard is- `spec:AST-059`'s.+ sheets, where BottomSheet's hook covers the search and value fields only+ while the sheet is fully expanded, as Gap 5 states for Tokenizer. Its query+ input (Gap 4) and the text and number fields of its popover value editor+ render there only with `presentation="popover"`, and everywhere else by+ default; they have no keyboard handling. Keeping the popover itself above the+ keyboard is `spec:AST-059`'s.- **Gap 8 — CommandPalette's search input.** It sits in a Dialog and has nokeyboard handling.- **Gap 9 — ChatComposer's input.** ChatLayout docks the composer with a fixed@@ -352,9 +359,9 @@ No covered field meets FR9 on `main`. Each gap below is open.that 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 on `main`. The keyboard module that would carry the ride- does not exist (Gap 1), 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+ 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 pxabove the keyboard in the frame the keyboard is reported, no field adds themissing scroll range at its scroller's end, and ChatLayout's dock does notapply the keyboard height. BottomSheet's inset stays local to its own sheet.@@ -379,7 +386,7 @@ that sets its own `translate`, to the app.| 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 || FR7 | Tests in an iframe and in a top-level document | the same keyboard event sequence in both | A non-zero value or a claimed focus inside an iframe |-| FR8 | Chrome on Android in the emulator with Gboard, top-level document, plus a consumer documentation check | keyboard show and hide with the composer and a Tall sheet; a Lab bottom search field; reduced motion on; focus inside a keyboard-aware field, which rides by the visual-viewport height; an app with `interactive-widget=resizes-content`, focus inside and outside keyboard-aware fields, where a field's keyboard height is 0 | A Core surface jumping after the keyboard settles, lagging the keyboard by more than a frame, left under the keyboard, moved by JavaScript per frame, or committing layout more than once; a Lab surface riding instead of committing at rest; anything travelling with the keyboard under reduced motion instead of DR2's cross-fade; the app's viewport setting overridden; a keyboard-aware field not riding by the visual-viewport height, or adding an offset under `interactive-widget=resizes-content`; or the setting missing from the docs |+| FR8 | Chrome on Android in the emulator with Gboard, top-level document, plus a consumer documentation check | keyboard show and hide with the composer and a Tall sheet; a Lab bottom search field; reduced motion on; focus inside a keyboard-aware field, which rides by the visual-viewport height; an app with `interactive-widget=resizes-content`, focus inside and outside keyboard-aware fields, where a field's keyboard height is 0; Back: the ride starts at Chrome's hide report | A Core surface jumping after the keyboard settles, lagging the keyboard by more than a frame, left under the keyboard, moved by JavaScript per frame, or committing layout more than once; a Lab surface riding instead of committing at rest; anything travelling with the keyboard under reduced motion instead of DR2's cross-fade; the app's viewport setting overridden; a keyboard-aware field not riding by the visual-viewport height, or adding an offset under `interactive-widget=resizes-content`; or the setting missing from the docs || FR8 | Firefox for Android in the emulator, top-level document | focus routes, keyboard shown and hidden, page panned and pinch-zoomed, a sheet moved | The page lurches, the field ends under the keyboard, or the height is wrong after a pan or zoom || FR2–FR5 | Safari on iOS in the iOS Simulator or on a device, top-level document | focus routes, keyboard shown and hidden, page panned and pinch-zoomed, a sheet moved, in Safari and as a home-screen app | The page lurches, the field ends under the keyboard, or the height is wrong after a pan or zoom || FR2–FR5 | Release gate: a physical iPhone in a top-level document (DEC-3) | iPhone Safari with the toolbar expanded and collapsed; iPhone home-screen app; the phone's refresh rate | The page lurches, the field ends under the keyboard, or the surface does not follow the keyboard |@@ -502,6 +509,30 @@ leaves the screen.Rejected: an opt-in prop or per-component keyboard handling; leaving an app's docked bar to the browser's reveal.+### DEC-6 — In Chrome on Android, the focused field is placed above the keyboard at its first report++**Reference:** `spec:AST-099/DEC-6`+**Decider:** `cixzhang`, `2026-11-03`++In Chrome on Android, at the keyboard's first report the content is placed+in one frame so the focused field's bottom sits just above the keyboard's+top, and the content then rides the rest of the keyboard's slide. Chrome+pans the page itself, by the keyboard's whole height, if the focused field is+still drawn below the keyboard about 100–170 ms after the report. The page+gets no frame until that pan ends, so a pan can only be put back as a snap.+Chrome blanks the area below the keyboard's top while the placement happens.+On the Android emulator with Gboard, the one-frame placement showed no pan in+12 shows, including at 4× CPU and with the ride slowed 5×. A slide that+reached the keyboard's top within 50 ms showed a pan in 1 of 8 shows, and in+1 of 4 at 4× CPU. The owner team's side-by-side recording showed a pan in 0+of 5 shows for the placement and in 7 of 8 for the slide.++In Chrome on Android, a hide nothing on the page predicts, such as Back, is+reported partway through the keyboard's slide; the content rides down from+that report.++Rejected: a fast slide, which Chrome's pan still overtakes when the page stalls; the VirtualKeyboard overlay setting, which changes DEC-4's measurement source and the page's layout.+## Open questionsNone.diff --git a/packages/cli/api/component/__fixtures__/resolutions/modules.txt b/packages/cli/api/component/__fixtures__/resolutions/modules.txtindex ddb4114d12..a1af0d42fe 100644--- a/packages/cli/api/component/__fixtures__/resolutions/modules.txt+++ b/packages/cli/api/component/__fixtures__/resolutions/modules.txt@@ -277,7 +277,7 @@ useListFormatter useListFormatter i18n/InternationalizationProvider.doc.mjs i18nuseMenuDrillIn useMenuDrillIn DropdownMenu/DropdownMenu.doc.mjs DropdownMenu/useMenuDrillIn.tsxuseMenuHover useMenuHover hooks/useAnimatedLayout.doc.mjs hooks/useMenuHover.tsuseMenuOverflow useMenuOverflow DropdownMenu/DropdownMenu.doc.mjs DropdownMenu/useMenuOverflow.ts-useMobileKeyboard useMobileKeyboard BottomSheet/BottomSheet.doc.mjs BottomSheet/useMobileKeyboard.ts+useMobileKeyboard ERR_UNKNOWN_COMPONENT - keyboard/useMobileKeyboard.tsuseOutlineFromDOM useOutlineFromDOM Outline/Outline.doc.mjs Outline/useOutlineFromDOM.tsuseOverlay useOverlay Overlay/Overlay.doc.mjs Overlay/useOverlay.tsxuseOwnScrollGesture useOwnScrollGesture DateInput/DateInput.doc.mjs DateInput/useOwnScrollGesture.tsdiff --git a/packages/cli/assets/docs/browser-support.doc.mjs b/packages/cli/assets/docs/browser-support.doc.mjsindex 1346164e9c..679ff89da9 100644--- a/packages/cli/assets/docs/browser-support.doc.mjs+++ b/packages/cli/assets/docs/browser-support.doc.mjs@@ -32,7 +32,12 @@ export const docs = {},{type: 'table',- headers: ['Tier', 'Baseline', 'Representative versions', 'What your users experience'],+ headers: [+ 'Tier',+ 'Baseline',+ 'Representative versions',+ 'What your users experience',+ ],rows: [['Tier 1: Full fidelity',@@ -138,6 +143,27 @@ export const docs = {},],},+ {+ title: 'The On-Screen Keyboard',+ content: [+ {+ type: 'prose',+ text: "On a phone, a fully expanded `height='tall'` BottomSheet responds to the on-screen keyboard: it measures the keyboard as the layout viewport's height minus the visual viewport's height times its scale. Where the visual viewport shrinks for the keyboard, as in Safari on iOS in the browser and as a home-screen app, in Firefox for Android and in Chrome on Android, it keeps the focused field above the keyboard and leaves the page where it was. If Firefox for Android pans to the field, the sheet puts the page back within a couple of frames.",+ },+ {+ type: 'prose',+ text: 'In Chrome on Android, a Tall BottomSheet\u2019s focused field rides the keyboard as Gboard slides it up, and as Gboard slides it down after the field loses focus. The scroll room stays until the keyboard is down. A hide Chrome reports late, such as Back, which keeps the focus, rides down from Chrome\u2019s report. When the keyboard is reported, the sheet places the field just above it in that same frame, so Chrome has no covered field to pan to; if Chrome pans anyway, the sheet puts the page back when that pan ends. Chrome follows your viewport setting, which Astryx documents and never sets: your app owns its viewport `<meta>` element. By default (`interactive-widget=resizes-visual`) Chrome lays the keyboard over the page and pans to a focused field elsewhere on the page. With `interactive-widget=resizes-content` it shrinks the layout viewport instead, so content anchored to the bottom sits above the keyboard, and the sheet measures no keyboard and changes nothing: the browser has already made the room.',+ },+ {+ type: 'code',+ lang: 'html',+ label: 'Chrome on Android resizes the page for the keyboard',+ code: `<meta+ name="viewport"+ content="width=device-width, initial-scale=1, interactive-widget=resizes-content" />`,+ },+ ],+ },{title: 'Supporting Older Browsers',content: [diff --git a/packages/cli/test/__golden__/no-icon-set/docs-topics.json b/packages/cli/test/__golden__/no-icon-set/docs-topics.jsonindex cf55b2f9ba..40cbd19c11 100644--- a/packages/cli/test/__golden__/no-icon-set/docs-topics.json+++ b/packages/cli/test/__golden__/no-icon-set/docs-topics.json@@ -113,10 +113,11 @@"which-features-set-the-floor","which-components-are-affected","what-astryx-guarantees",+ "the-on-screen-keyboard","supporting-older-browsers","how-these-tiers-move-over-time"],- "skeleton": "98bdd1d0e1db35f5ad03896962be51d2f21679c3f3cd25cf724045778a959b5e",+ "skeleton": "463a740e90118dea23181c46a2cca01695d9295027863282835518f0bd655bdb","mentions": []},"color": {diff --git a/packages/cli/test/__golden__/no-icon-set/docs-tree.json b/packages/cli/test/__golden__/no-icon-set/docs-tree.jsonindex a717afb7be..f124e06bd7 100644--- a/packages/cli/test/__golden__/no-icon-set/docs-tree.json+++ b/packages/cli/test/__golden__/no-icon-set/docs-tree.json@@ -684,6 +684,7 @@"which-features-set-the-floor","which-components-are-affected","what-astryx-guarantees",+ "the-on-screen-keyboard","supporting-older-browsers","how-these-tiers-move-over-time"],diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.jsonindex 187911e488..3061911c60 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json@@ -3,7 +3,7 @@"type": "search","data": {"query": "icon set",- "matchCount": 378,+ "matchCount": 379,"results": [{"domain": "doc",diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txtindex d6bd00f528..63d2e678c3 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt@@ -1,4 +1,4 @@-Results for "icon set" (20 of 378)+Results for "icon set" (20 of 379)name: authoring/building-blocks/templates/build-the-template/template-assets/template-iconssection: use-astryx-icondomain: docdiff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjsindex 1431c4f4ac..8c20f980fb 100644--- a/packages/core/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/core/src/BottomSheet/BottomSheet.doc.mjs@@ -152,7 +152,7 @@ export const docs = {name: 'height',type: "'hug' | 'capped' | 'tall' | number | string",description:- "How tall the sheet is. Named budgets: 'hug' fits its content up to 92% of the viewport, 'capped' is a scrolling mid-height panel (~62%), and 'tall' is a pinned near-full panel (~92%) for content that streams in. Or pass a number (px) / CSS length for a custom budget. Give snapPoints to let the user drag between heights. On shorter viewports the sheet fills the available height. Only a fully expanded 'tall' sheet provides mobile-keyboard accommodation: it stays put and scrolls each focused control above the keyboard. Hug, Capped, numeric and CSS-length heights never do, and a Tall sheet stops doing it the moment the user drags it to a shorter detent, resuming when they drag it back. Outside that state the sheet neither moves nor adds keyboard scroll space, and the browser's own focus reveal is left in place; on iOS that reveal can shift the whole page.",+ "How tall the sheet is. Named budgets: 'hug' fits its content up to 92% of the viewport, 'capped' is a scrolling mid-height panel (~62%), and 'tall' is a pinned near-full panel (~92%) for content that streams in. Or pass a number (px) / CSS length for a custom budget. Give snapPoints to let the user drag between heights. On shorter viewports the sheet fills the available height. Only a fully expanded 'tall' sheet provides mobile-keyboard accommodation: it stays put and scrolls each focused control above the keyboard. Hug, Capped, numeric and CSS-length heights never do, and a Tall sheet stops doing it the moment the user drags it to a shorter detent, resuming when they drag it back. Outside that state the sheet neither moves nor adds keyboard scroll space, and the browser's own focus reveal is left in place; on iOS that reveal can shift the whole page. This accommodation applies where the visual viewport shrinks for the keyboard, as in Safari on iOS, Firefox for Android and Chrome on Android, where the sheet places the focused control just above the keyboard as it comes up, and the control rides the rest of Gboard\u2019s slide up, and the slide down after it loses focus; a hide Chrome reports late, such as Back, rides down from Chrome\u2019s report (`astryx docs browser-support`).",default: "'capped'",},{diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsxindex 3e04ecc9c5..ae30e3f75d 100644--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx@@ -9,14 +9,25 @@* SYNC: When BottomSheet.tsx changes, update tests to match new behavior*/-import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {+ describe,+ it,+ expect,+ vi,+ beforeEach,+ afterEach,+ onTestFinished,+} from 'vitest';import {act, render, screen, fireEvent} from '@testing-library/react';-import {Profiler, createRef, useState} from 'react';+import {Profiler, createRef, useState, type ReactNode} from 'react';import {BottomSheet} from './BottomSheet';import {BottomSheetEscapeContext} from './bottomSheetEscape';import {resetBottomSheetStackForTests} from './bottomSheetStack';import {BottomSheetSwitcher} from './BottomSheetSwitcher';import {__resetInteractionModalityForTest} from '../utils/interactionModality';+import {__focusTakeoverCallersForTest} from '../keyboard/keyboardHeight';+import {__resetRevealsAtReportForTest} from '../keyboard/useMobileKeyboard';+import {getKeyboardLayoutGuide} from '../keyboard/keyboardLayoutGuide';// 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@@ -77,6 +88,7 @@ beforeEach(() => {afterEach(() => {vi.unstubAllGlobals();+ __resetRevealsAtReportForTest();});function getSheet(): HTMLElement {@@ -147,7 +159,13 @@ function mockWindowHeight(height: number) {vi.stubGlobal('innerHeight', height);}+// A touch platform that measures the keyboard (spec:AST-099 FR6): a visual+// viewport, and no keyboard geometry API of its own. The user agent below no+// longer decides anything; the capability does.function mockIOSWebKit() {+ if (window.visualViewport == null) {+ mockVisualViewport(window.innerHeight);+ }const navigatorMock = Object.create(window.navigator);Object.defineProperties(navigatorMock, {userAgent: {@@ -158,6 +176,37 @@ function mockIOSWebKit() {maxTouchPoints: {configurable: true, value: 5},});vi.stubGlobal('navigator', navigatorMock);+ mockPrimaryPointer('coarse');+}++// The primary pointer `matchMedia` reports: a touch screen's coarse finger,+// or a desktop's fine mouse.+function mockPrimaryPointer(pointer: 'coarse' | 'fine') {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: query === `(pointer: ${pointer})`,+ 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.+function mockKeyboardGeometryApi() {+ const navigatorMock = Object.create(window.navigator);+ Object.defineProperty(navigatorMock, 'virtualKeyboard', {+ configurable: true,+ value: {overlaysContent: false},+ });+ vi.stubGlobal('navigator', navigatorMock);}interface ResizeObserverRecord {@@ -265,6 +314,17 @@ function fireTimedPointer(return fireEvent(target, event);}+// The room the keyboard takes at the end of a Tall sheet's body, CSS px, or 0+// when the sheet lays out none. The functional style on the body's content box sets+// it as its `::after` box's height.+function keyboardInsetOf(body: HTMLElement): number {+ const content = body.firstElementChild;+ const match = /--[\w-]+:\s*(-?[\d.]+)px/.exec(+ content?.getAttribute('style') ?? '',+ );+ return match == null ? 0 : Number(match[1]);+}+describe('BottomSheet', () => {it('renders children when open and applies the accessible label', () => {render(@@ -2017,6 +2077,126 @@ describe('BottomSheet', () => {});describe('mobile keyboard', () => {+ // The reveal-pan watch reads touches to leave a reader's own pan alone:+ // the most touch listeners registered at once.+ function trackTouchListeners(): () => number {+ const live = new Set<unknown>();+ let most = 0;+ const add = window.addEventListener.bind(window);+ const remove = window.removeEventListener.bind(window);+ const adding = vi+ .spyOn(window, 'addEventListener')+ .mockImplementation((type, listener, options) => {+ if (type === 'touchstart') {+ live.add(listener);+ most = Math.max(most, live.size);+ }+ add(type, listener, options);+ });+ const removing = vi+ .spyOn(window, 'removeEventListener')+ .mockImplementation((type, listener, options) => {+ if (type === 'touchstart') {+ live.delete(listener);+ }+ remove(type, listener, options);+ });+ onTestFinished(() => {+ adding.mockRestore();+ removing.mockRestore();+ });+ return () => most;+ }++ it('registers no touch listener for a presented Tall sheet under a fine pointer (architecture INV13, spec:AST-094 FR24)', () => {+ mockPrimaryPointer('fine');+ mockWindowHeight(800);+ mockVisualViewport(800);+ const mostTouchListeners = trackTouchListeners();+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ expect(screen.getByRole('textbox', {name: 'Comment'})).toBeVisible();+ expect(mostTouchListeners()).toBe(0);+ });++ it('installs no focus takeover for a presented Tall sheet under a fine pointer (architecture INV13, spec:AST-094 FR24)', () => {+ mockPrimaryPointer('fine');+ mockWindowHeight(800);+ mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ expect(screen.getByRole('textbox', {name: 'Comment'})).toBeVisible();+ expect(__focusTakeoverCallersForTest(document)).toBe(0);+ });++ it('installs the focus takeover for each presented Tall sheet under a coarse pointer, through the one shared listener (spec:AST-094 FR24)', () => {+ mockPrimaryPointer('coarse');+ mockWindowHeight(800);+ mockVisualViewport(800);+ render(+ <>+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a note"+ height="tall">+ <input aria-label="Note" />+ </BottomSheet>+ </>,+ );+ // Both sheets claim focus moves through the keyboard module's one+ // document listener (its own test counts that listener).+ expect(__focusTakeoverCallersForTest(document)).toBe(2);+ });++ it('registers one touch listener for two presented Tall sheets under a coarse pointer (spec:AST-094 FR24)', () => {+ mockPrimaryPointer('coarse');+ mockWindowHeight(800);+ mockVisualViewport(800);+ const mostTouchListeners = trackTouchListeners();+ render(+ <>+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a note"+ height="tall">+ <input aria-label="Note" />+ </BottomSheet>+ </>,+ );+ expect(screen.getByRole('textbox', {name: 'Note'})).toBeInTheDocument();+ expect(mostTouchListeners()).toBe(1);+ });+it('claims a transition between fields and delivers it with preventScroll', () => {mockIOSWebKit();render(@@ -2117,9 +2297,42 @@ describe('BottomSheet', () => {expect(sheetFocus).toHaveBeenCalledWith({preventScroll: true});});+ it('leaves focus to desktop Safari and Firefox, which measure but have a fine pointer (AST-017 FR59)', () => {+ // A visual viewport and no keyboard geometry API, as on iOS, but a mouse.+ mockVisualViewport(800);+ mockWindowHeight(800);+ mockPrimaryPointer('fine');+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Title" />+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const sheet = getSheet();+ const title = screen.getByRole('textbox', {name: 'Title'});+ const comment = screen.getByRole('textbox', {name: 'Comment'});+ title.focus();+ const commentFocus = vi.spyOn(comment, 'focus');+ const sheetFocus = vi.spyOn(sheet, 'focus');++ // Tab between fields: the browser's own move, not one delivered here.+ fireEvent.blur(title, {relatedTarget: comment});+ expect(commentFocus).not.toHaveBeenCalled();++ // A window switch blurs the field for nothing. The sheet does not park+ // focus on itself, so focus comes back to the field.+ fireEvent.blur(title, {relatedTarget: null});+ expect(sheetFocus).not.toHaveBeenCalled();+ });+it('does not alter ordinary desktop focus when the viewport is unobstructed', () => {mockVisualViewport(800);mockWindowHeight(800);+ mockKeyboardGeometryApi();const onFocus = vi.fn();render(<BottomSheet@@ -2137,12 +2350,76 @@ describe('BottomSheet', () => {expect(focus).not.toHaveBeenCalledWith({preventScroll: true});expect(onFocus).toHaveBeenCalledTimes(1);- expect(getBody().style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',+ expect(keyboardInsetOf(getBody())).toBe(0);+ });++ it('lays out no keyboard room when the body overhangs the viewport by a fraction of a pixel', () => {+ // On Chrome for Android, the visual viewport can be 0.3 px taller than+ // the layout viewport. A sheet sized to it ends that far below it.+ mockIOSWebKit();+ mockWindowHeight(800);+ mockVisualViewport(800.3);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800.3}),);+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 700, bottom: 740}),+ );++ input.focus();++ expect(keyboardInsetOf(body)).toBe(0);+ });++ it('scrolls nothing for a field in the bottom clearance band when the body overhangs the viewport by a fraction of a pixel', () => {+ // Chrome on Android: the visual viewport can be 0.3 px taller than the+ // layout viewport. With no keyboard up, a field in the sheet's bottom+ // 48 px is already visible: the suggestion clearance is for a keyboard.+ mockIOSWebKit();+ mockWindowHeight(800);+ mockVisualViewport(800.3);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800.3}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 760, bottom: 790}),+ );+ const scrollBy = vi.fn();+ Object.defineProperty(body, 'scrollBy', {+ configurable: true,+ value: scrollBy,+ });++ input.focus();++ expect(scrollBy).not.toHaveBeenCalled();+ expect(body.scrollTop).toBe(0);});it('keeps Tall geometry fixed while extending and cleaning up its internal scroll range', () => {+ mockWindowHeight(800);const viewport = mockVisualViewport(500);render(<BottomSheet@@ -2181,17 +2458,13 @@ describe('BottomSheet', () => {'',);// 300px keyboard overlap + 48px room for Android suggestion UI.- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);// Visible bottom is 500px; preserve the same 48px focus gap.expect(body.scrollTop).toBe(248);viewport.height = 800;void act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ expect(keyboardInsetOf(body)).toBe(0);expect(body.scrollTop).toBe(0);expect(sheet.getBoundingClientRect()).toEqual(initialRect);expect(sheet.style.height).toBe('');@@ -2218,9 +2491,7 @@ describe('BottomSheet', () => {);input.focus();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);expect(body.scrollTop).toBe(0);// Safari can move the sheet body during the interactive dismissal. The@@ -2231,9 +2502,7 @@ describe('BottomSheet', () => {void act(() => viewport.dispatchEvent(new Event('resize')));expect(body.scrollTop).toBe(0);- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '128px',- );+ expect(keyboardInsetOf(body)).toBe(128);// Once that recovery step has been consumed, later layout work at the// same visual-viewport height must not overwrite the person's scrolling.@@ -2246,6 +2515,7 @@ describe('BottomSheet', () => {});it('re-reveals a later focused field after full keyboard recovery restores the opening scroll position', () => {+ mockWindowHeight(800);const viewport = mockVisualViewport(500);render(<BottomSheet@@ -2284,9 +2554,7 @@ describe('BottomSheet', () => {viewport.height = 800;void act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ expect(keyboardInsetOf(body)).toBe(0);// Cleanup restores 0, then the unobstructed safe-area pass reveals the// still-focused later field at the bottom of the 100–800 body viewport.expect(body.scrollTop).toBe(100);@@ -2325,16 +2593,358 @@ describe('BottomSheet', () => {void act(() => viewport.dispatchEvent(new Event('resize')));expect(body.scrollTop).toBe(248);- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '128px',- );+ expect(keyboardInsetOf(body)).toBe(128);viewport.height = 800;void act(() => viewport.dispatchEvent(new Event('resize')));expect(body.scrollTop).toBe(0);- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',+ expect(keyboardInsetOf(body)).toBe(0);+ });++ it('lays out the keyboard room in Chrome on Android, which has its own keyboard geometry API (spec:AST-099 DEC-4)', () => {+ // Gboard shrinks Chrome's visual viewport while the layout viewport+ // keeps its height; the VirtualKeyboard API is not read.+ mockKeyboardGeometryApi();+ mockPrimaryPointer('coarse');+ mockWindowHeight(800);+ mockVisualViewport(500);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),);+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 300, bottom: 340}),+ );++ input.focus();++ expect(keyboardInsetOf(body)).toBe(348);+ });++ describe('on Gboard\u2019s slides in Chrome on Android (spec:AST-099 FR8)', () => {+ // A Tall sheet in Chrome on Android. Its body, from top 100 to bottom+ // 800, holds 800 px of content and the room after it. So the last+ // field's reveal scrolls into the room. The body's scroll stays within+ // its range, as a browser keeps it. `scrollBy` records a smooth scroll+ // and moves nothing, unless `instantScrollBy` lands it at once.+ function renderChromeSheet({+ instantScrollBy = false,+ roomRangeShort = 0,+ pointer = 'coarse',+ picker,+ }: {+ instantScrollBy?: boolean;+ roomRangeShort?: number;+ pointer?: 'coarse' | 'fine';+ picker?: ReactNode;+ } = {}) {+ mockKeyboardGeometryApi();+ mockPrimaryPointer(pointer);+ mockWindowHeight(800);+ const viewport = Object.assign(mockVisualViewport(800), {scale: 1});+ 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;+ // The scroll range the room adds: its height, less `roomRangeShort`.+ const scrollHeight = () =>+ 800 + Math.max(0, keyboardInsetOf(body) - roomRangeShort);+ 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()));+ },+ },+ });+ const scrollBy = vi.fn((options: ScrollToOptions) => {+ if (instantScrollBy) {+ body.scrollTop += options.top ?? 0;+ }+ });+ Object.defineProperty(body, 'scrollBy', {+ configurable: true,+ value: scrollBy,+ });+ 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'));+ });+ };+ return {body, content, input, report, scrollBy};+ }++ const afterTheSlide = async () =>+ act(async () => {+ await new Promise(resolve => setTimeout(resolve, 400));+ });++ it('lands the body at once at the keyboard\u2019s report, and the content\u2019s ride ends with no translate left', async () => {+ const {body, content, input, report, scrollBy} = renderChromeSheet();+ act(() => input.focus());+ report(500);+ // In the report's own event, the room is 300 px of keyboard over the+ // body plus the 48 px clearance. The body scrolls at once, so the+ // field rests 48 px above the keyboard. No smooth scroll trails+ // Gboard's slide.+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);+ expect(scrollBy).not.toHaveBeenCalled();+ await afterTheSlide();+ // The ride ends at the layout: no translate is left.+ expect(content.style.translate).toBe('');+ expect(body.scrollTop).toBe(248);+ });++ it('keeps the room through the keyboard\u2019s hide while the content rides down to the scroll from before the keyboard, then drops both at rest', async () => {+ const {body, content, input, report} = renderChromeSheet({+ instantScrollBy: true,+ });+ act(() => input.focus());+ report(500);+ await afterTheSlide();+ expect(body.scrollTop).toBe(248);++ // Back: Chrome reports the keyboard gone, and the field keeps focus.+ // The guide dates the hide back by the lag measured on blurs.+ report(800);+ // The room stays, so the body keeps its scroll. The content rides+ // down 248 px, back to the scroll from before the keyboard.+ expect(keyboardInsetOf(body)).toBe(348);+ expect(body.scrollTop).toBe(248);+ expect(content.style.translate).toBe('0px 248px');++ await afterTheSlide();+ // At rest, in one commit, the room drops, the body's scroll goes back+ // to 0, and the translate clears.+ expect(keyboardInsetOf(body)).toBe(0);+ expect(body.scrollTop).toBe(0);+ expect(content.style.translate).toBe('');+ });++ it.each([+ [+ 'a select',+ <select key="s" aria-label="Picker">+ <option>One</option>+ </select>,+ ],+ ['a date input', <input key="d" type="date" aria-label="Picker" />],+ ] as const)(+ 'rides the content down and keeps the room through the hide when focus moves to %s, whose picker Chrome opens over the page',+ async (_, picker) => {+ const {body, content, input, report} = renderChromeSheet({+ instantScrollBy: true,+ picker,+ });+ // The picker sits above the field, in view while the keyboard is up.+ const pickerControl = screen.getByLabelText('Picker');+ vi.spyOn(pickerControl, 'getBoundingClientRect').mockImplementation(+ () =>+ rect({top: 600 - body.scrollTop, bottom: 640 - body.scrollTop}),+ );+ act(() => input.focus());+ report(500);+ await afterTheSlide();+ expect(body.scrollTop).toBe(248);+ // Gboard slides down for the picker: Chrome reports the keyboard+ // gone, and no keyboard comes back.+ act(() => pickerControl.focus());+ report(800);+ expect(keyboardInsetOf(body)).toBe(348);+ expect(content.style.translate).toBe('0px 248px');+ await afterTheSlide();+ expect(keyboardInsetOf(body)).toBe(0);+ expect(body.scrollTop).toBe(0);+ expect(content.style.translate).toBe('');+ },+ );++ it('rides by the scroll the room\u2019s drop takes back where the room adds less range than its height, as in Chrome 124', async () => {+ // Chrome 124 added 344 px of scroll range for a 360 px room: here 16+ // px less than the room's 348. The body starts at the end of its+ // range, 100 px, so the clear puts its scroll back there.+ const {body, content, input, report} = renderChromeSheet({+ instantScrollBy: true,+ roomRangeShort: 16,+ });+ body.scrollTop = 100;+ act(() => input.focus());+ report(500);+ await afterTheSlide();+ expect(body.scrollTop).toBe(248);+ report(800);+ // The drop takes back 148 px, to the end of the range without the+ // room, not the 164 px the room's height would say.+ expect(content.style.translate).toBe('0px 148px');+ await afterTheSlide();+ expect(body.scrollTop).toBe(100);+ expect(content.style.translate).toBe('');+ });++ it('attaches nothing of the ride under a fine pointer: the room drops at Chrome\u2019s hide report', () => {+ const guide = getKeyboardLayoutGuide(window);+ const subscribe = vi.spyOn(guide, 'subscribe');+ const {body, content, input, report} = renderChromeSheet({+ instantScrollBy: true,+ pointer: 'fine',+ });+ act(() => input.focus());+ report(500);+ expect(keyboardInsetOf(body)).toBe(348);+ report(800);+ expect(keyboardInsetOf(body)).toBe(0);+ expect(content.style.translate).toBe('');+ // Nothing subscribed the keyboard layout guide.+ expect(subscribe).not.toHaveBeenCalled();+ subscribe.mockRestore();+ });+ });++ it('subscribes no keyboard layout guide where the keyboard moves on Safari\u2019s schedule, whose transitions the sheet never rides (spec:AST-099 FR8)', () => {+ // iOS Safari and Firefox for Android have no VirtualKeyboard API, so the+ // guide has no profile there. The sheet subscribes no guide, and its+ // room follows the keyboard's reports.+ mockWindowHeight(800);+ const viewport = mockVisualViewport(800);+ mockIOSWebKit();+ const guide = getKeyboardLayoutGuide(window);+ const subscribe = vi.spyOn(guide, 'subscribe');+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 660, bottom: 700}),+ );+ act(() => input.focus());+ viewport.height = 500;+ void act(() => viewport.dispatchEvent(new Event('resize')));+ // The room follows the keyboard's report (FR3)...+ expect(keyboardInsetOf(body)).toBe(348);+ // ...and nothing subscribed the guide, so no frame watch runs.+ expect(subscribe).not.toHaveBeenCalled();+ subscribe.mockRestore();+ });++ it('keeps the keyboard room when the page is pinch-zoomed past 2x with the keyboard up', () => {+ // WebKit reports innerWidth and innerHeight in the zoomed visual+ // viewport's px. At 2x, innerHeight alone reads no keyboard, and the+ // sheet would give the room back with the keyboard up.+ mockIOSWebKit();+ mockWindowHeight(800);+ vi.stubGlobal('innerWidth', 1024);+ const viewport = Object.assign(mockVisualViewport(500), {+ width: 1024,+ scale: 1,+ });+ try {+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 300, bottom: 340}),+ );+ input.focus();+ expect(keyboardInsetOf(body)).toBe(348);++ vi.stubGlobal('innerHeight', 400);+ vi.stubGlobal('innerWidth', 512);+ Object.assign(viewport, {height: 250, scale: 2, width: 512});+ void act(() => viewport.dispatchEvent(new Event('resize')));+ expect(keyboardInsetOf(body)).toBe(348);+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('makes no keyboard room beside a classic scrollbar with no keyboard', () => {+ // A desktop page with a 17 px vertical scrollbar: innerWidth counts it,+ // the document's client width and the visual viewport do not.+ mockPrimaryPointer('fine');+ mockWindowHeight(800);+ vi.stubGlobal('innerWidth', 1280);+ Object.assign(mockVisualViewport(800), {width: 1263, scale: 1});+ Object.defineProperty(document.documentElement, 'clientWidth', {+ configurable: true,+ value: 1263,+ });+ try {+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 700, bottom: 740}),+ );+ input.focus();+ expect(keyboardInsetOf(body)).toBe(0);+ } finally {+ Reflect.deleteProperty(document.documentElement, 'clientWidth');+ vi.unstubAllGlobals();+ }});it('smoothly scrolls a focused Tall control above the keyboard', () => {@@ -2372,6 +2982,178 @@ describe('BottomSheet', () => {expect(scrollBy).toHaveBeenCalledWith({top: 248, behavior: 'smooth'});});+ describe('the reveal at the keyboard\u2019s report (spec:AST-099 FR4)', () => {+ // A Tall sheet with its last field low, as in the Mobile keyboard story,+ // on a touch screen. The on-screen keyboard's own pan comes with a touch+ // screen.+ function renderLowField() {+ mockPrimaryPointer('coarse');+ mockWindowHeight(800);+ const viewport = Object.assign(mockVisualViewport(800), {scale: 1});+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ // A smooth scroll is still under way when the next event comes; an+ // instant one has landed.+ const scrollBy = vi.fn((options: ScrollToOptions) => {+ if (options.behavior !== 'smooth') {+ body.scrollTop += options.top ?? 0;+ }+ });+ Object.defineProperty(body, 'scrollBy', {+ configurable: true,+ value: scrollBy,+ });+ 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 scrollIntoView = vi.fn();+ const dialog = body.closest('dialog')!;+ Object.defineProperty(dialog, 'scrollIntoView', {+ configurable: true,+ value: scrollIntoView,+ });+ const report = (height: number) => {+ viewport.height = height;+ void act(() => viewport.dispatchEvent(new Event('resize')));+ };+ // The browser's own pan: the visual viewport moves down within the+ // layout viewport, with no touch and no document scroll.+ const pan = (offsetTop: number) => {+ viewport.offsetTop = offsetTop;+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ };+ return {body, input, scrollBy, scrollIntoView, report, pan};+ }++ it('reveals the field in the report\u2019s own frame', () => {+ const {body, input, report} = renderLowField();+ // No frame comes: only what the report's own event does shows.+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn(() => 1),+ );+ input.focus();+ report(500);+ expect(keyboardInsetOf(body)).toBe(348);+ });++ it('keeps the smooth reveal where the browser does not pan to the field', () => {+ const {input, scrollBy, scrollIntoView, report} = renderLowField();+ input.focus();+ report(500);+ expect(scrollBy).toHaveBeenLastCalledWith({+ top: 248,+ behavior: 'smooth',+ });+ expect(scrollIntoView).not.toHaveBeenCalled();+ });++ it('puts back the browser\u2019s own pan to the field and reveals at once from then on', () => {+ const {body, input, scrollBy, scrollIntoView, report, pan} =+ renderLowField();+ input.focus();+ report(500);+ pan(256);+ expect(scrollIntoView).toHaveBeenCalledWith({+ block: 'start',+ inline: 'nearest',+ behavior: 'instant',+ });+ expect(scrollBy).toHaveBeenLastCalledWith({+ top: 248,+ behavior: 'instant',+ });++ // The next keyboard lands the field in the report's frame, at once.+ report(800);+ pan(0);+ body.scrollTop = 0;+ scrollBy.mockClear();+ report(500);+ expect(scrollBy).toHaveBeenLastCalledWith({+ top: 248,+ behavior: 'instant',+ });+ });++ it('puts the pan back without a second scroll while the smooth reveal is still on its way', () => {+ const {body, input, scrollBy, scrollIntoView, report, pan} =+ renderLowField();+ // The body can scroll far enough; the smooth reveal is under way.+ Object.defineProperty(body, 'scrollHeight', {+ configurable: true,+ value: 2000,+ });+ Object.defineProperty(body, 'clientHeight', {+ configurable: true,+ value: 700,+ });+ input.focus();+ report(500);+ expect(scrollBy).toHaveBeenLastCalledWith({+ top: 248,+ behavior: 'smooth',+ });+ scrollBy.mockClear();+ pan(256);+ // Firefox keeps adding a smooth scrollBy's distance after an instant+ // scroll, so a second scroll here would overshoot.+ expect(scrollBy).not.toHaveBeenCalled();+ expect(scrollIntoView).toHaveBeenCalledWith({+ block: 'start',+ inline: 'nearest',+ behavior: 'instant',+ });+ // The put-back moves the visual viewport up again; the reveal that+ // follows leaves the smooth one to land the field.+ pan(0);+ expect(scrollBy).not.toHaveBeenCalled();+ });++ it('keeps the browser\u2019s reveal when the sheet cannot bring the field above the keyboard', () => {+ const {input, scrollBy, scrollIntoView, report, pan} = renderLowField();+ // The body cannot scroll further: the field stays under the keyboard.+ scrollBy.mockImplementation(() => {});+ input.focus();+ report(500);+ pan(256);+ expect(scrollIntoView).not.toHaveBeenCalled();+ });++ it('leaves a pan the reader makes', () => {+ const {input, scrollBy, scrollIntoView, report, pan} = renderLowField();+ input.focus();+ report(500);+ fireEvent.touchStart(document.body);+ pan(256);+ expect(scrollIntoView).not.toHaveBeenCalled();+ expect(scrollBy).not.toHaveBeenCalledWith(+ expect.objectContaining({behavior: 'instant'}),+ );+ });++ it('leaves a document scroll, which is not the browser revealing the field', () => {+ const {input, scrollIntoView, report, pan} = renderLowField();+ input.focus();+ report(500);+ vi.stubGlobal('scrollY', 120);+ pan(120);+ expect(scrollIntoView).not.toHaveBeenCalled();+ });+ });+it('does not add clearance or scroll when the viewport is unobstructed', () => {mockVisualViewport(800);mockWindowHeight(800);@@ -2395,9 +3177,7 @@ describe('BottomSheet', () => {input.focus();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ expect(keyboardInsetOf(body)).toBe(0);expect(body.scrollTop).toBe(0);});@@ -2456,9 +3236,7 @@ describe('BottomSheet', () => {input.focus();void act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ expect(keyboardInsetOf(body)).toBe(0);expect(body.scrollTop).toBe(0);// The keyboard moved nothing: the sheet still rests at that detent.expect(sheet.style.transform).toBe('');@@ -2509,7 +3287,7 @@ describe('BottomSheet', () => {expect(body.scrollTop).toBe(120);expect(focus).not.toHaveBeenCalled();expect(sheetFocus).not.toHaveBeenCalled();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe('');+ expect(keyboardInsetOf(body)).toBe(0);expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift'),).toBe('');@@ -2565,9 +3343,7 @@ describe('BottomSheet', () => {input.focus();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);expect(body.scrollTop).toBe(248);result.unmount();},@@ -2605,7 +3381,10 @@ describe('BottomSheet', () => {const observer = observers.find(instance => instance.observed.has(input));expect(observer).toBeDefined();act(() => {- observer?.callback([], observer as unknown as ResizeObserver);+ observer?.callback(+ [{target: input} as unknown as ResizeObserverEntry],+ observer as unknown as ResizeObserver,+ );});expect(body.scrollTop).toBe(448);@@ -2641,9 +3420,7 @@ describe('BottomSheet', () => {input.focus();expect(body.scrollTop).toBe(248);- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);const pointerDownAllowed = fireEvent.pointerDown(getHandle(), {pointerId: 1,@@ -2660,16 +3437,12 @@ describe('BottomSheet', () => {expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe('',);- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);expect(body.scrollTop).toBe(248);viewport.height = 800;void act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ expect(keyboardInsetOf(body)).toBe(0);});it('retains Tall keyboard scroll space after blur until the viewport recovers', () => {@@ -2695,21 +3468,15 @@ describe('BottomSheet', () => {}),);input.focus();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);input.blur();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);viewport.height = 800;void act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ expect(keyboardInsetOf(body)).toBe(0);});it('blurs the focused Tall field and retains its inset until the viewport recovers', () => {@@ -2737,22 +3504,16 @@ describe('BottomSheet', () => {}),);input.focus();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);rerender(content(false));expect(document.activeElement).not.toBe(input);- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);viewport.height = 800;void act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ expect(keyboardInsetOf(body)).toBe(0);});it('retains Tall keyboard scroll space through a switcher handoff until the viewport recovers', () => {@@ -2782,22 +3543,16 @@ describe('BottomSheet', () => {}),);input.focus();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);rerender(content('confirmation'));expect(document.activeElement).not.toBe(input);- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);viewport.height = 800;void act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ expect(keyboardInsetOf(body)).toBe(0);});it('puts back a document scroll the browser makes to reveal a field', () => {@@ -2844,6 +3599,45 @@ describe('BottomSheet', () => {Object.defineProperty(window, 'scrollY', {configurable: true, value: 0});});+ it('puts back only the page\u2019s own scroll, never an element\u2019s scroll that reaches the window', () => {+ mockVisualViewport(377);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 57, bottom: 714}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 600 - body.scrollTop, bottom: 640 - body.scrollTop}),+ );+ input.focus();+ const scrollTo = vi.mocked(window.scrollTo);+ scrollTo.mockClear();+ Object.defineProperty(window, 'scrollY', {+ configurable: true,+ value: 337,+ });+ try {+ fireEvent.scroll(body);+ expect(scrollTo).not.toHaveBeenCalled();+ fireEvent.scroll(window);+ expect(scrollTo).toHaveBeenCalledWith(0, 0);+ } finally {+ Object.defineProperty(window, 'scrollY', {+ configurable: true,+ value: 0,+ });+ }+ });+it('leaves the document alone when no keyboard is measured', () => {mockVisualViewport(800);render(@@ -2924,9 +3718,7 @@ describe('BottomSheet', () => {// The first field opens the keyboard and is already inside the safe// area, so nothing has to move for it.title.focus();- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '348px',- );+ expect(keyboardInsetOf(body)).toBe(348);expect(scrolls).toEqual([]);// A keyboard accessory "Next" or a Tab arrives as a blur naming the@@ -2944,6 +3736,7 @@ describe('BottomSheet', () => {it('does not scroll a browser-driven transition when the viewport is unobstructed', () => {mockIOSWebKit();+ mockWindowHeight(800);mockVisualViewport(800);render(<BottomSheet@@ -3056,8 +3849,8 @@ describe('BottomSheet', () => {rect({top: 660 - body.scrollTop, bottom: 700 - body.scrollTop}),);input.focus();- const inset = body.style.getPropertyValue('--_sheet-keyboard-inset');- expect(inset).toBe(`${layoutBottom - (500 - 48)}px`);+ const inset = keyboardInsetOf(body);+ expect(inset).toBe(layoutBottom - (500 - 48));// The browser pans the page up to reveal a field: the same 500px of// visible page, now offset so its bottom edge coincides with the layout@@ -3067,9 +3860,7 @@ describe('BottomSheet', () => {input.blur();// The keyboard did not change size, so neither does the scroll range.- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- inset,- );+ expect(keyboardInsetOf(body)).toBe(inset);});it('keeps defending a pinned sheet after the browser has panned it once', () => {@@ -3115,14 +3906,12 @@ describe('BottomSheet', () => {);title.focus();- const inset = body.style.getPropertyValue('--_sheet-keyboard-inset');- expect(inset).toBe(`${layoutBottom - (500 - 48)}px`);+ const inset = keyboardInsetOf(body);+ expect(inset).toBe(layoutBottom - (500 - 48));viewport.offsetTop = layoutBottom - 500;void act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- inset,- );+ expect(keyboardInsetOf(body)).toBe(inset);// And the next browser-driven transition is still claimed and revealed,// by a distance measured against the unshifted keyboard boundary.diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex 031f6fa498..7f4b8da13b 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -14,7 +14,7 @@* - /packages/core/src/BottomSheet/BottomSheet.tsx* - /packages/core/src/BottomSheet/BottomSheetPanel.test.tsx* - /packages/core/src/BottomSheet/snapOffsets.ts- * - /packages/core/src/BottomSheet/useMobileKeyboard.ts+ * - /packages/core/src/keyboard/useMobileKeyboard.ts* - /packages/core/src/BottomSheet/useSheetGestures.ts* - /packages/core/src/Layout/container.stylex.ts (bottom-sheet padding chain)*/@@ -66,7 +66,7 @@ import {resolveSnapPoints,type BottomSheetSnapPoint,} from './snapOffsets';-import {useMobileKeyboard} from './useMobileKeyboard';+import {useMobileKeyboard} from '../keyboard/useMobileKeyboard';import {scrollPreservationPadding,sheetLayoutHeight,@@ -316,13 +316,29 @@ const styles = stylex.create({},tallKeyboardBody: {scrollPaddingBlockEnd: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,+ },+ // The inset the keyboard takes at the end of a Tall sheet's content+ // (useMobileKeyboard), so its last control can scroll above the keyboard.+ // It is the content box's last in-flow box, after the content's own+ // children, not a box after the content. Firefox resolves the content's+ // `min-height: min-content` as `auto` in the block axis. The content box+ // then keeps the body's height while its children overflow it. An inset+ // after that box sat inside the overflow and added no scroll range. In+ // Firefox for Android, the body's scrollHeight was 1491 with and without a+ // 357 px inset.+ tallKeyboardContent: {'::after': {content: '""',display: 'block',- blockSize: 'var(--_sheet-keyboard-inset, 0px)',+ blockSize: 0,pointerEvents: 'none',},},+ keyboardInset: (inset: number) => ({+ '::after': {+ blockSize: inset,+ },+ }),budget: {height: `calc(var(--_sheet-budget) + ${OVERSCROLL_PADDING}px)`,},@@ -564,6 +580,9 @@ export function BottomSheetPanel({...props}: BottomSheetPanelProps) {const elementRef = useRef<HTMLDivElement | null>(null);+ const dismissKeyboardRef = useRef<+ ((focusTarget?: HTMLElement) => void) | null+ >(null);const previousStateRef = useRef(state);const reactivatedEntranceRef = useRef(false);const onMotionStartRef = useRef(onMotionStart);@@ -639,7 +658,6 @@ export function BottomSheetPanel({dragOffset,settledOffset,isDragging,- isTraveling,isDismissedByTouchDrag,sheetHeight,scrollPreservationInset,@@ -653,6 +671,10 @@ export function BottomSheetPanel({offscreenBlockEndInset: OVERSCROLL_PADDING,onDismiss,snapHeights,+ onTravelStart: () => {+ // Focusing the sheet dismisses the keyboard as the sheet starts to move.+ dismissKeyboardRef.current?.(elementRef.current ?? undefined);+ },onScrimOpacity,hasFixedHeight: consumerHeight != null,});@@ -686,17 +708,19 @@ export function BottomSheetPanel({isPresentedRef.current = isPresented;sheetRef(isPresented ? elementRef.current : null);}, [isPresented, sheetRef]);- useMobileKeyboard({- bodyRef: bodyElementRef,- bottomClearance: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,- isEnabled: height === 'tall',- isFullyExpanded: settledOffset === 0,- isPageScrollLocked,- isSheetTraveling: isTraveling,+ const keyboard = useMobileKeyboard(elementRef, {+ move: 'ride',+ inset: true,+ offset: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,+ isEnabled: height === 'tall' && isPresented,+ isExpanded: settledOffset === 0,isOpen: isInteractive,- isPresented,- sheetRef: elementRef,+ isPageScrollLocked,});+ const keyboardInset = keyboard.inset;+ // The drag's own callback dismisses the keyboard as the sheet starts to+ // move. It runs in the gesture, so it reads the newest dismiss.+ dismissKeyboardRef.current = keyboard.dismiss;// Keep controller registration attached to one stable host ref. React// detaches an old callback ref when a consumer supplies a new identity; if// that public ref were merged with setElement, an ordinary parent rerender@@ -943,6 +967,10 @@ export function BottomSheetPanel({getContentProps<HTMLDivElement>(stylex.props(styles.content,+ height === 'tall' && styles.tallKeyboardContent,+ height === 'tall' &&+ keyboardInset > 0 &&+ styles.keyboardInset(keyboardInset),...container(usesThemePadding? {useThemeDefault: 'bottom-sheet'}diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboardInset.interaction.browser.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboardInset.interaction.browser.spec.tsnew file mode 100644index 0000000000..4183f679a8--- /dev/null+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboardInset.interaction.browser.spec.ts@@ -0,0 +1,628 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetKeyboardInset.interaction.browser.spec.ts+ * @input Playwright, the interaction harness, the Mobile keyboard story, a+ * stand-in visual viewport the test drives, and Gboard's measured slides+ * @output Tests that a fully expanded Tall sheet makes room for the keyboard+ * at the end of its body. The sheet brings the focused field above the+ * keyboard and gives the room back. In Chrome on Android, under a coarse+ * pointer, the field rides Gboard's show. Through the hide the room stays+ * while the content rides down, and both clear in one commit at rest.+ * Under Reduce Motion nothing travels. Under a fine pointer nothing of the+ * ride attaches.+ * @position Browser tests for BottomSheet's use of the keyboard module+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {cubicBezier} from '../../motion/bezier';+import {keyboard as ANDROID_KEYBOARD} from '../../motion/android/keyboard';+import {+ compareCurve,+ curveOf,+ holdAnimations,+ type HeldAnimation,+ openStory,+ releaseAnimations,+ sampleCurve,+ timeline,+ waitForAnimation,+ waitForRest,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++// The cover Mobile Safari reports on an iPhone 17 Pro (keyboard, accessory+// bar and the floating address bar).+const COVER = 337;++/**+ * Replaces `window.visualViewport` before the page loads with one the test+ * drives: `__keyboard(cover)` shrinks it from the bottom and fires one+ * `resize`, as Mobile Safari does.+ */+async function installKeyboard(page: Page) {+ await page.addInitScript(() => {+ // Mobile Safari has no keyboard geometry API.+ Reflect.deleteProperty(Navigator.prototype, 'virtualKeyboard');+ const viewport = Object.assign(new EventTarget(), {+ height: window.innerHeight,+ width: window.innerWidth,+ offsetTop: 0,+ offsetLeft: 0,+ pageTop: 0,+ pageLeft: 0,+ scale: 1,+ });+ Object.defineProperty(window, 'visualViewport', {+ configurable: true,+ get: () => viewport,+ });+ (window as unknown as {__keyboard: (cover: number) => void}).__keyboard =+ cover => {+ viewport.height = window.innerHeight - cover;+ viewport.dispatchEvent(new Event('resize'));+ };+ });+}++const report = async (page: Page, cover: number) =>+ page.evaluate(+ c => (window as unknown as {__keyboard: (c: number) => void}).__keyboard(c),+ cover,+ );++/** The room at the end of the field's scrolling body, and where the field is. */+const readBody = async (field: Locator) =>+ field.evaluate(element => {+ let body = element.parentElement;+ while (body != null) {+ const overflow = getComputedStyle(body).overflowY;+ if (overflow === 'auto' || overflow === 'scroll') {+ break;+ }+ body = body.parentElement;+ }+ if (body == null) {+ throw new Error('no scrolling body');+ }+ const content = body.firstElementChild ?? body;+ const roomOf = (box: Element) =>+ parseFloat(getComputedStyle(box, '::after').blockSize) || 0;+ return {+ room: Math.max(roomOf(body), roomOf(content)),+ style: body.getAttribute('style') ?? '',+ contentStyle: content.getAttribute('style') ?? '',+ contentTranslate: getComputedStyle(content).translate,+ fieldBottom: element.getBoundingClientRect().bottom,+ scrollHeight: body.scrollHeight,+ scrollTop: body.scrollTop,+ clientHeight: body.clientHeight,+ };+ });++/**+ * Keeps the content box at the body's height while its fields overflow it, as+ * Firefox lays it out. Firefox resolves the content's `min-height:+ * min-content` as `auto` in the block axis.+ */+const keepContentBoxAtBodyHeight = async (field: Locator) =>+ field.evaluate(element => {+ let body = element.parentElement;+ while (body != null && getComputedStyle(body).overflowY !== 'auto') {+ body = body.parentElement;+ }+ (body?.firstElementChild as HTMLElement | null)?.style.setProperty(+ 'min-height',+ '0',+ 'important',+ );+ });++test('a Tall sheet makes room for the keyboard at the end of its body, through its own style', async ({+ page,+}) => {+ await installKeyboard(page);+ await openStory(page, storybook(), 'core-bottomsheet--mobile-keyboard');+ await page.getByRole('button', {name: 'Add a comment'}).click();+ const dialog = page.getByRole('dialog', {name: 'Add a comment'});+ await expect(dialog).toBeVisible();+ // Let the sheet settle fully expanded.+ await page.waitForTimeout(800);+ const field = dialog.getByRole('textbox').last();+ await field.focus();+ await report(page, COVER);+ await expect+ .poll(async () => (await readBody(field)).room, {timeout: 2000})+ .toBeGreaterThan(0);+ const shown = await readBody(field);+ // No CSS custom property of the sheet's own carries the keyboard (FR3).+ expect(shown.style).not.toContain('--_sheet-keyboard-inset');+ expect(shown.contentStyle).not.toContain('--_sheet-keyboard-inset');+ // The sheet scrolls the last field above the keyboard within itself.+ const keyboardTop = await page.evaluate(c => window.innerHeight - c, COVER);+ await expect+ .poll(async () => (await readBody(field)).fieldBottom, {timeout: 2000})+ .toBeLessThanOrEqual(keyboardTop);++ // The keyboard goes: the room goes with it.+ await field.blur();+ await report(page, 0);+ await expect+ .poll(async () => (await readBody(field)).room, {timeout: 2000})+ .toBe(0);+});++test('the last field scrolls above the keyboard where the content box keeps the body\u2019s height, as in Firefox', async ({+ page,+}) => {+ await installKeyboard(page);+ await openStory(page, storybook(), 'core-bottomsheet--mobile-keyboard');+ await page.getByRole('button', {name: 'Add a comment'}).click();+ const dialog = page.getByRole('dialog', {name: 'Add a comment'});+ await expect(dialog).toBeVisible();+ await page.waitForTimeout(800);+ const field = dialog.getByRole('textbox').last();+ await keepContentBoxAtBodyHeight(field);+ await field.focus();+ await report(page, COVER);+ await expect+ .poll(async () => (await readBody(field)).room, {timeout: 2000})+ .toBeGreaterThan(0);+ // The room comes after the content's own fields, so the body can scroll the+ // last of them above the keyboard.+ const keyboardTop = await page.evaluate(c => window.innerHeight - c, COVER);+ await expect+ .poll(async () => (await readBody(field)).fieldBottom, {timeout: 2000})+ .toBeLessThanOrEqual(keyboardTop);+});++/**+ * Chrome on Android: the same driven visual viewport, plus a VirtualKeyboard+ * object the guide must leave alone. The guide then reads Chrome's profile and+ * publishes Gboard's slides.+ */+async function installAndroidKeyboard(page: Page) {+ await page.addInitScript(() => {+ const keyboard = Object.assign(new EventTarget(), {+ overlaysContent: false,+ boundingRect: new DOMRect(0, 0, 0, 0),+ });+ Object.defineProperty(navigator, 'virtualKeyboard', {+ configurable: true,+ value: keyboard,+ });+ const viewport = Object.assign(new EventTarget(), {+ height: window.innerHeight,+ width: window.innerWidth,+ offsetTop: 0,+ offsetLeft: 0,+ pageTop: 0,+ pageLeft: 0,+ scale: 1,+ });+ Object.defineProperty(window, 'visualViewport', {+ configurable: true,+ get: () => viewport,+ });+ (window as unknown as {__keyboard: (cover: number) => void}).__keyboard =+ cover => {+ viewport.height = window.innerHeight - cover;+ viewport.dispatchEvent(new Event('resize'));+ };+ });+}++// The vertical part of a computed `translate` (`none`, or `Xpx Ypx`).+const translateYOf = (translate: string) =>+ parseFloat(translate.split(' ')[1] ?? '') || 0;++// The content box's ride among what a hold takes on it: the one script+// animation that moves `translate`.+function rideOf(held: ReadonlyArray<HeldAnimation>): HeldAnimation {+ const ride = held.find(+ a => a.kind === 'Animation' && a.keyframes.some(k => 'translate' in k),+ );+ if (ride == null) {+ throw new Error(`no ride among ${JSON.stringify(held)}`);+ }+ return ride;+}++test.describe('Chrome on Android, on Gboard\u2019s slides (spec:AST-099 FR8)', () => {+ test.use({hasTouch: true, isMobile: true});+ test.skip(+ ({browserName}) => browserName !== 'chromium',+ 'Chrome\u2019s keyboard profile needs the VirtualKeyboard API',+ );++ // Reports the keyboard's cover and returns the report's time.+ const reportAt = async (page: Page, cover: number) =>+ page.evaluate(c => {+ let at = 0;+ const view = window.visualViewport as unknown as EventTarget;+ view.addEventListener(+ 'resize',+ event => {+ at = event.timeStamp;+ },+ {once: true},+ );+ (window as unknown as {__keyboard: (c: number) => void}).__keyboard(c);+ return at;+ }, cover);++ // Opens the sheet with its body scrolled to the end, so the last field's+ // reveal scrolls into the keyboard room.+ async function openAtLastField(page: Page) {+ await installAndroidKeyboard(page);+ await openStory(page, storybook(), 'core-bottomsheet--mobile-keyboard');+ await page.getByRole('button', {name: 'Add a comment'}).click();+ const dialog = page.getByRole('dialog', {name: 'Add a comment'});+ await expect(dialog).toBeVisible();+ await page.waitForTimeout(800);+ const field = dialog.getByRole('textbox').last();+ await field.evaluate(element => {+ let body = element.parentElement;+ while (body != null && getComputedStyle(body).overflowY !== 'auto') {+ body = body.parentElement;+ }+ if (body == null) {+ throw new Error('no scrolling body');+ }+ body.scrollTop = body.scrollHeight;+ body.firstElementChild?.setAttribute('data-sheet-content', '');+ });+ const content = page.locator('[data-sheet-content]');+ const keyboardTop = await page.evaluate(c => window.innerHeight - c, COVER);+ return {field, content, keyboardTop};+ }++ test('the last field clears the keyboard\u2019s top in the report\u2019s own commit, then rides the rest on Gboard\u2019s show, dated back to Gboard\u2019s start', async ({+ page,+ }) => {+ const {field, content, keyboardTop} = await openAtLastField(page);+ await field.focus();+ const before = await readBody(field);+ const reported = await reportAt(page, COVER);+ // The body lands at once in the report's event. The content starts 4 px+ // above the keyboard's top and rides the rest of Gboard's slide up.+ const landed = await readBody(field);+ const distance = landed.scrollTop - before.scrollTop;+ expect(distance).toBeGreaterThan(100);+ await waitForAnimation(content);+ const start = await content.evaluate(el =>+ Math.max(+ ...el.getAnimations().map(a => Number(a.startTime ?? -Infinity)),+ ),+ );+ expect(+ Math.abs(start - (reported - ANDROID_KEYBOARD.showReportLagMs)),+ ).toBeLessThan(2);+ const ride = rideOf(await holdAnimations(page, content));+ const samples = curveOf(+ await sampleCurve(content, timeline(ride.offsetMs + ride.curveEndMs)),+ 'translateY',+ );+ await releaseAnimations(page);+ // At rest: no translate is left, the body did not scroll again, and the+ // field rests above the keyboard.+ await waitForRest(content);+ const rest = await readBody(field);+ expect(translateYOf(rest.contentTranslate)).toBeCloseTo(0, 1);+ expect(rest.scrollTop).toBe(landed.scrollTop);+ expect(rest.fieldBottom).toBeLessThanOrEqual(keyboardTop);+ // Chrome pans the page itself if the field is still below the keyboard's+ // top 100 to 170 ms after the report. The field sits 4 px above that top+ // from the report's own commit, and only that last stretch rides.+ const within = keyboardTop - rest.fieldBottom - 4;+ const fromReport = ride.offsetMs + (reported - start);+ const late = samples.filter(sample => sample.t >= fromReport);+ expect(late.length).toBeGreaterThan(0);+ for (const sample of late) {+ expect(sample.value, JSON.stringify(late)).toBeLessThanOrEqual(+ within + 0.5,+ );+ }+ // That stretch rides on Gboard's own curve, from the slide's start.+ const ease = cubicBezier(ANDROID_KEYBOARD.showCurve);+ const result = compareCurve(+ samples,+ t =>+ within *+ (1 -+ ease(+ Math.min(+ 1,+ Math.max(0, (t - ride.offsetMs) / ANDROID_KEYBOARD.showMs),+ ),+ )),+ 0.5,+ );+ expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(+ 0.5,+ );+ });++ test('a report the page reads after Gboard\u2019s slide has ended lands the last field above the keyboard at once', async ({+ page,+ }) => {+ const {field, keyboardTop} = await openAtLastField(page);+ await field.focus();+ // A busy page reads the report 350 ms after the browser sent it, past the+ // 267 ms slide.+ const bottoms = await field.evaluate(async (element, c) => {+ const view = window.visualViewport as unknown as EventTarget & {+ height: number;+ };+ view.height = window.innerHeight - c;+ const report = new Event('resize');+ const until = performance.now() + 350;+ while (performance.now() < until) {+ // The page is busy.+ }+ view.dispatchEvent(report);+ const out: number[] = [];+ for (let i = 0; i < 3; i += 1) {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => resolve()),+ );+ out.push(element.getBoundingClientRect().bottom);+ }+ return out;+ }, COVER);+ for (const bottom of bottoms) {+ expect(bottom, JSON.stringify(bottoms)).toBeLessThanOrEqual(keyboardTop);+ }+ });++ test('through Gboard\u2019s hide the room stays while the content rides down by the scroll its drop takes back, and both clear in one commit at rest', async ({+ page,+ }) => {+ const {field, content} = await openAtLastField(page);+ await field.focus();+ await reportAt(page, COVER);+ await waitForRest(content);+ await page.waitForTimeout(100);+ const shown = await readBody(field);+ // How far the body has scrolled into the room: the scroll its drop takes+ // back.+ const intoRoom =+ shown.scrollTop - (shown.scrollHeight - shown.room - shown.clientHeight);+ expect(intoRoom).toBeGreaterThan(100);++ // Back: Chrome reports the keyboard gone while the field keeps focus.+ // The guide dates the hide back by the lag measured on blurs.+ const reported = await reportAt(page, 0);+ const held = await readBody(field);+ expect(held.room).toBe(shown.room);+ expect(held.scrollTop).toBe(shown.scrollTop);+ await waitForAnimation(content);+ const start = await content.evaluate(el =>+ Math.max(+ ...el.getAnimations().map(a => Number(a.startTime ?? -Infinity)),+ ),+ );+ expect(+ Math.abs(start - (reported - ANDROID_KEYBOARD.hideReportLagMs)),+ ).toBeLessThan(2);+ const ride = rideOf(await holdAnimations(page, content));+ const samples = curveOf(+ await sampleCurve(content, timeline(ride.offsetMs + ride.curveEndMs)),+ 'translateY',+ );+ await releaseAnimations(page);+ const ease = cubicBezier(ANDROID_KEYBOARD.hideCurve);+ const result = compareCurve(+ samples,+ t =>+ intoRoom *+ ease(+ Math.min(+ 1,+ Math.max(0, (t - ride.offsetMs) / ANDROID_KEYBOARD.hideMs),+ ),+ ),+ 0.5,+ );+ expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(+ 0.5,+ );++ // At rest, in one commit, the room is gone and the body's scroll gave back+ // what the content rode. No translate remains, and the page draws the+ // field where the ride took it.+ await waitForRest(content);+ await page.waitForTimeout(100);+ const rest = await readBody(field);+ expect(rest.room).toBe(0);+ expect(translateYOf(rest.contentTranslate)).toBeCloseTo(0, 1);+ expect(rest.scrollTop).toBeCloseTo(shown.scrollTop - intoRoom, 0);+ expect(rest.fieldBottom).toBeCloseTo(shown.fieldBottom + intoRoom, 0);+ });++ // The field's drawn bottom, the content box's opacity and the room, on every+ // animation frame for `ms` after the test reports `cover`.+ const sampleAfterReport = async (field: Locator, cover: number, ms: number) =>+ field.evaluate(+ async (element, {c, until}) => {+ let body = element.parentElement;+ while (body != null && getComputedStyle(body).overflowY !== 'auto') {+ body = body.parentElement;+ }+ const content = body?.firstElementChild ?? body;+ const read = () => ({+ bottom: element.getBoundingClientRect().bottom,+ opacity: Number(getComputedStyle(content as Element).opacity),+ room:+ parseFloat(+ getComputedStyle(content as Element, '::after').blockSize,+ ) || 0,+ });+ const out = [read()];+ const end = performance.now() + until;+ await new Promise<void>(resolve => {+ const sample = () => {+ out.push(read());+ if (performance.now() < end) {+ requestAnimationFrame(sample);+ } else {+ resolve();+ }+ };+ requestAnimationFrame(sample);+ (window as unknown as {__keyboard: (c: number) => void}).__keyboard(+ c,+ );+ });+ return out;+ },+ {c: cover, until: ms},+ );++ // Chrome on the Android emulator pans the visual viewport to the focused+ // field a few frames after the report, while the content still rides. This+ // reports the keyboard, then moves the stand-in viewport down by 30 px on+ // each of `frames` frames. It returns each frame the hook put the pan back+ // in, with the content's ride offset at that moment.+ const panAfterReport = async (page: Page, cover: number, frames: number) =>+ page.evaluate(+ async ([c, n]) => {+ const viewport = window.visualViewport as unknown as EventTarget & {+ offsetTop: number;+ };+ const content = document.querySelector(+ '[data-sheet-content]',+ ) as HTMLElement;+ const putBacks: {frame: number; ride: number}[] = [];+ let frame = -1;+ const scrollIntoView = Element.prototype.scrollIntoView;+ Element.prototype.scrollIntoView = function (+ this: Element,+ options?: boolean | ScrollIntoViewOptions,+ ) {+ if (this instanceof HTMLDialogElement) {+ const translate = getComputedStyle(content).translate;+ putBacks.push({+ frame,+ ride: parseFloat(translate.split(' ')[1] ?? '') || 0,+ });+ viewport.offsetTop = 0;+ }+ scrollIntoView.call(this, options);+ };+ const nextFrame = async () => {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => resolve()),+ );+ };+ (window as unknown as {__keyboard: (c: number) => void}).__keyboard(c);+ await nextFrame();+ for (frame = 0; frame < n; frame += 1) {+ viewport.offsetTop += 30;+ viewport.dispatchEvent(new Event('scroll'));+ await nextFrame();+ }+ Element.prototype.scrollIntoView = scrollIntoView;+ return putBacks;+ },+ [cover, frames] as const,+ );++ test('puts the browser\u2019s reveal pan back in its first frame, while the content still rides', async ({+ page,+ }) => {+ const {field} = await openAtLastField(page);+ await field.focus();+ const putBacks = await panAfterReport(page, COVER, 6);+ expect(putBacks.length, JSON.stringify(putBacks)).toBeGreaterThan(0);+ expect(putBacks[0].frame, JSON.stringify(putBacks)).toBe(0);+ expect(putBacks[0].ride).toBeGreaterThan(1);+ });++ test('Reduce Motion: puts the browser\u2019s reveal pan back in its first frame, during the cross-fade', async ({+ page,+ }) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {field} = await openAtLastField(page);+ await field.focus();+ const putBacks = await panAfterReport(page, COVER, 6);+ expect(putBacks.length, JSON.stringify(putBacks)).toBeGreaterThan(0);+ expect(putBacks[0].frame, JSON.stringify(putBacks)).toBe(0);+ });++ test('Reduce Motion: the sheet never travels with Gboard; it cross-fades, and the room drops once at rest (design:reduced-motion)', async ({+ page,+ }) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {field} = await openAtLastField(page);+ await field.focus();+ const show = await sampleAfterReport(field, COVER, 900);+ const shown = show.at(-1) as (typeof show)[number];+ // The field rests from the report's first frame, so Chrome has nothing to+ // pan to, and only the fade changes.+ expect(+ show+ .slice(1)+ .filter(frame => Math.abs(frame.bottom - shown.bottom) >= 0.5),+ JSON.stringify(show.map(f => Math.round(f.bottom))),+ ).toEqual([]);+ // Every frame draws the field where it was or where it rests, and the+ // change is a fade.+ for (const frame of show) {+ expect(+ Math.abs(frame.bottom - show[0].bottom) < 0.5 ||+ Math.abs(frame.bottom - shown.bottom) < 0.5,+ JSON.stringify(show.map(f => Math.round(f.bottom))),+ ).toBe(true);+ }+ expect(Math.min(...show.map(f => f.opacity))).toBeLessThan(1);+ expect(shown.opacity).toBe(1);++ const hide = await sampleAfterReport(field, 0, 900);+ const rest = hide.at(-1) as (typeof hide)[number];+ for (const frame of hide) {+ expect(+ Math.abs(frame.bottom - hide[0].bottom) < 0.5 ||+ Math.abs(frame.bottom - rest.bottom) < 0.5,+ JSON.stringify(hide.map(f => Math.round(f.bottom))),+ ).toBe(true);+ }+ // The room holds through the hide, then drops once.+ const rooms = hide.map(f => Math.round(f.room));+ expect(rooms[0]).toBeGreaterThan(0);+ expect(rest.room).toBe(0);+ expect(+ rooms.filter((room, i) => i > 0 && room !== rooms[i - 1]),+ ).toHaveLength(1);+ expect(rest.opacity).toBe(1);+ });++ test.describe('under a fine pointer', () => {+ test.use({hasTouch: false, isMobile: false});++ test('nothing of the ride attaches: the room drops at Chrome\u2019s hide report', async ({+ page,+ }) => {+ const {field, content} = await openAtLastField(page);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ await field.focus();+ await reportAt(page, COVER);+ await expect+ .poll(async () => (await readBody(field)).room, {timeout: 2000})+ .toBeGreaterThan(0);+ await page.waitForTimeout(800);+ await reportAt(page, 0);+ expect((await readBody(field)).room).toBe(0);+ expect(await content.evaluate(el => el.getAnimations().length)).toBe(0);+ });+ });+});diff --git a/packages/core/src/BottomSheet/bottomSheetStack.ts b/packages/core/src/BottomSheet/bottomSheetStack.tsindex 7f70da5390..c27ba6653c 100644--- a/packages/core/src/BottomSheet/bottomSheetStack.ts+++ b/packages/core/src/BottomSheet/bottomSheetStack.ts@@ -1881,7 +1881,7 @@ export function getBottomSheetBeneath(// preventScroll on both: presenting a sheet must not scroll the page to reveal// what it just focused. For an autofocused field that reveal is the mobile-// keyboard's, and it moves the document under a fixed sheet; useMobileKeyboard+// keyboard's, and it moves the document under a fixed sheet. useMobileKeyboard// brings the field into view within the sheet instead./*** Move focus into a sheet panel. Focus already inside the sheet stays put:diff --git a/packages/core/src/BottomSheet/useMobileKeyboard.ts b/packages/core/src/BottomSheet/useMobileKeyboard.tsdeleted file mode 100644index 55ea68e888..0000000000--- a/packages/core/src/BottomSheet/useMobileKeyboard.ts+++ /dev/null@@ -1,542 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--/**- * @file useMobileKeyboard.ts- * @input Uses React effects and refs supplied by BottomSheet- * @output Exports internal useMobileKeyboard hook- * @position Internal to BottomSheet; not exported from the core entry point- */--// A fully expanded, explicitly Tall sheet gets a keyboard-aware internal-// scroll range, and the sheet itself stays still. Other detents and heights-// opt out. Tall-sheet travel or a close blurs the field and dismisses the-// keyboard.-//-// On iOS the browser reveals a focused field by scrolling the document, and-// a fixed sheet moves with it, so the page lurches. The reveal belongs to the-// focus operation, so refuse it there: take over the focus change on the-// capture-phase blur, focus with preventScroll, and then scroll the control-// into view in the sheet's own scroller. A tap, the keyboard's Next, Tab and-// focus() all pass through that one change.--import {useEffect, useRef, type RefObject} from 'react';--const MOBILE_KEYBOARD_INSET_VAR = '--_sheet-keyboard-inset';-const NON_TEXT_INPUT_TYPES = new Set([- 'button',- 'checkbox',- 'color',- 'file',- 'hidden',- 'image',- 'radio',- 'range',- 'reset',- 'submit',-]);--interface UseMobileKeyboardOptions {- bodyRef: RefObject<HTMLElement | null>;- bottomClearance: number;- isEnabled: boolean;- isFullyExpanded: boolean;- isPageScrollLocked: boolean;- isSheetTraveling: boolean;- isOpen: boolean;- isPresented: boolean;- sheetRef: RefObject<HTMLDivElement | null>;-}--interface KeyboardGeometry {- bodyBottom: number;-}--function getObstructionTop(): number {- return window.visualViewport?.height ?? window.innerHeight;-}--// The keyboard is gone once the visible band reaches the layout viewport bottom.-function isVisualViewportRecovered(): boolean {- return getObstructionTop() >= window.innerHeight - 0.5;-}--function isIOSWebKit(): boolean {- const userAgent = window.navigator.userAgent;- return (- /iPad|iPhone|iPod/.test(userAgent) ||- (userAgent.includes('Macintosh') && window.navigator.maxTouchPoints > 1)- );-}--function isTextEntryControl(element: Element | null): element is HTMLElement {- if (element instanceof HTMLTextAreaElement) {- return !element.disabled && !element.readOnly;- }- if (element instanceof HTMLInputElement) {- return (- !element.disabled &&- !element.readOnly &&- !NON_TEXT_INPUT_TYPES.has(- (element.getAttribute('type') ?? 'text').toLowerCase(),- )- );- }- return (- element instanceof HTMLElement &&- element.matches('[contenteditable]:not([contenteditable="false"])')- );-}--function findTextEntryControl(- target: EventTarget | null,- body: HTMLElement,-): HTMLElement | null {- if (!(target instanceof Element)) {- return null;- }-- const direct = target.closest(- 'input, textarea, [contenteditable]:not([contenteditable="false"])',- );- if (body.contains(direct) && isTextEntryControl(direct)) {- return direct;- }-- const label = target.closest('label');- const control = label instanceof HTMLLabelElement ? label.control : null;- return body.contains(control) && isTextEntryControl(control) ? control : null;-}--export function useMobileKeyboard({- bodyRef,- bottomClearance,- isEnabled,- isFullyExpanded,- isPageScrollLocked,- isSheetTraveling,- isOpen,- isPresented,- sheetRef,-}: UseMobileKeyboardOptions): void {- const hasKeyboardLayoutRef = useRef(false);- const retainKeyboardLayoutRef = useRef(false);- const isFullyExpandedRef = useRef(isFullyExpanded);- const isOpenRef = useRef(isOpen);- isFullyExpandedRef.current = isFullyExpanded;- isOpenRef.current = isOpen;-- useEffect(() => {- if (!isEnabled || !isSheetTraveling) {- return;- }- const sheet = sheetRef.current;- const activeElement = document.activeElement;- if (- sheet &&- activeElement instanceof HTMLElement &&- activeElement !== sheet &&- sheet.contains(activeElement)- ) {- // Keep the current keyboard scroll range while focusing the sheet- // dismisses the keyboard. Viewport resize events unwind that layout as- // the visual viewport recovers, avoiding a content jump on the first- // drag frame.- retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;- sheet.focus({preventScroll: true});- }- }, [isEnabled, isSheetTraveling, sheetRef]);-- // Syncs the on-screen keyboard with the sheet. When a presented sheet closes,- // the focused field blurs, so the keyboard closes.- useEffect(() => {- if (!isEnabled || !isPresented || isOpen) {- return;- }- const sheet = sheetRef.current;- const activeElement = document.activeElement;- if (- sheet &&- activeElement instanceof HTMLElement &&- activeElement !== sheet &&- sheet.contains(activeElement)- ) {- retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;- activeElement.blur();- }- }, [isEnabled, isOpen, isPresented, sheetRef]);-- // Syncs the body's end inset with the visual viewport, so the on-screen- // keyboard does not cover the body.- useEffect(() => {- const body = bodyRef.current;- const sheet = sheetRef.current;- if (!isEnabled || !isPresented || !body) {- return;- }-- let keyboardGeometry: KeyboardGeometry | null = null;- let keyboardObstructionTop: number | null = null;- let bodyScrollTopAtKeyboard: number | null = null;- let documentScrollAtKeyboard: {x: number; y: number} | null = null;- const ownsFocusTransitions = isIOSWebKit();-- const clearKeyboardLayout = () => {- body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, '0px');- if (bodyScrollTopAtKeyboard != null) {- body.scrollTop = bodyScrollTopAtKeyboard;- }- keyboardGeometry = null;- keyboardObstructionTop = null;- bodyScrollTopAtKeyboard = null;- documentScrollAtKeyboard = null;- hasKeyboardLayoutRef.current = false;- retainKeyboardLayoutRef.current = false;- };-- const scrollBodyBy = (distance: number, smoothly: boolean) => {- if (typeof body.scrollBy !== 'function') {- body.scrollTop += distance;- return;- }- const reduceMotion =- typeof window.matchMedia === 'function' &&- window.matchMedia('(prefers-reduced-motion: reduce)').matches;- body.scrollBy({- top: distance,- // Not 'auto': that defers to the element's computed `scroll-behavior`,- // so a consumer's `scroll-behavior: smooth` would animate a scroll this- // hook needs to land in the same frame.- behavior: smoothly && !reduceMotion ? 'smooth' : 'instant',- });- };-- // Scroll `control` into the part of the body the keyboard leaves visible,- // reading live geometry each time.- const scrollControlIntoSafeArea = (- control: HTMLElement,- smoothly: boolean,- ) => {- const measuredBodyRect = body.getBoundingClientRect();- const measuredControlRect = control.getBoundingClientRect();- const obstructionTop = getObstructionTop();- const overlap = Math.max(0, measuredBodyRect.bottom - obstructionTop);- const clearance = overlap > 0 ? bottomClearance : 0;- const safeTop = measuredBodyRect.top;- const safeBottom = Math.min(- measuredBodyRect.bottom,- obstructionTop - clearance,- );- if (safeBottom <= safeTop) {- return;- }-- if (measuredControlRect.bottom > safeBottom) {- scrollBodyBy(measuredControlRect.bottom - safeBottom, smoothly);- } else if (measuredControlRect.top < safeTop) {- scrollBodyBy(measuredControlRect.top - safeTop, smoothly);- }- };-- const applyKeyboardGeometry = (geometry: KeyboardGeometry) => {- const obstructionTop = getObstructionTop();- // A collapsed detent can extend the body below the layout viewport even- // after the keyboard closes, so body overlap alone cannot identify- // recovery. Once the visual viewport is full height again, release the- // retained keyboard layout unconditionally.- if (isVisualViewportRecovered()) {- clearKeyboardLayout();- return;- }- const overlap = Math.max(0, geometry.bodyBottom - obstructionTop);- if (overlap === 0) {- clearKeyboardLayout();- return;- }-- const inset = Math.max(- 0,- geometry.bodyBottom - (obstructionTop - bottomClearance),- );- body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);- };-- // Take the focus transition over before the browser performs it.- //- // `blur` is dispatched in the capture phase ahead of the browser's own- // focus step, and it names the destination in `relatedTarget`. Focusing it- // here with preventScroll settles the transition: the browser's step finds- // the element already active, so it dispatches nothing further and has- // nothing to reveal.- const claimFocusTransition = (event: FocusEvent) => {- if (!isFullyExpandedRef.current) {- return;- }- const destination = findTextEntryControl(event.relatedTarget, body);- if (destination) {- if (destination !== document.activeElement) {- // Revealing the field is not this handler's job: focusing it raises- // focusin, and the viewport resize that follows the keyboard raises- // another — both already schedule the reveal below, which knows the- // safe area and scrolls only the sheet's own body.- destination.focus({preventScroll: true});- }- return;- }-- // Focus left for nothing — the keyboard's Done button parks it on the- // body. Park it on the sheet instead, so re-tapping the same field is- // still a transition this handler sees. Left on the body, the field is- // already `document.activeElement` on the next tap, no blur fires, and- // the browser reveals it its own way.- //- // Only while the sheet is open: closing blurs the field too, and there- // is no next tap to keep claimable — the host restores focus to whatever- // opened the sheet.- const origin = findTextEntryControl(event.target, body);- if (isOpenRef.current && origin && !event.relatedTarget) {- sheet?.focus({preventScroll: true});- }- };-- const revealFocusedControl = () => {- const obstructionTop = getObstructionTop();- const activeElement = document.activeElement;- const focusedControl =- activeElement instanceof HTMLElement &&- body.contains(activeElement) &&- isTextEntryControl(activeElement)- ? activeElement- : null;- // The keyboard may close while the text field remains focused (for- // example, a downward keyboard dismissal gesture on iOS). Run the full- // cleanup path so the temporary spacer and the body scroll it enabled- // are both restored. Then reveal the still-focused control against the- // recovered sheet, because it may not be the field that opened the- // keyboard and therefore may sit outside the restored scroll position.- if (hasKeyboardLayoutRef.current && isVisualViewportRecovered()) {- clearKeyboardLayout();- if (isFullyExpandedRef.current && focusedControl) {- scrollControlIntoSafeArea(focusedControl, false);- }- return;- }- if (!isFullyExpandedRef.current || focusedControl == null) {- if (retainKeyboardLayoutRef.current && keyboardGeometry) {- applyKeyboardGeometry(keyboardGeometry);- return;- }- clearKeyboardLayout();- return;- }-- // An interactively dismissed iOS keyboard can leave the accessory bar- // visible, so the visual viewport grows without reaching full height.- // Restore the pre-keyboard body position as soon as that recovery starts;- // the ordinary safe-area pass below may still scroll a low focused field- // just enough for whatever obstruction remains. Advance the remembered- // obstruction so later content mutations do not repeat this recovery.- if (- hasKeyboardLayoutRef.current &&- keyboardObstructionTop != null &&- obstructionTop > keyboardObstructionTop + 0.5 &&- bodyScrollTopAtKeyboard != null- ) {- body.scrollTop = bodyScrollTopAtKeyboard;- keyboardObstructionTop = obstructionTop;- }-- retainKeyboardLayoutRef.current = false;-- const measuredBodyRect = body.getBoundingClientRect();- const overlap = Math.max(0, measuredBodyRect.bottom - obstructionTop);- // The extra clearance leaves room for mobile suggestion UI, but only- // while the visual viewport actually overlaps the sheet. With no- // obstruction, ordinary desktop and hardware-keyboard focus must not- // shift an already visible control.- const clearance = overlap > 0 ? bottomClearance : 0;- keyboardGeometry =- overlap > 0- ? {- bodyBottom: measuredBodyRect.bottom,- }- : null;- // Where the document sits with the keyboard up and nothing yet shifted:- // the position handleDocumentScroll returns to. Captured on the- // transition only — a reveal that runs after the browser has already- // scrolled would otherwise record the shifted position as correct.- if (overlap > 0 && !hasKeyboardLayoutRef.current) {- keyboardObstructionTop = obstructionTop;- bodyScrollTopAtKeyboard = body.scrollTop;- if (isPageScrollLocked) {- documentScrollAtKeyboard = {x: window.scrollX, y: window.scrollY};- }- }- hasKeyboardLayoutRef.current = overlap > 0;-- const inset =- overlap > 0- ? Math.max(0, measuredBodyRect.bottom - (obstructionTop - clearance))- : 0;- body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);-- scrollControlIntoSafeArea(focusedControl, overlap > 0);- };-- let animationFrame = 0;- const scheduleReveal = () => {- cancelAnimationFrame(animationFrame);- animationFrame = requestAnimationFrame(revealFocusedControl);- };-- // Resuming the app re-reveals the focused field with no focus event to- // claim, so the reveal above never runs and the document scrolls — taking- // the fixed sheet with it. Put that scroll back on the event that reports- // it and re-reveal inside the sheet.- //- // Only while the page is locked, which is the only state in which a- // document scroll cannot be the user's own: behind a non-modal sheet the- // page stays scrollable, and reverting there would fight them.- const handleDocumentScroll = () => {- const expected = documentScrollAtKeyboard;- if (- expected == null ||- (window.scrollX === expected.x && window.scrollY === expected.y)- ) {- return;- }- window.scrollTo(expected.x, expected.y);- const activeElement = document.activeElement;- if (- activeElement instanceof HTMLElement &&- body.contains(activeElement) &&- isTextEntryControl(activeElement)- ) {- scrollControlIntoSafeArea(activeElement, false);- }- };-- const resizeObserver =- typeof ResizeObserver === 'undefined'- ? null- : new ResizeObserver(scheduleReveal);- const refreshObservedLayout = () => {- if (!resizeObserver) {- return;- }- resizeObserver.disconnect();-- // Body/sheet box changes include public height and xstyle updates. The- // generated inset pseudo-element changes only scroll overflow, so these- // observations do not feed the keyboard inset back into sheet geometry.- const targets = new Set<Element>([body]);- if (sheet) {- targets.add(sheet);- }- for (const child of body.children) {- targets.add(child);- }- const activeElement = document.activeElement;- if (- activeElement instanceof HTMLElement &&- body.contains(activeElement)- ) {- for (- let element: HTMLElement | null = activeElement;- element && element !== body;- element = element.parentElement- ) {- targets.add(element);- }- }- for (const target of targets) {- resizeObserver.observe(target);- }- };- const mutationObserver =- typeof MutationObserver === 'undefined'- ? null- : new MutationObserver(records => {- // Ignore the internal inset written on the body. Consumer DOM,- // text, class, style, or visibility changes can all move the- // focused control without a viewport event.- if (- records.every(- record =>- record.type === 'attributes' && record.target === body,- )- ) {- return;- }- refreshObservedLayout();- scheduleReveal();- });- const handleFocusIn = () => {- refreshObservedLayout();- scheduleReveal();- };- const handleFocusOut = () => {- // Keep the added scroll range while the keyboard animates away. A focus- // transition to another text-entry control cancels this in focusin.- retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;- scheduleReveal();- };- const handleSheetTransitionEnd = (event: TransitionEvent) => {- if (event.target === sheet && event.propertyName === 'transform') {- scheduleReveal();- }- };-- const viewport = window.visualViewport;- if (ownsFocusTransitions) {- // `blur` does not bubble, so the capture phase is the only place to hear- // every one of them — and it runs before the browser's own focus step,- // which is the only window in which the transition can still be claimed.- document.addEventListener('blur', claimFocusTransition, true);- }- body.addEventListener('focusin', handleFocusIn);- body.addEventListener('focusout', handleFocusOut);- sheet?.addEventListener('transitionend', handleSheetTransitionEnd);- viewport?.addEventListener('resize', scheduleReveal);- viewport?.addEventListener('scroll', scheduleReveal);- window.addEventListener('scroll', handleDocumentScroll);- window.addEventListener('resize', scheduleReveal);- mutationObserver?.observe(body, {- attributes: true,- characterData: true,- childList: true,- subtree: true,- });- refreshObservedLayout();- // The dialog enters the top layer in a later effect. Wait until the next- // frame so flex geometry is final before measuring the body.- scheduleReveal();-- return () => {- cancelAnimationFrame(animationFrame);- if (ownsFocusTransitions) {- document.removeEventListener('blur', claimFocusTransition, true);- }- body.removeEventListener('focusin', handleFocusIn);- body.removeEventListener('focusout', handleFocusOut);- sheet?.removeEventListener('transitionend', handleSheetTransitionEnd);- viewport?.removeEventListener('resize', scheduleReveal);- viewport?.removeEventListener('scroll', scheduleReveal);- window.removeEventListener('scroll', handleDocumentScroll);- window.removeEventListener('resize', scheduleReveal);- resizeObserver?.disconnect();- mutationObserver?.disconnect();- body.style.removeProperty(MOBILE_KEYBOARD_INSET_VAR);- hasKeyboardLayoutRef.current = false;- retainKeyboardLayoutRef.current = false;- };- }, [- bodyRef,- bottomClearance,- isEnabled,- isPageScrollLocked,- isPresented,- sheetRef,- ]);-}diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.tsindex f6422da62f..3efa88c583 100644--- a/packages/core/src/BottomSheet/useSheetGestures.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.ts@@ -354,6 +354,8 @@ export interface UseSheetGesturesOptions {snapHeights?: () => number[];/** Notified when the settled visible detent height (px) changes. */onSnap?: (heightPx: number) => void;+ /** Called once a drag first moves the sheet off its detent. */+ onTravelStart?: () => void;/*** Called with the scrim opacity the sheet should show (1 = fully visible,* 0 = hidden) as the drag moves and on settle. Full while the sheet is at@@ -508,6 +510,7 @@ export function useSheetGestures({onDismiss,snapHeights,onSnap,+ onTravelStart,onScrimOpacity,hasFixedHeight = false,}: UseSheetGesturesOptions): UseSheetGesturesResult {@@ -654,6 +657,8 @@ export function useSheetGestures({// stops by the time the re-anchor read it.const snapHeightsRef = useRef(snapHeights);snapHeightsRef.current = snapHeights;+ const onTravelStartRef = useRef(onTravelStart);+ onTravelStartRef.current = onTravelStart;const onDismissRef = useRef(onDismiss);const canDismissRef = useRef(canDismiss);@@ -1312,6 +1317,7 @@ export function useSheetGestures({if (!state.hasTraveled && next !== state.baseOffset) {state.hasTraveled = true;setIsTraveling(true);+ onTravelStartRef.current?.();}// Mirror the scrim to the live drag: full at/above the mid detent,diff --git a/packages/core/src/keyboard/README.md b/packages/core/src/keyboard/README.mdnew file mode 100644index 0000000000..c4bc77f9f9--- /dev/null+++ b/packages/core/src/keyboard/README.md@@ -0,0 +1,197 @@+# On-screen keyboard++Core's one source for the on-screen keyboard (`spec:AST-099`,+`architecture:react-component-runtime` INV11), and the keyboard layout guide+that times motion with it. Everything here is internal to+`@astryxdesign/core`: components import it from its defining file, such as+`../keyboard/keyboardHeight`, and nothing is exported from the package entry.++## The keyboard module (`keyboardHeight.ts`)++- **The height (FR2):** `measureKeyboardHeight(window)` is the layout+ viewport's height minus the visual viewport's height times its scale, in CSS+ px. A page pan is not a smaller keyboard, and a pinch zoom is not a keyboard.+ The layout viewport's height is `layoutViewportHeight(window)`+ (`../utils/layoutViewport.ts`), in layout px in every engine: WebKit reports+ `innerHeight` and `innerWidth` in the zoomed visual viewport's px, which+ `innerWidth` matching the visual viewport's width tells apart. A classic+ horizontal scrollbar, which `innerHeight` counts and the visual viewport+ does not, is taken out, so a desktop page wider than its window reads no+ keyboard. BottomSheet's obstruction reads it too.+- **Where it measures (FR6, FR7, DEC-4):** `isKeyboardMeasurable(window)` is+ true for a top-level document with a visual viewport, a browser with its own+ keyboard geometry API (`navigator.virtualKeyboard`, Chrome on Android)+ included, whose visual viewport shrinks for the keyboard as everywhere+ else. It is decided from capabilities, never from the user agent or the+ pointer. A desktop browser's visual viewport never shrinks for a keyboard,+ so it reads 0; inside an iframe the height is 0. Where the app sets+ `interactive-widget=resizes-content`, Chrome shrinks the layout viewport+ with the keyboard, so the height is 0 there too and nothing rides: the+ browser has made the inset (FR8).+- **One set of listeners (FR1, INV11):** `subscribeKeyboardHeight(window, fn)`+ delivers every report (the visual viewport's resize and scroll, the window's+ resize, and with `{focus: true}` focus moves, whose input-stream+ subscriptions exist only while such a subscriber does) from one set of listeners per window,+ however many components subscribe, and `getKeyboardHeight(window)` gives a reader the+ height that report measured. No other code in core listens to the visual+ viewport for the keyboard.+- **Focus (FR4):** `refuseFocusReveal(document, {claim, park, isActive})`+ delivers every focus move a surface claims with `preventScroll`, on the+ capture-phase `blur` before the browser's own focus step, so the browser+ never reveals a field by scrolling the document. Focus that leaves for+ nothing (the keyboard's Done) can be parked so the next tap is a transition+ again. Every caller in a document shares one listener, which lives only+ while a caller does; BottomSheet's hook installs it only under a coarse+ primary pointer.+- **The browser's own reveal pan (FR4):** `watchRevealPan(window, {owns})`+ is the one building block every keyboard-aware surface uses for a browser+ that pans the visual viewport to a focused field after the keyboard's+ report. The surface calls `report()` on each report that changes the+ height; on a later report, `isRevealPan(height)` says the visual viewport+ has moved down with no touch, document scroll or zoom since, while a text+ field the surface owns has focus, and `putBack()` pans it back without+ scrolling the document, by scrolling into view a probe fixed where the+ visual viewport sat at the report (or the element given, such as a+ full-viewport dialog). Every watch in a document shares one passive+ `touchstart` subscription on the window's input stream, which lives only+ while a surface watches. BottomSheet's hook watches while its sheet is presented+ under a coarse primary pointer; under a fine one it registers no touch+ listener.+- **The surface hook (FR4, FR5):** `useMobileKeyboard(targetRef, options)`+ (`useMobileKeyboard.ts`) keeps a focused field in a target above the+ keyboard. BottomSheet passes its panel with `{move: 'ride', inset: true}`+ and its suggestion clearance as `offset`, and enables it for a presented+ Tall sheet. The inset goes at the end of the panel's scroll area, its body,+ which `useScrollableArea` marks. The hook gives a fully expanded sheet its+ keyboard scroll range, claims focus moves into it, and puts back a document+ scroll while the page is locked. It attaches through `useAttachment`. It+ returns the inset the keyboard takes at the end of the body's content, and+ `dismiss`, which BottomSheet calls from the drag that starts to move the sheet. The hook itself dismisses the keyboard as its target closes. The sheet lays the inset out after its+ content box's children through a functional style (FR3), committed before+ the reveal scrolls into it. Under a coarse primary pointer, where the+ guide publishes the keyboard's own slide (Gboard's, in Chrome on Android),+ the sheet rides it (FR8). A reveal during the show scrolls the body at once.+ In the same commit it sets the content box so the field sits 4 px above the+ keyboard's top, and the content box then rides the rest of the show's+ curve. Through the hide the inset stays and the content box rides down to+ where 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.+- **When the keyboard goes:** the body's scroll goes back to where it was+ when the keyboard came up, within the range left once the inset drops. A+ field that keeps focus, as after iOS's downward keyboard dismissal, is then+ brought into the body's view. Where that dismissal leaves the accessory bar+ up, the visual viewport grows short of full height: the scroll goes back as+ soon as it grows, and a low field is still kept clear of the bar.++## Riding the keyboard++Layout follows the height (FR3), through a functional style on your own+element, so it is right with no animation running; for an element docked at+the bottom, `lift = height > 0 ? max(0, restingBottom − (innerHeight − height)) : 0`.+An animation that rides the keyboard is optional polish on top, timed by the+guide:++```ts+const guide = getKeyboardLayoutGuide(window);+const unsubscribe = guide.subscribe(t => {+ rideKeyboard(animator, {y: layoutLift - lift(t.to)}, t);+});+```++Each transition is+`{kind, from, to, start, velocity, animated, predicted, curve}`: heights in+CSS px, `start` on the document timeline (dated back to Gboard's start for a+slide Chrome reported, slightly ahead for a hide that starts after a blur),+and the curve the keyboard moves on: `curve`, Gboard's slide in Chrome on+Android, values and no motion role (architecture:react-component-runtime+INV11). `rideKeyboard` moves your element on the compositor from `start` on+that curve. It lands the element at once when the transition is not animated,+or when its slide has ended by the call. Hand the translate back to the layout+once the ride ends (BottomSheet's hook does, in one commit at rest). Under Reduce Motion+nothing travels with the keyboard+(design:reduced-motion): the animator's default cross-fades on a touch screen+and moves at once otherwise. `presentation(time)` gives the height presented+at any time, for something that appears while the keyboard moves.++## What the page sees++- Safari reveals a focused field by scrolling the whole page, so a layout that+ keeps its own content above the keyboard focuses its field with+ `preventScroll` (`refuseFocusReveal`).+- Firefox for Android reports the keyboard once it is up, and 54 to 143 ms+ later pans the visual viewport to a focused field the keyboard still+ covers. So BottomSheet reveals in the report's own event, and where a+ browser has panned to the field after a report (`watchRevealPan`), it+ lands the field with its own scroller, leaving a smooth reveal under way to+ land it, and only then scrolls the dialog's top back into view; a field it+ cannot bring up keeps the browser's reveal. Every later reveal lands at+ once in the report's frame. Until a browser pans once, the sheet keeps the+ smooth reveal.+- Chrome on Android (Gboard) animates its own pan to a focused field the+ keyboard still covers, by the keyboard's whole height. It starts about+ 150 ms after the report in Chrome 124, and 100 to 170 ms after it in+ Chrome 133. The page gets no frame until that pan ends, so `watchRevealPan`+ puts it back then. A Tall BottomSheet sets its field 4 px above the+ keyboard's top in the report's own commit, so the field is never covered+ when Chrome checks. Chromium 158 pans the same way when the field stays+ covered, by 312 px with the sheet's reveal on the next frame.++## What the page sees (Chromium 158 with Gboard, Android 15)++Measured frame by frame on the emulator, with a marker the page paints on each+report and Gboard's top read from every recorded frame (`../motion/android/+keyboard.ts` has the numbers and their sources). The guide reads these reports+in a browser with the VirtualKeyboard API (`keyboardProfileOf`), and the+keyboard module measures them from the visual viewport, as in every browser+(`spec:AST-099` FR8, DEC-4).++- Show: Gboard slides up over the page in about 267 ms. Chrome's one `resize`+ of the visual viewport comes just after the slide starts: its first painted+ frame trails Gboard's first moved frame by 14 to 35 ms. The guide dates the+ show back by `androidKeyboard.showReportLagMs` and rides Gboard's show+ curve, joining the slide where it is, so content riding it stays on top of+ the keyboard instead of being covered until the report.+- Hide: Gboard starts down about `androidKeyboard.hideAfterBlurMs` after the+ blur 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,+ dated back `hideReportLagMs`, the lag measured on blurs. Chrome can report+ Back later in the slide, so on Back the content starts down after the+ keyboard does.+- When focus moves from one field to another through something that brings up+ no keyboard (a popover's container), Chrome reports the keyboard gone and+ back within about 50 ms. A hide reported while a field that gained focus less+ than 150 ms ago still has it waits for the move to settle.+- `navigator.virtualKeyboard` with `overlaysContent`, the keyboard's own+ geometry, was measured and not used: in 12 shows its `geometrychange` was+ painted 0 to 67 ms after Gboard started (against 14 to 35 ms for the+ visual viewport), it failed to show the keyboard in 4 of 12 shows when set+ on focus (1 of 24 when set as the touch lands), and it hides Chromium's bottom+ toolbar on the keyboard's frame (+56 px of layout).++## Consumers++- BottomSheet (`BottomSheet/BottomSheetPanel.tsx`): `useMobileKeyboard`, whose+ inset the content box's `keyboardInset` functional style lays out as the+ content's last box (after its own children, so it adds scroll range in+ Firefox too, which keeps the content box at the body's height); it reveals the+ focused field in the keyboard report's own event, and in Chrome rides the+ content box on Gboard's slides (`rideKeyboard`, from the guide's+ transitions).++## Files++| File | What it holds |+| ------------------------ | --------------------------------------------------------------------------------------------------------------------- |+| `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. |+| `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`). |+| `index.ts` | Entry point. |++The timing constants live in `../motion/android/keyboard.ts` (Chrome with+Gboard).diff --git a/packages/core/src/keyboard/index.ts b/packages/core/src/keyboard/index.tsnew file mode 100644index 0000000000..97a8c4508c--- /dev/null+++ b/packages/core/src/keyboard/index.ts@@ -0,0 +1,48 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file index.ts+ * @input keyboardHeight.ts, keyboardLayoutGuide.ts, keyboardModel.ts and+ * rideKeyboard.ts+ * @output Re-exports the on-screen keyboard module, the keyboard layout+ * guide and rideKeyboard, with their types+ * @position Entry of the keyboard module. It is internal to core, and the+ * package entry point exports nothing here.+ *+ * SYNC: When modified, update /packages/core/src/keyboard/README.md+ */++export {+ findTextEntryControl,+ getKeyboardHeight,+ isKeyboardMeasurable,+ isTextEntryControl,+ measureKeyboardHeight,+ refuseFocusReveal,+ subscribeKeyboardHeight,+ watchRevealPan,+ type KeyboardHeightEvent,+ type RefuseFocusRevealOptions,+ type RevealPanWatch,+ type WatchRevealPanOptions,+} from './keyboardHeight';+export {+ bringsUpKeyboard,+ getKeyboardLayoutGuide,+ keyboardProfileOf,+ type KeyboardLayoutGuide,+} from './keyboardLayoutGuide';+export {rideKeyboard} from './rideKeyboard';+export {+ useMobileKeyboard,+ type MobileKeyboard,+ type MobileKeyboardOptions,+} from './useMobileKeyboard';+export {+ createKeyboardModel,+ type KeyboardCurve,+ type KeyboardModel,+ type KeyboardProfile,+ type KeyboardTransition,+ type KeyboardTransitionKind,+} from './keyboardModel';diff --git a/packages/core/src/keyboard/keyboardChromium.test.ts b/packages/core/src/keyboard/keyboardChromium.test.tsnew file mode 100644index 0000000000..0636167b45--- /dev/null+++ b/packages/core/src/keyboard/keyboardChromium.test.ts@@ -0,0 +1,282 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardChromium.test.ts+ * @input vitest, jsdom, getKeyboardLayoutGuide, a stand-in visual viewport in+ * Chrome's profile and a stand-in navigator.virtualKeyboard+ * @output Tests the guide on Chrome. A keyboard coming up rides from its+ * report, dated back to Gboard's start, on Gboard's slide. The accessory+ * bar's report rides to the last keyboard's height. A hide rides down from+ * the blur or from its report. Focus moving between fields holds Chrome's+ * momentary hide. The page's VirtualKeyboard is never touched.+ * @position Unit tests for the Chrome part of keyboard/keyboardLayoutGuide.ts+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {keyboard as androidKeyboard} from '../motion/android';+import {getKeyboardLayoutGuide} from './keyboardLayoutGuide';+import type {KeyboardTransition} from './keyboardModel';++let view: EventTarget & {height: number; offsetTop: number; scale: number};+let virtualKeyboard: EventTarget & {overlaysContent: boolean};+let a: HTMLInputElement;+let b: HTMLInputElement;+let button: HTMLButtonElement;+const seen: KeyboardTransition[] = [];+let unsubscribe: () => void = () => {};+const innerHeightDescriptor = Object.getOwnPropertyDescriptor(+ window,+ 'innerHeight',+) as PropertyDescriptor;++const report = (cover: number) => {+ view.height = window.innerHeight - cover;+ view.dispatchEvent(new Event('resize'));+};++describe('the keyboard layout guide on Chrome', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ view = Object.assign(new EventTarget(), {+ height: window.innerHeight,+ offsetTop: 0,+ scale: 1,+ });+ Object.defineProperty(window, 'visualViewport', {+ configurable: true,+ value: view,+ });+ virtualKeyboard = Object.assign(new EventTarget(), {+ overlaysContent: false,+ });+ Object.defineProperty(window.navigator, 'virtualKeyboard', {+ configurable: true,+ value: virtualKeyboard,+ });+ // Under a finger: the keyboard module measures Chrome's visual viewport.+ vi.stubGlobal(+ 'matchMedia',+ (query: string) =>+ ({+ matches: query === '(pointer: coarse)',+ media: query,+ }) as unknown as MediaQueryList,+ );+ document.body.innerHTML =+ '<input id="a"><button id="pop">Open</button><input id="b">';+ a = document.getElementById('a') as HTMLInputElement;+ b = document.getElementById('b') as HTMLInputElement;+ button = document.getElementById('pop') as HTMLButtonElement;+ seen.length = 0;+ unsubscribe = getKeyboardLayoutGuide(window).subscribe(t => seen.push(t));+ });++ afterEach(() => {+ unsubscribe();+ (document.activeElement as HTMLElement | null)?.blur();+ document.body.innerHTML = '';+ Object.defineProperty(window, 'innerHeight', innerHeightDescriptor);+ Reflect.deleteProperty(window, 'visualViewport');+ Reflect.deleteProperty(window.navigator, 'virtualKeyboard');+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it('rides a keyboard coming up from its report, dated back to Gboard’s start, on Gboard’s slide', () => {+ expect(getKeyboardLayoutGuide(window).profile).toBe('chromium');+ a.focus();+ let reportAt = 0;+ view.addEventListener(+ 'resize',+ event => {+ reportAt = event.timeStamp;+ },+ {once: true},+ );+ report(312);+ expect(seen).toHaveLength(1);+ expect(seen[0]).toMatchObject({kind: 'show', to: 312, animated: true});+ expect(seen[0]?.start).toBeCloseTo(+ reportAt - androidKeyboard.showReportLagMs,+ 6,+ );+ expect(seen[0]?.curve).toEqual({+ durationMs: androidKeyboard.showMs,+ points: androidKeyboard.showCurve,+ });+ });++ it('rides to the last keyboard’s height for the accessory bar’s report, and the keyboard’s report confirms it', () => {+ a.focus();+ report(312);+ a.blur();+ report(0);+ vi.advanceTimersByTime(1000);+ seen.length = 0;+ b.focus();+ report(48);+ expect(seen.at(-1)).toMatchObject({+ kind: 'show',+ to: 312,+ animated: true,+ predicted: true,+ });+ report(312);+ // Confirmed: no second motion.+ expect(seen).toHaveLength(1);+ expect(getKeyboardLayoutGuide(window).transition.predicted).toBe(false);+ });++ it('rides a hide down from hideAfterBlurMs after our blur, on Gboard’s slide', () => {+ a.focus();+ report(312);+ vi.advanceTimersByTime(1000);+ let blurAt = 0;+ a.addEventListener(+ 'focusout',+ event => {+ blurAt = event.timeStamp;+ },+ {once: true},+ );+ a.blur();+ const hide = seen.at(-1);+ expect(hide).toMatchObject({kind: 'hide', to: 0, animated: true});+ expect(hide?.start).toBeCloseTo(+ blurAt + androidKeyboard.hideAfterBlurMs,+ 6,+ );+ expect(hide?.curve).toEqual({+ durationMs: androidKeyboard.hideMs,+ points: androidKeyboard.hideCurve,+ });+ // Chrome's report confirms it.+ report(0);+ 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.+ vi.spyOn(window.performance, 'now').mockImplementation(() => Date.now());+ a.focus();+ report(312);+ vi.advanceTimersByTime(1000);+ 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);+ expect(seen.at(-1)).toBe(hide);+ vi.advanceTimersByTime(2);+ expect(seen.at(-1)).toMatchObject({kind: 'show', to: 312});+ });++ it('rides a hide nothing predicted (Back) down from its report, dated back to Gboard’s start', () => {+ a.focus();+ report(312);+ vi.advanceTimersByTime(1000);+ let reportAt = 0;+ view.addEventListener(+ 'resize',+ event => {+ reportAt = event.timeStamp;+ },+ {once: true},+ );+ report(0);+ expect(seen.at(-1)).toMatchObject({kind: 'hide', to: 0, animated: true});+ expect(seen.at(-1)?.start).toBeCloseTo(+ reportAt - androidKeyboard.hideReportLagMs,+ 6,+ );+ });++ it.each([+ [+ 'a select',+ () => {+ const select = document.createElement('select');+ select.append(new Option('One'), new Option('Two'));+ return select;+ },+ ],+ [+ 'a date input',+ () => Object.assign(document.createElement('input'), {type: 'date'}),+ ],+ [+ 'a time input',+ () => Object.assign(document.createElement('input'), {type: 'time'}),+ ],+ ] as const)(+ 'rides the hide down when focus moves to %s, whose picker Chrome opens over the page as the keyboard goes',+ (_, make) => {+ const picker = make();+ document.body.append(picker);+ a.focus();+ report(312);+ vi.advanceTimersByTime(1000);+ expect(seen.map(t => t.kind)).toEqual(['show']);+ // No keyboard comes back for a picker: its hide is not a momentary one.+ picker.focus();+ report(0);+ expect(seen.at(-1)).toMatchObject({kind: 'hide', to: 0, animated: true});+ vi.advanceTimersByTime(500);+ expect(getKeyboardLayoutGuide(window).inset).toBe(0);+ },+ );++ it('holds the momentary hide Chrome reports while focus moves to another field', () => {+ a.focus();+ report(360);+ vi.advanceTimersByTime(1000);+ expect(seen.map(t => t.kind)).toEqual(['show']);+ // Through a popover's container to its field: Chrome reports the+ // keyboard gone, then back, within about 50 ms.+ button.focus();+ b.focus();+ vi.advanceTimersByTime(30);+ report(0);+ vi.advanceTimersByTime(15);+ report(360);+ vi.advanceTimersByTime(500);+ expect(seen.map(t => t.kind)).toEqual(['show', 'hide', 'show']);+ expect(getKeyboardLayoutGuide(window).inset).toBe(360);+ });++ it('rides nothing where the app sets interactive-widget=resizes-content, since Chrome shrinks the layout viewport with the keyboard (FR8)', () => {+ const full = window.innerHeight;+ // Chrome lays the page out again in the room above the keyboard: the+ // layout viewport shrinks with the visual viewport, so FR2 reads 0.+ const resizeContent = (cover: number) => {+ Object.defineProperty(window, 'innerHeight', {+ configurable: true,+ value: full - cover,+ });+ view.height = full - cover;+ window.dispatchEvent(new Event('resize'));+ view.dispatchEvent(new Event('resize'));+ };+ a.focus();+ resizeContent(312);+ vi.advanceTimersByTime(1000);+ a.blur();+ resizeContent(0);+ vi.advanceTimersByTime(1000);+ b.focus();+ resizeContent(312);+ vi.advanceTimersByTime(1000);++ expect(seen.filter(t => t.to > 0 || t.from > 0)).toEqual([]);+ expect(getKeyboardLayoutGuide(window).transition.to).toBe(0);+ });++ it('never touches the page’s VirtualKeyboard', () => {+ a.focus();+ report(312);+ a.blur();+ expect(virtualKeyboard.overlaysContent).toBe(false);+ });+});diff --git a/packages/core/src/keyboard/keyboardHeight.test.ts b/packages/core/src/keyboard/keyboardHeight.test.tsnew file mode 100644index 0000000000..81b6d5d69d--- /dev/null+++ b/packages/core/src/keyboard/keyboardHeight.test.ts@@ -0,0 +1,776 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardHeight.test.ts+ * @input keyboardHeight.ts, the keyboard layout guide, a stand-in visual+ * viewport+ * @output Tests for the on-screen keyboard module: the height, where it+ * measures, its one set of listeners and the focus refusal+ * @position Keyboard module tests+ */++import fs from 'node:fs';+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 {+ __resetLayoutViewportForTest,+ layoutViewportHeight,+} from '../utils/layoutViewport';+import {+ findTextEntryControl,+ getKeyboardHeight,+ isKeyboardMeasurable,+ isTextEntryControl,+ measureKeyboardHeight,+ refuseFocusReveal,+ subscribeKeyboardHeight,+ watchRevealPan,+ type KeyboardHeightEvent,+} from './keyboardHeight';++type FakeViewport = EventTarget & {+ height: number;+ offsetTop: number;+ scale: number;+ width?: number;+};++let viewport: FakeViewport;++function report(changes: Partial<FakeViewport>) {+ Object.assign(viewport, changes);+ act(() => {+ viewport.dispatchEvent(new Event('resize'));+ });+}++beforeEach(() => {+ viewport = Object.assign(new EventTarget(), {+ height: window.innerHeight,+ offsetTop: 0,+ scale: 1,+ });+ Object.defineProperty(window, 'visualViewport', {+ configurable: true,+ value: viewport,+ });+});++afterEach(() => {+ Reflect.deleteProperty(window, 'visualViewport');+ Reflect.deleteProperty(window.navigator, 'virtualKeyboard');+ for (const key of ['clientWidth', 'clientHeight', 'scrollWidth']) {+ Reflect.deleteProperty(document.documentElement, key);+ }+ __resetLayoutViewportForTest();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('the keyboard height (spec:AST-099 FR2)', () => {+ it('is the layout viewport minus the visual viewport', () => {+ viewport.height = window.innerHeight - 300;+ expect(measureKeyboardHeight(window)).toBe(300);+ });++ it('is not made smaller by a page pan', () => {+ viewport.height = window.innerHeight - 300;+ viewport.offsetTop = 120;+ expect(measureKeyboardHeight(window)).toBe(300);+ });++ it('is 0 while pinch-zoomed with no keyboard, and the keyboard with one', () => {+ viewport.scale = 2;+ viewport.height = window.innerHeight / 2;+ expect(measureKeyboardHeight(window)).toBe(0);+ viewport.height = (window.innerHeight - 300) / 2;+ expect(measureKeyboardHeight(window)).toBe(300);+ });++ it('is 0 with no keyboard shown', () => {+ expect(measureKeyboardHeight(window)).toBe(0);+ });+});++describe('the layout viewport WebKit reports under a pinch zoom (FR2)', () => {+ // Measured in Safari on iOS 26.2 on an iPhone 17 Pro, with a 402 × 714+ // layout viewport and a 337 px keyboard. WebKit reports innerWidth and+ // innerHeight in the zoomed visual viewport's px. The visual viewport's+ // height times its scale stays in layout px.+ function safari({+ innerHeight,+ innerWidth,+ height,+ scale,+ offsetTop = 0,+ }: {+ innerHeight: number;+ innerWidth: number;+ height: number;+ scale: number;+ offsetTop?: number;+ }) {+ vi.stubGlobal('innerHeight', innerHeight);+ vi.stubGlobal('innerWidth', innerWidth);+ // The visual viewport is the 402 px layout width over the zoom.+ Object.assign(viewport, {height, scale, offsetTop, width: 402 / scale});+ }++ it('reads the keyboard at scale 1', () => {+ safari({innerHeight: 714, innerWidth: 402, height: 377, scale: 1});+ expect(measureKeyboardHeight(window)).toBe(337);+ expect(layoutViewportHeight(window)).toBe(714);+ });++ it('reads the same keyboard pinch-zoomed to 1.33', () => {+ safari({innerHeight: 536, innerWidth: 302, height: 282.75, scale: 4 / 3});+ expect(Math.abs(measureKeyboardHeight(window) - 337)).toBeLessThan(1);+ });++ it('follows the layout viewport WebKit clamps to the document after a scroll', () => {+ safari({+ innerHeight: 666,+ innerWidth: 402,+ height: 377,+ scale: 1,+ offsetTop: 120,+ });+ expect(measureKeyboardHeight(window)).toBe(289);+ });++ it('reads the same keyboard scrolled and pinch-zoomed', () => {+ safari({+ innerHeight: 536,+ innerWidth: 302,+ height: 282.75,+ scale: 4 / 3,+ offsetTop: 154.5,+ });+ expect(Math.abs(measureKeyboardHeight(window) - 337)).toBeLessThan(1);+ });++ it('keeps the keyboard past a 2x zoom, where innerHeight alone reads none', () => {+ safari({innerHeight: 357, innerWidth: 201, height: 188.5, scale: 2});+ expect(measureKeyboardHeight(window)).toBe(337);+ });++ it('reads no keyboard pinch-zoomed with none, in WebKit and where innerHeight ignores the zoom', () => {+ safari({innerHeight: 536, innerWidth: 302, height: 536, scale: 4 / 3});+ expect(measureKeyboardHeight(window)).toBe(0);+ safari({innerHeight: 714, innerWidth: 402, height: 535.5, scale: 4 / 3});+ expect(measureKeyboardHeight(window)).toBe(0);+ });++ it('reads no keyboard beside a classic scrollbar', () => {+ // A desktop page with a 17 px vertical scrollbar, which innerWidth and+ // not the document's client width or the visual viewport counts.+ vi.stubGlobal('innerHeight', 800);+ vi.stubGlobal('innerWidth', 1280);+ Object.defineProperty(document.documentElement, 'clientWidth', {+ configurable: true,+ value: 1263,+ });+ Object.assign(viewport, {height: 800, scale: 1, width: 1263});+ expect(layoutViewportHeight(window)).toBe(800);+ expect(measureKeyboardHeight(window)).toBe(0);+ });++ /** The document's root: its client box and how wide its content is. */+ function root(box: {+ clientHeight: number;+ clientWidth: number;+ scrollWidth: number;+ }) {+ for (const [key, value] of Object.entries(box)) {+ Object.defineProperty(document.documentElement, key, {+ configurable: true,+ value,+ });+ }+ }++ /**+ * Scrollbars that take `thickness` px of a scrolling box (0: overlaid).+ * `probes` counts the scrolling boxes measured.+ */+ function scrollbars(thickness: number): {probes: number} {+ const counter = {probes: 0};+ const scrolls = (el: Element) =>+ el instanceof HTMLElement && el.style.overflow === 'scroll';+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(+ function (this: HTMLElement) {+ if (scrolls(this)) {+ counter.probes += 1;+ return 100;+ }+ return 0;+ },+ );+ vi.spyOn(Element.prototype, 'clientHeight', 'get').mockImplementation(+ function (this: Element) {+ return scrolls(this) ? 100 - thickness : 0;+ },+ );+ return counter;+ }++ it('reads no keyboard from a desktop page\u2019s classic horizontal scrollbar', () => {+ // Chromium with classic scrollbars, on a page wider than the window.+ // innerHeight counts the 15 px scrollbar. The visual viewport and the+ // document's client height do not.+ scrollbars(15);+ vi.stubGlobal('innerHeight', 800);+ vi.stubGlobal('innerWidth', 1280);+ root({clientHeight: 785, clientWidth: 1280, scrollWidth: 1600});+ Object.assign(viewport, {height: 785, scale: 1, width: 1280});+ expect(layoutViewportHeight(window)).toBe(785);+ expect(measureKeyboardHeight(window)).toBe(0);+ });++ it('measures the scrollbar once, however many keyboard changes read the height (INV11)', () => {+ // The probe writes to the document and forces a layout: it runs once,+ // and every later measurement reuses the thickness.+ const counter = scrollbars(15);+ vi.stubGlobal('innerHeight', 800);+ vi.stubGlobal('innerWidth', 1280);+ root({clientHeight: 785, clientWidth: 1280, scrollWidth: 1600});+ Object.assign(viewport, {height: 785, scale: 1, width: 1280});+ for (let i = 0; i < 3; i += 1) {+ expect(measureKeyboardHeight(window)).toBe(0);+ }+ expect(counter.probes).toBe(1);+ });++ it('reads the whole keyboard under a hidden toolbar, which no scrollbar explains', () => {+ // Chrome on Android sizes the document's client height to the viewport+ // with its toolbar shown, 754 px, and overlays its scrollbars. So the+ // 136 px a hidden toolbar adds to innerHeight is no scrollbar, also on a+ // page wider than the window.+ scrollbars(0);+ vi.stubGlobal('innerHeight', 890);+ vi.stubGlobal('innerWidth', 411);+ root({clientHeight: 754, clientWidth: 411, scrollWidth: 1600});+ Object.assign(viewport, {height: 590, scale: 1, width: 411});+ expect(measureKeyboardHeight(window)).toBe(300);+ });+});++describe('where the keyboard is measured (FR6, FR7)', () => {+ it('measures with a visual viewport and no keyboard geometry API', () => {+ expect(isKeyboardMeasurable(window)).toBe(true);+ });++ it('measures Chrome on Android from its visual viewport, which has its own keyboard geometry API (DEC-4)', () => {+ // Gboard shrinks Chrome's visual viewport while the layout viewport keeps+ // its height, as everywhere else; the VirtualKeyboard API is not read.+ Object.defineProperty(window.navigator, 'virtualKeyboard', {+ configurable: true,+ value: {overlaysContent: false},+ });+ vi.stubGlobal(+ 'matchMedia',+ (query: string) =>+ ({matches: false, media: query}) as unknown as MediaQueryList,+ );+ viewport.height = window.innerHeight - 300;+ expect(isKeyboardMeasurable(window)).toBe(true);+ expect(measureKeyboardHeight(window)).toBe(300);+ });++ it('reads no keyboard where a desktop browser with the API shows none', () => {+ Object.defineProperty(window.navigator, 'virtualKeyboard', {+ configurable: true,+ value: {overlaysContent: false},+ });+ expect(measureKeyboardHeight(window)).toBe(0);+ });++ it('reads no keyboard under interactive-widget=resizes-content, where Chrome shrinks the layout viewport with it (FR8)', () => {+ Object.defineProperty(window.navigator, 'virtualKeyboard', {+ configurable: true,+ value: {overlaysContent: false},+ });+ const full = window.innerHeight;+ Object.defineProperty(window, 'innerHeight', {+ configurable: true,+ value: full - 300,+ });+ try {+ viewport.height = full - 300;+ expect(measureKeyboardHeight(window)).toBe(0);+ } finally {+ Object.defineProperty(window, 'innerHeight', {+ configurable: true,+ value: full,+ });+ }+ });++ it('measures nothing without a visual viewport', () => {+ Reflect.deleteProperty(window, 'visualViewport');+ expect(measureKeyboardHeight(window)).toBe(0);+ });++ it('measures nothing inside an iframe', () => {+ const frame = document.createElement('iframe');+ document.body.append(frame);+ const inner = frame.contentWindow as Window;+ Object.defineProperty(inner, 'visualViewport', {+ configurable: true,+ value: Object.assign(new EventTarget(), {+ height: inner.innerHeight - 300,+ offsetTop: 0,+ scale: 1,+ }),+ });+ expect(isKeyboardMeasurable(inner)).toBe(false);+ expect(measureKeyboardHeight(inner)).toBe(0);+ frame.remove();+ });+});++describe('one set of listeners per window (FR1, INV11)', () => {+ it('shares the listeners among subscribers and removes them with the last', () => {+ const add = vi.spyOn(viewport, 'addEventListener');+ const remove = vi.spyOn(viewport, 'removeEventListener');+ const first = vi.fn();+ const second = vi.fn();+ const stopFirst = subscribeKeyboardHeight(window, first);+ const stopSecond = subscribeKeyboardHeight(window, second);+ expect(add.mock.calls.map(([type]) => type)).toEqual(['resize', 'scroll']);++ report({height: window.innerHeight - 300});+ expect(first).toHaveBeenLastCalledWith(+ expect.objectContaining({type: 'viewport', height: 300}),+ );+ expect(second).toHaveBeenLastCalledWith(+ expect.objectContaining({type: 'viewport', height: 300}),+ );++ stopFirst();+ expect(remove).not.toHaveBeenCalled();+ stopSecond();+ expect(remove.mock.calls.map(([type]) => type)).toEqual([+ 'resize',+ 'scroll',+ ]);+ });++ it('feeds the keyboard layout guide, which adds no listener of its own', () => {+ const add = vi.spyOn(viewport, 'addEventListener');+ const windowAdd = vi.spyOn(window, 'addEventListener');+ const stopHook = subscribeKeyboardHeight(window, () => {});+ const guide = getKeyboardLayoutGuide(window);+ const transitions: number[] = [];+ const stopGuide = guide.subscribe(transition => {+ transitions.push(transition.to);+ });+ expect(add).toHaveBeenCalledTimes(2);+ expect(+ windowAdd.mock.calls.filter(([type]) => type === 'resize'),+ ).toHaveLength(1);++ report({height: window.innerHeight - 300});+ expect(transitions.at(-1)).toBe(300);+ expect(guide.inset).toBe(300);+ stopGuide();+ stopHook();+ });++ it('reads the layout once per keyboard change, however many read the height (INV11)', () => {+ // Count every read of the visual viewport's height: one per measurement.+ let height = viewport.height;+ let reads = 0;+ Object.defineProperty(viewport, 'height', {+ configurable: true,+ get: () => {+ reads += 1;+ return height;+ },+ set: (value: number) => {+ height = value;+ },+ });+ const seen: number[] = [];+ // Three readers, each reading the height again as it lays out.+ const reader = () => (event: KeyboardHeightEvent) => {+ if (event.type === 'viewport') {+ seen.push(getKeyboardHeight(window), event.height);+ }+ };+ // And the keyboard layout guide, whose rider reads the height again as+ // it commits its layout.+ const stopGuide = getKeyboardLayoutGuide(window).subscribe(transition => {+ seen.push(getKeyboardHeight(window), transition.to);+ });+ const stops = [reader(), reader(), reader()].map(listener =>+ subscribeKeyboardHeight(window, listener),+ );+ try {+ reads = 0;+ report({height: window.innerHeight - 300});+ expect(seen).toHaveLength(8);+ expect(seen.every(value => value === 300)).toBe(true);+ expect(reads).toBe(1);+ } finally {+ for (const stop of stops) {+ stop();+ }+ stopGuide();+ }+ });+ it('listens to focus moves only while a subscriber asks for them, through one pair of shared input listeners (spec:AST-094 FR24)', () => {+ const documentAdd = vi.spyOn(window, 'addEventListener');+ const documentRemove = vi.spyOn(window, 'removeEventListener');+ const focusCalls = (spy: typeof documentAdd) =>+ spy.mock.calls+ .filter(([type]) => type.startsWith('focus'))+ .map(([type]) => type);+ const viewportTypes: string[] = [];+ const guideTypes: string[] = [];+ const input = document.createElement('input');+ document.body.append(input);+ // A viewport reader (a Tall BottomSheet's hook) adds no focus listener.+ const stopViewport = subscribeKeyboardHeight(window, event => {+ viewportTypes.push(event.type);+ });+ try {+ expect(focusCalls(documentAdd)).toEqual([]);+ // Readers of focus moves (the keyboard layout guide) share one pair.+ const stopA = subscribeKeyboardHeight(+ window,+ event => {+ guideTypes.push(event.type);+ },+ {focus: true},+ );+ const stopB = subscribeKeyboardHeight(window, () => {}, {focus: true});+ expect(focusCalls(documentAdd)).toEqual(['focusin', 'focusout']);+ input.focus();+ input.blur();+ expect(guideTypes).toEqual(['focusin', 'focusout']);+ expect(viewportTypes).toEqual([]);+ stopA();+ expect(focusCalls(documentRemove)).toEqual([]);+ stopB();+ expect(focusCalls(documentRemove)).toEqual(['focusin', 'focusout']);+ } finally {+ input.remove();+ stopViewport();+ documentAdd.mockRestore();+ documentRemove.mockRestore();+ }+ });++ it('reports the window\u2019s own resize, not a resize event an element sends through the window', () => {+ const heights: number[] = [];+ const stop = subscribeKeyboardHeight(window, event => {+ heights.push(event.height);+ });+ try {+ document.body.dispatchEvent(new Event('resize'));+ expect(heights).toEqual([]);+ window.dispatchEvent(new Event('resize'));+ expect(heights).toHaveLength(1);+ } finally {+ stop();+ }+ });++ it('reads a keyboard that is already up when the first subscriber attaches', () => {+ // Nothing listens yet: the keyboard came up before any keyboard-aware+ // component mounted (a sheet opened from a focused field).+ viewport.height = window.innerHeight - 300;+ expect(getKeyboardHeight(window)).toBe(300);+ const heights: number[] = [];+ const stop = subscribeKeyboardHeight(window, event => {+ if (event.type === 'viewport') {+ heights.push(event.height);+ }+ });+ expect(getKeyboardHeight(window)).toBe(300);+ // The guide reads it too.+ const guide = getKeyboardLayoutGuide(window);+ const stopGuide = guide.subscribe(() => {});+ expect(guide.inset).toBe(300);+ report({height: window.innerHeight});+ expect(heights).toEqual([0]);+ stopGuide();+ stop();+ });+ it('is the only visual viewport listener for the keyboard in core', () => {+ // Visible-viewport readers that place layers and scroll areas, not the+ // keyboard; the layer cap's keyboard is architecture:layer-runtime's.+ const visibleViewportReaders = new Set([+ 'AppShell/observeMainOverflow.ts',+ 'DropdownMenu/useMenuOverflow.ts',+ 'Popover/Popover.tsx',+ 'hooks/useScrollableArea.ts',+ ]);+ const root = path.resolve(__dirname, '..');+ const offenders: string[] = [];+ const walk = (dir: string) => {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const file = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ walk(file);+ continue;+ }+ if (+ !/\.tsx?$/.test(entry.name) ||+ /\.(test|spec|stories)\./.test(entry.name)+ ) {+ continue;+ }+ const relative = path.relative(root, file).split(path.sep).join('/');+ const source = fs.readFileSync(file, 'utf8');+ if (+ /visualViewport\??\.addEventListener|viewport\??\.addEventListener\(\s*'(resize|scroll)'/.test(+ source,+ ) &&+ relative !== 'keyboard/keyboardHeight.ts' &&+ !visibleViewportReaders.has(relative)+ ) {+ offenders.push(relative);+ }+ }+ };+ walk(root);+ expect(offenders).toEqual([]);+ });+});++describe('the focus refusal (FR4)', () => {+ it('delivers a claimed focus move with preventScroll and parks focus that leaves for nothing', () => {+ const first = document.createElement('input');+ const second = document.createElement('input');+ const park = vi.fn();+ document.body.append(first, second);+ const stop = refuseFocusReveal(document, {+ claim: target => (target === second ? second : null),+ park,+ });+ const focus = vi.spyOn(second, 'focus');+ first.focus();+ second.focus();+ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ second.blur();+ expect(park).toHaveBeenCalledWith(second);+ stop();+ first.remove();+ second.remove();+ });++ it('leaves the window\u2019s own blur alone: it moves no focus in the document', () => {+ const parked: unknown[] = [];+ const stop = refuseFocusReveal(document, {+ claim: () => null,+ park: origin => parked.push(origin),+ });+ try {+ window.dispatchEvent(new FocusEvent('blur'));+ expect(parked).toEqual([]);+ } finally {+ stop();+ }+ });++ it('shares one blur subscription among its callers, each still hearing every blur (spec:AST-094 FR24)', () => {+ const add = vi.spyOn(window, 'addEventListener');+ const remove = vi.spyOn(window, 'removeEventListener');+ const field = document.createElement('input');+ const other = document.createElement('input');+ document.body.append(field, other);+ const heard: string[] = [];+ const stopFirst = refuseFocusReveal(document, {+ claim: () => {+ heard.push('first');+ return null;+ },+ });+ const stopSecond = refuseFocusReveal(document, {+ claim: () => {+ heard.push('second');+ return null;+ },+ });+ expect(add.mock.calls.filter(([type]) => type === 'blur')).toHaveLength(1);+ field.focus();+ other.focus();+ expect(heard).toEqual(['first', 'second']);+ stopFirst();+ expect(remove).not.toHaveBeenCalled();+ field.focus();+ expect(heard).toEqual(['first', 'second', 'second']);+ stopSecond();+ expect(remove.mock.calls.map(([type]) => type)).toEqual(['blur']);+ field.remove();+ other.remove();+ });+});++describe('the browser\u2019s own reveal pan (FR4)', () => {+ function setup() {+ const region = document.createElement('div');+ const field = document.createElement('textarea');+ const outside = document.createElement('textarea');+ region.append(field);+ document.body.append(region, outside);+ const watch = watchRevealPan(window, {+ owns: focused => region.contains(focused),+ });+ field.focus();+ viewport.height = window.innerHeight - 300;+ watch.report();+ return {region, field, outside, watch};+ }++ afterEach(() => {+ document.body.replaceChildren();+ });++ it('sees the visual viewport moving down after the report as a reveal pan of an owned field', () => {+ const {watch} = setup();+ expect(watch.isRevealPan(300)).toBe(false);+ viewport.offsetTop = 300;+ expect(watch.isRevealPan(300)).toBe(true);+ expect(watch.isRevealPan(0)).toBe(false);+ watch.stop();+ });++ it('leaves alone a reader\u2019s own pan, a document scroll, a zoom, and a field it does not own', () => {+ const touched = setup();+ document.dispatchEvent(new Event('touchstart'));+ viewport.offsetTop = 300;+ expect(touched.watch.isRevealPan(300)).toBe(false);+ touched.watch.stop();+ document.body.replaceChildren();+ viewport.offsetTop = 0;++ const scrolled = setup();+ vi.stubGlobal('scrollY', 120);+ viewport.offsetTop = 300;+ expect(scrolled.watch.isRevealPan(300)).toBe(false);+ scrolled.watch.stop();+ vi.unstubAllGlobals();+ document.body.replaceChildren();+ viewport.offsetTop = 0;++ const zoomed = setup();+ Object.assign(viewport, {offsetTop: 300, scale: 1.5});+ expect(zoomed.watch.isRevealPan(300)).toBe(false);+ zoomed.watch.stop();+ document.body.replaceChildren();+ Object.assign(viewport, {offsetTop: 0, scale: 1});++ const elsewhere = setup();+ elsewhere.outside.focus();+ viewport.offsetTop = 300;+ expect(elsewhere.watch.isRevealPan(300)).toBe(false);+ elsewhere.watch.stop();+ });++ it('puts the pan back by scrolling a fixed probe at the report\u2019s offset into view, or a given anchor', () => {+ const {watch} = setup();+ const scrolled: {element: HTMLElement; position: string; top: string}[] =+ [];+ // jsdom has no scrollIntoView.+ Object.defineProperty(Element.prototype, 'scrollIntoView', {+ configurable: true,+ value(this: HTMLElement) {+ scrolled.push({+ element: this,+ position: this.style.position,+ top: this.style.top,+ });+ },+ });+ viewport.offsetTop = 300;+ watch.putBack();+ expect(scrolled).toHaveLength(1);+ expect(scrolled[0].position).toBe('fixed');+ expect(scrolled[0].top).toBe('0px');+ // The probe is gone once the sheet puts the pan back.+ expect(scrolled[0].element.isConnected).toBe(false);++ const anchor = document.createElement('dialog');+ document.body.append(anchor);+ watch.putBack(anchor);+ expect(scrolled.at(-1)?.element).toBe(anchor);+ watch.stop();+ Reflect.deleteProperty(Element.prototype, 'scrollIntoView');+ });++ it('listens for touches only while it watches', () => {+ const add = vi.spyOn(window, 'addEventListener');+ const remove = vi.spyOn(window, 'removeEventListener');+ const watch = watchRevealPan(window, {owns: () => true});+ expect(add.mock.calls.map(([type]) => type)).toEqual(['touchstart']);+ watch.stop();+ expect(remove.mock.calls.map(([type]) => type)).toEqual(['touchstart']);+ });++ it('shares one touch subscription among its watches (architecture INV13, spec:AST-094 FR24)', () => {+ const add = vi.spyOn(window, 'addEventListener');+ const remove = vi.spyOn(window, 'removeEventListener');+ const touched: string[] = [];+ const first = watchRevealPan(window, {+ owns: () => true,+ onTouch: () => touched.push('first'),+ });+ const second = watchRevealPan(window, {+ owns: () => true,+ onTouch: () => touched.push('second'),+ });+ expect(add.mock.calls.map(([type]) => type)).toEqual(['touchstart']);+ document.dispatchEvent(new Event('touchstart'));+ expect(touched).toEqual(['first', 'second']);+ first.stop();+ expect(remove).not.toHaveBeenCalled();+ document.dispatchEvent(new Event('touchstart'));+ expect(touched).toEqual(['first', 'second', 'second']);+ second.stop();+ expect(remove.mock.calls.map(([type]) => type)).toEqual(['touchstart']);+ });+});++describe('the text-entry predicate', () => {+ it('reads an inputmode="none" field as no text entry, as the keyboard layout guide does', () => {+ const input = document.createElement('input');+ input.setAttribute('inputmode', 'none');+ document.body.append(input);+ try {+ expect(isTextEntryControl(input)).toBe(false);+ expect(findTextEntryControl(input, document.body)).toBeNull();+ expect(bringsUpKeyboard(input)).toBe(false);+ } finally {+ input.remove();+ }+ });++ it('gives the keyboard layout guide only a select beyond the text-entry controls', () => {+ const select = document.createElement('select');+ const text = document.createElement('input');+ const box = document.createElement('input');+ box.type = 'checkbox';+ const area = document.createElement('textarea');+ area.readOnly = true;+ const editable = document.createElement('div');+ editable.setAttribute('contenteditable', '');+ document.body.append(select, text, box, area, editable);+ try {+ expect(isTextEntryControl(select)).toBe(false);+ expect(bringsUpKeyboard(select)).toBe(true);+ for (const element of [text, box, area, editable]) {+ expect(bringsUpKeyboard(element)).toBe(isTextEntryControl(element));+ }+ } finally {+ for (const element of [select, text, box, area, editable]) {+ element.remove();+ }+ }+ });+});diff --git a/packages/core/src/keyboard/keyboardHeight.ts b/packages/core/src/keyboard/keyboardHeight.tsnew file mode 100644index 0000000000..3a16909b8f--- /dev/null+++ b/packages/core/src/keyboard/keyboardHeight.ts@@ -0,0 +1,543 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file keyboardHeight.ts+ * @input The visual viewport, the window's input stream (focus, blur,+ * resize, scroll and touch), and the layout viewport's height+ * @output The on-screen keyboard module: measureKeyboardHeight,+ * isKeyboardMeasurable, subscribeKeyboardHeight, getKeyboardHeight,+ * isTextEntryControl, findTextEntryControl, refuseFocusReveal and+ * watchRevealPan+ * @position Core's one source for the on-screen keyboard. It is internal to+ * core and never exported from the package.+ *+ * SYNC: When modified, update /packages/core/src/keyboard/README.md+ */++import {subscribeInput} from '../utils/inputStream';+import {layoutViewportHeight} from '../utils/layoutViewport';++// A shortfall smaller than this is rounding, not a keyboard.+export const KEYBOARD_EPSILON = 1;+const NON_TEXT_INPUT_TYPES = new Set([+ 'button',+ 'checkbox',+ 'color',+ 'file',+ 'hidden',+ 'image',+ 'radio',+ 'range',+ 'reset',+ 'submit',+]);++/**+ * Whether this window measures the keyboard: a top-level document with a+ * visual viewport. Capabilities decide it, never the user agent or the+ * pointer. The module measures a browser with its own keyboard geometry API,+ * such as Chrome on Android with the VirtualKeyboard API, the same way.+ * Its visual viewport shrinks for the keyboard while the layout viewport keeps+ * its height, as everywhere else. A desktop browser's visual viewport never+ * shrinks for a keyboard, so it reads 0. Where the app sets+ * `interactive-widget=resizes-content`, Chrome shrinks the layout viewport+ * with the keyboard. The height is then 0 too, and nothing rides, because the+ * browser has made the room itself.+ */+export function isKeyboardMeasurable(win: Window): boolean {+ return win.visualViewport != null && win.self === win.top;+}++/**+ * The on-screen keyboard's height over the layout viewport, CSS px. It is 0+ * when none is shown, also while pinch-zoomed, and wherever+ * `isKeyboardMeasurable` is false.+ */+export function measureKeyboardHeight(win: Window): number {+ const viewport = win.visualViewport;+ if (viewport == null || !isKeyboardMeasurable(win)) {+ return 0;+ }+ const height =+ layoutViewportHeight(win) - viewport.height * (viewport.scale ?? 1);+ return height > KEYBOARD_EPSILON ? Math.round(height * 100) / 100 : 0;+}++/** A report from the keyboard module, in the order the window raised them. */+export type KeyboardHeightEvent =+ | {+ /** The visual viewport or the window changed size or position. */+ type: 'viewport';+ /** The keyboard height after this report. */+ height: number;+ /** The report's event time (the document timeline). */+ timeStamp: number;+ }+ | {+ /** Focus moved into (`focusin`) or out of (`focusout`) `target`. */+ type: 'focusin' | 'focusout';+ height: number;+ timeStamp: number;+ target: EventTarget | null;+ relatedTarget: EventTarget | null;+ };++interface KeyboardStore {+ height: number;+ listeners: Set<(event: KeyboardHeightEvent) => void>;+ /** The subscribers that asked for focus moves too (the layout guide). */+ focusListeners: Set<(event: KeyboardHeightEvent) => void>;+ detach: (() => void) | null;+ detachFocus: (() => void) | null;+}++const stores = new WeakMap<Window, KeyboardStore>();++// A window's capture phase also hears its document's events. A window's own+// event has no node as its target.+export function isNodeTarget(target: EventTarget | null): boolean {+ return target != null && typeof (target as Node).nodeType === 'number';+}++function storeOf(win: Window): KeyboardStore {+ let store = stores.get(win);+ if (store == null) {+ store = {+ height: 0,+ listeners: new Set(),+ focusListeners: new Set(),+ detach: null,+ detachFocus: null,+ };+ stores.set(win, store);+ }+ return store;+}++function attach(win: Window, store: KeyboardStore): () => void {+ const viewport = win.visualViewport;+ store.height = measureKeyboardHeight(win);+ const onViewport = (event: Event) => {+ store.height = measureKeyboardHeight(win);+ const report: KeyboardHeightEvent = {+ type: 'viewport',+ height: store.height,+ timeStamp: event.timeStamp,+ };+ for (const listener of [...store.listeners]) {+ listener(report);+ }+ };+ viewport?.addEventListener('resize', onViewport);+ viewport?.addEventListener('scroll', onViewport);+ // Only the window's own resize reports.+ const stopResize = subscribeInput(win, 'resize', event => {+ if (!isNodeTarget(event.target)) {+ onViewport(event);+ }+ });+ return () => {+ viewport?.removeEventListener('resize', onViewport);+ viewport?.removeEventListener('scroll', onViewport);+ stopResize();+ };+}++// Focus moves are heard only while a subscriber asks for them. A viewport+// reader, such as a Tall BottomSheet's hook under any pointer, adds no focus+// listener.+function attachFocus(win: Window, store: KeyboardStore): () => void {+ const onFocus = (event: FocusEvent) => {+ const report: KeyboardHeightEvent = {+ type: event.type === 'focusin' ? 'focusin' : 'focusout',+ height: store.height,+ timeStamp: event.timeStamp,+ target: event.target,+ relatedTarget: event.relatedTarget,+ };+ for (const listener of [...store.focusListeners]) {+ listener(report);+ }+ };+ const stopFocusIn = subscribeInput(win, 'focusin', onFocus);+ const stopFocusOut = subscribeInput(win, 'focusout', onFocus);+ return () => {+ stopFocusIn();+ stopFocusOut();+ };+}++/**+ * Calls `listener` with every report of `win`'s keyboard until the caller+ * runs the returned function. It reports the viewport's changes, and focus+ * moves too when the caller sets `focus`. All subscribers of a window share+ * one set of listeners, and its focus listeners exist only while a subscriber+ * asks for focus moves.+ *+ * @example+ * ```+ * const stop = subscribeKeyboardHeight(window, event => {+ * if (event.type === 'viewport') layout(event.height);+ * });+ * ```+ */+export function subscribeKeyboardHeight(+ win: Window,+ listener: (event: KeyboardHeightEvent) => void,+ {focus = false}: {focus?: boolean} = {},+): () => void {+ const store = storeOf(win);+ store.listeners.add(listener);+ if (store.detach == null) {+ store.detach = attach(win, store);+ }+ if (focus) {+ store.focusListeners.add(listener);+ if (store.detachFocus == null) {+ store.detachFocus = attachFocus(win, store);+ }+ }+ return () => {+ store.listeners.delete(listener);+ if (focus) {+ store.focusListeners.delete(listener);+ if (store.focusListeners.size === 0 && store.detachFocus != null) {+ store.detachFocus();+ store.detachFocus = null;+ }+ }+ if (store.listeners.size === 0 && store.detach != null) {+ store.detach();+ store.detach = null;+ }+ };+}++/**+ * `win`'s keyboard height. While the module listens, it is the height+ * measured at the last report. Every reader of a keyboard change, such as+ * each component's hook, shares that one layout read. Every change of the+ * visual viewport or the window is a report, so a reader between two reports+ * sees the current height. With nothing listening yet, the call measures the+ * height now.+ */+export function getKeyboardHeight(win: Window): number {+ const store = stores.get(win);+ return store?.detach != null ? store.height : measureKeyboardHeight(win);+}++/**+ * Whether focusing `element` brings up a keyboard for typing text. A control+ * with `inputmode="none"` brings up none.+ */+export function isTextEntryControl(+ element: Element | null,+): element is HTMLElement {+ if (+ element instanceof HTMLElement &&+ element.getAttribute('inputmode') === 'none'+ ) {+ return false;+ }+ if (element instanceof HTMLTextAreaElement) {+ return !element.disabled && !element.readOnly;+ }+ if (element instanceof HTMLInputElement) {+ return (+ !element.disabled &&+ !element.readOnly &&+ !NON_TEXT_INPUT_TYPES.has(+ (element.getAttribute('type') ?? 'text').toLowerCase(),+ )+ );+ }+ return (+ element instanceof HTMLElement &&+ element.matches('[contenteditable]:not([contenteditable="false"])')+ );+}++/** The text-entry control inside `container` that `target` is or labels. */+export function findTextEntryControl(+ target: EventTarget | null,+ container: HTMLElement,+): HTMLElement | null {+ if (!(target instanceof Element)) {+ return null;+ }++ const direct = target.closest(+ 'input, textarea, [contenteditable]:not([contenteditable="false"])',+ );+ if (container.contains(direct) && isTextEntryControl(direct)) {+ return direct;+ }++ const label = target.closest('label');+ const control = label instanceof HTMLLabelElement ? label.control : null;+ return container.contains(control) && isTextEntryControl(control)+ ? control+ : null;+}++/** The caller's rules for refuseFocusReveal. */+export interface RefuseFocusRevealOptions {+ /** Whether to claim at all just now, checked on every blur. */+ isActive?: () => boolean;+ /** The control a focus move is heading to, when this caller claims it. */+ claim: (destination: EventTarget | null) => HTMLElement | null;+ /** Focus left `origin` for nothing (the keyboard's Done): park it, if at all. */+ park?: (origin: EventTarget | null) => void;+}++// One shared `blur` subscription per document serves every caller of+// refuseFocusReveal in it, so listeners do not grow with the number of+// instances. The first caller adds it, and the last removes it.+const focusTakeovers = new WeakMap<+ Document,+ {+ stop: () => void;+ callers: Set<(event: FocusEvent) => void>;+ }+>();++/**+ * Delivers the focus moves `claim` accepts with `preventScroll`, so the+ * browser never reveals their destination itself. It stops when the caller+ * runs the returned function.+ *+ * The browser dispatches `blur` in the capture phase ahead of its own focus+ * step, and `blur` names the destination in `relatedTarget`. Focusing it there+ * with preventScroll settles the change. The browser's step then finds the+ * element already active, so it dispatches nothing further and reveals+ * nothing.+ *+ * @example+ * ```+ * const stop = refuseFocusReveal(document, {+ * claim: target => findTextEntryControl(target, body),+ * park: () => sheet.focus({preventScroll: true}),+ * });+ * ```+ */+export function refuseFocusReveal(+ doc: Document,+ {isActive, claim, park}: RefuseFocusRevealOptions,+): () => void {+ const onBlur = (event: FocusEvent) => {+ if (isActive != null && !isActive()) {+ return;+ }+ const destination = claim(event.relatedTarget);+ if (destination != null) {+ if (destination !== doc.activeElement) {+ destination.focus({preventScroll: true});+ }+ return;+ }+ if (event.relatedTarget == null) {+ park?.(event.target);+ }+ };+ let shared = focusTakeovers.get(doc);+ if (shared == null) {+ const view = doc.defaultView;+ if (view == null) {+ return () => {};+ }+ const callers = new Set<(event: FocusEvent) => void>();+ // Callers hear each blur in the order they came, as separate listeners+ // would; one that stopped during this blur no longer hears it.+ const listener = (event: FocusEvent) => {+ for (const caller of [...callers]) {+ if (callers.has(caller)) {+ caller(event);+ }+ }+ };+ // `blur` does not bubble: only the capture phase hears every one, and it+ // runs before the browser's own focus step. The window's own blur moves+ // no focus inside the document.+ const stop = subscribeInput(view, 'blur', event => {+ if (isNodeTarget(event.target)) {+ listener(event);+ }+ });+ shared = {stop, callers};+ focusTakeovers.set(doc, shared);+ }+ shared.callers.add(onBlur);+ return () => {+ const current = focusTakeovers.get(doc);+ if (current == null || !current.callers.delete(onBlur)) {+ return;+ }+ if (current.callers.size === 0) {+ current.stop();+ focusTakeovers.delete(doc);+ }+ };+}++/**+ * Test-only: how many callers refuse the focus reveal in `doc`, through its+ * one shared subscription. Not part of the runtime API.+ *+ * @internal+ */+export function __focusTakeoverCallersForTest(doc: Document): number {+ return focusTakeovers.get(doc)?.callers.size ?? 0;+}++/** The caller's rules for watchRevealPan. */+export interface WatchRevealPanOptions {+ /** Whether the focused field is the caller's to keep in view. */+ owns: (focused: HTMLElement) => boolean;+ /** Called on every touch start, which ends the watch for the report. */+ onTouch?: () => void;+}++/** A watch for the browser's own reveal pan (see watchRevealPan). */+export interface RevealPanWatch {+ /** A report changed the keyboard's height: remember where everything sat. */+ report: () => void;+ /** Whether the visual viewport has since moved down as a reveal pan. */+ isRevealPan: (height: number) => boolean;+ /**+ * Pans the visual viewport back to where it sat at the report, without+ * scrolling the document. It scrolls `anchor` into view, an element fixed at+ * the layout viewport's top, or else a probe fixed where the viewport sat.+ */+ putBack: (anchor?: Element | null) => void;+ /** Ends the watch; the shared touch subscription goes with the last watch. */+ stop: () => void;+}++// One shared touch subscription per document serves every reveal-pan watch+// in it, so no instance adds a listener. The first watch adds it, and the+// last removes it.+const touchStartWatches = new WeakMap<+ Document,+ {stop: () => void; watches: Set<() => void>}+>();++function watchTouchStarts(doc: Document, onTouchStart: () => void): () => void {+ let shared = touchStartWatches.get(doc);+ if (shared == null) {+ const view = doc.defaultView;+ if (view == null) {+ return () => {};+ }+ const watches = new Set<() => void>();+ const stop = subscribeInput(view, 'touchstart', () => {+ for (const watch of [...watches]) {+ watch();+ }+ });+ shared = {stop, watches};+ touchStartWatches.set(doc, shared);+ }+ shared.watches.add(onTouchStart);+ return () => {+ const current = touchStartWatches.get(doc);+ if (current == null || !current.watches.delete(onTouchStart)) {+ return;+ }+ if (current.watches.size === 0) {+ current.stop();+ touchStartWatches.delete(doc);+ }+ };+}++/**+ * Some browsers reveal a focused field themselves, after the keyboard's+ * report, by panning the visual viewport to it while the keyboard still+ * covers it. Firefox for Android pans 54 to 143 ms after the report. Chrome+ * on Android animates a pan of the keyboard's whole height from about 100 to+ * 170 ms after it. The page gets no frame until that pan ends. Such a pan+ * moves the visual viewport down within the+ * layout viewport. Since the report there is no touch, document scroll or+ * zoom, and a text field the caller owns has focus. The watch reads the+ * behavior, never the user agent. The caller lands its field itself and+ * puts the pan back. Every keyboard-aware surface can use it.+ *+ * @example+ * ```+ * const watch = watchRevealPan(window, {owns: field => region.contains(field)});+ * // On a report that changes the height: watch.report();+ * // On any later report: if (watch.isRevealPan(height)) watch.putBack();+ * ```+ */+export function watchRevealPan(+ win: Window,+ {owns, onTouch}: WatchRevealPanOptions,+): RevealPanWatch {+ const doc = win.document;+ let atReport: {x: number; y: number; top: number; scale: number} | null =+ null;+ let touchedSinceReport = false;+ const stopTouchStarts = watchTouchStarts(doc, () => {+ touchedSinceReport = true;+ onTouch?.();+ });+ return {+ report: () => {+ const viewport = win.visualViewport;+ atReport =+ viewport == null+ ? null+ : {+ x: win.scrollX,+ y: win.scrollY,+ top: viewport.offsetTop,+ scale: viewport.scale,+ };+ touchedSinceReport = false;+ },+ isRevealPan: height => {+ const viewport = win.visualViewport;+ const focused = doc.activeElement;+ return (+ viewport != null &&+ atReport != null &&+ !touchedSinceReport &&+ height > 0 &&+ viewport.offsetTop > atReport.top &&+ viewport.scale === atReport.scale &&+ win.scrollX === atReport.x &&+ win.scrollY === atReport.y &&+ focused instanceof HTMLElement &&+ isTextEntryControl(focused) &&+ owns(focused)+ );+ },+ putBack: anchor => {+ const options: ScrollIntoViewOptions = {+ block: 'start',+ inline: 'nearest',+ behavior: 'instant',+ };+ if (anchor != null) {+ anchor.scrollIntoView(options);+ return;+ }+ // A fixed element sits in the layout viewport, which the pan does not+ // move: scrolling its top into view pans the visual viewport back.+ const probe = doc.createElement('div');+ probe.style.position = 'fixed';+ probe.style.left = '0';+ probe.style.top = `${atReport?.top ?? 0}px`;+ probe.style.width = '1px';+ probe.style.height = '1px';+ probe.style.visibility = 'hidden';+ probe.style.pointerEvents = 'none';+ (doc.body ?? doc.documentElement).append(probe);+ probe.scrollIntoView(options);+ probe.remove();+ },+ stop: stopTouchStarts,+ };+}diff --git a/packages/core/src/keyboard/keyboardLayoutGuide.ts b/packages/core/src/keyboard/keyboardLayoutGuide.tsnew file mode 100644index 0000000000..5bcd168a62--- /dev/null+++ b/packages/core/src/keyboard/keyboardLayoutGuide.ts@@ -0,0 +1,266 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardLayoutGuide.ts+ * @input The keyboard module's reports (subscribeKeyboardHeight) and+ * createKeyboardModel+ * @output getKeyboardLayoutGuide (a window's one guide), bringsUpKeyboard and+ * the KeyboardLayoutGuide type+ * @position The web's UIKeyboardLayoutGuide: where the software keyboard+ * covers the layout viewport and how it moves. Touch presentations read it+ * to keep content above the keyboard. It is internal to core.+ *+ * SYNC: When modified, update /packages/core/src/keyboard/README.md+ */++import {+ getKeyboardHeight,+ isTextEntryControl,+ subscribeKeyboardHeight,+ type KeyboardHeightEvent,+} from './keyboardHeight';+import {+ createKeyboardModel,+ type KeyboardModel,+ type KeyboardProfile,+ type KeyboardTransition,+} from './keyboardModel';++/**+ * Whose keyboard schedule the guide reads: `chromium` where the browser has+ * the VirtualKeyboard API, else null. Without the profile, no surface rides+ * the guide. Chrome reports the keyboard as each slide starts. The profile is+ * a capability, never the user agent. motion/android/keyboard.ts holds the+ * measured timing.+ */+export function keyboardProfileOf(win: Window): KeyboardProfile | null {+ return 'virtualKeyboard' in win.navigator ? 'chromium' : null;+}++/** A window's keyboard layout guide. */+export interface KeyboardLayoutGuide {+ /** The inset the keyboard rests at (or is heading to), CSS px. */+ readonly inset: number;+ /** The latest transition. */+ readonly transition: KeyboardTransition;+ /** The inset presented at `time` (default now), CSS px. */+ presentation(time?: number): number;+ /**+ * Calls `listener` with every transition, inside the event that revealed+ * it, until the caller runs the returned function.+ */+ subscribe(listener: (transition: KeyboardTransition) => void): () => void;+ /** Whose keyboard schedule the guide reads (keyboardProfileOf). */+ readonly profile: KeyboardProfile | null;+}++// Extra time after a predicted transition's end before checking it.+const VERIFY_SLACK_MS = 150;+// How long after a field gains focus Chrome may still report the keyboard+// gone for a moment (measured: back within 50 ms of the move).+const FOCUS_HANDOFF_MS = 150;++// Controls whose picker Chrome on Android opens over the page while the+// keyboard goes away; on iOS the picker takes the keyboard's place.+const PICKER_INPUT_TYPES = new Set([+ 'date',+ 'datetime-local',+ 'month',+ 'time',+ 'week',+]);++/**+ * Whether focusing `target` brings up a software keyboard (or another input+ * view in its place, as a select's picker does).+ */+export function bringsUpKeyboard(target: EventTarget | null): boolean {+ const element = target instanceof Element ? target : null;+ return (+ isTextEntryControl(element) ||+ (element instanceof HTMLSelectElement && !element.disabled)+ );+}++// Whether `target` is a select, or a date or time field, which Chrome on+// Android edits in a picker over the page.+function opensPickerOverPage(target: EventTarget | null): boolean {+ const element = target as HTMLElement | null;+ if (element == null || element.nodeType !== 1) {+ return false;+ }+ return (+ element.tagName === 'SELECT' ||+ (element.tagName === 'INPUT' &&+ PICKER_INPUT_TYPES.has((element as HTMLInputElement).type))+ );+}++const guides = new WeakMap<Window, KeyboardLayoutGuide>();++/**+ * The window's keyboard layout guide, created on first use.+ *+ * One guide serves each window. It subscribes to the keyboard module only+ * while something subscribes to it. It owns no listener and measures nothing.+ * It feeds the model the module's reports, the keyboard height and the focus+ * changes that start a hide. It hands each transition to its subscribers.+ * What it adds is timing: when a show started, a hide predicted from the+ * blur, and the motion in between. Layout follows the keyboard height+ * itself, and the guide's transitions only time the optional ride on top.+ *+ * The model reads Chrome's measured schedule: Chrome reports each slide just+ * after it starts. A surface rides the guide only where the VirtualKeyboard+ * API reports the keyboard. Focus can move from one field to another through+ * something that brings no keyboard, such as a popover's container. Chrome+ * then reports the keyboard gone for a moment and then back. So a hide+ * reported while a field that just got focus still has it waits until the+ * move settles.+ *+ * @example+ * ```+ * const guide = getKeyboardLayoutGuide(window);+ * const unsubscribe = guide.subscribe(t => {+ * rideKeyboard(animator, {y: -t.to}, t);+ * });+ * ```+ */+export function getKeyboardLayoutGuide(win: Window): KeyboardLayoutGuide {+ let guide = guides.get(win);+ if (guide == null) {+ guide = createGuide(win);+ guides.set(win, guide);+ }+ return guide;+}++function createGuide(win: Window): KeyboardLayoutGuide {+ const listeners = new Set<(transition: KeyboardTransition) => void>();+ let profile = keyboardProfileOf(win);+ let model: KeyboardModel = createKeyboardModel(getKeyboardHeight(win));+ let verifyTimer: ReturnType<typeof setTimeout> | null = null;+ let detach: (() => void) | null = null;++ const publish = (transition: KeyboardTransition | null) => {+ if (transition == null) {+ return;+ }+ if (transition.predicted) {+ scheduleVerify(transition);+ }+ for (const listener of [...listeners]) {+ listener(transition);+ }+ };+ const scheduleVerify = (transition: KeyboardTransition) => {+ if (verifyTimer != null) {+ clearTimeout(verifyTimer);+ }+ const due =+ transition.start + (transition.curve?.durationMs ?? 0) + VERIFY_SLACK_MS;+ verifyTimer = setTimeout(+ () => {+ verifyTimer = null;+ publish(model.verify(getKeyboardHeight(win), win.performance.now()));+ },+ Math.max(0, due - win.performance.now()),+ );+ };++ 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;+ const report = (+ height: number,+ time: number,+ ): KeyboardTransition | null => {+ if (handoffTimer != null) {+ clearTimeout(handoffTimer);+ handoffTimer = null;+ }+ const settled = keyboardFocusAt + FOCUS_HANDOFF_MS;+ if (+ profile === 'chromium' &&+ height < 0.5 &&+ model.inset >= 0.5 &&+ time < settled &&+ keepsInputView(win.document.activeElement)+ ) {+ // Focus just moved to another field: Chrome reports the keyboard+ // gone before it reports it back. Hold the hide until the move+ // settles, then believe whatever the keyboard is doing.+ handoffTimer = setTimeout(() => {+ handoffTimer = null;+ publish(model.report(getKeyboardHeight(win), settled));+ }, settled - time);+ return null;+ }+ return model.report(height, time);+ };+ const onReport = (event: KeyboardHeightEvent) => {+ if (event.type === 'viewport') {+ publish(report(event.height, event.timeStamp));+ } else if (event.type === 'focusin') {+ if (keepsInputView(event.target)) {+ keyboardFocusAt = event.timeStamp;+ publish(model.focused(event.timeStamp));+ }+ } else if (+ keepsInputView(event.target) &&+ !keepsInputView(event.relatedTarget)+ ) {+ publish(model.blurred(event.timeStamp));+ }+ };+ const unsubscribe = subscribeKeyboardHeight(win, onReport, {focus: true});+ return () => {+ unsubscribe();+ if (handoffTimer != null) {+ clearTimeout(handoffTimer);+ handoffTimer = null;+ }+ if (verifyTimer != null) {+ clearTimeout(verifyTimer);+ verifyTimer = null;+ }+ };+ };++ return {+ get profile() {+ return profile;+ },+ get inset() {+ return model.inset;+ },+ get transition() {+ return model.transition;+ },+ presentation(time = win.performance.now()) {+ return model.presentation(time);+ },+ subscribe(listener) {+ listeners.add(listener);+ if (detach == null) {+ detach = attach();+ }+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0 && detach != null) {+ detach();+ detach = null;+ }+ };+ },+ };+}diff --git a/packages/core/src/keyboard/keyboardModel.test.ts b/packages/core/src/keyboard/keyboardModel.test.tsnew file mode 100644index 0000000000..d6b437227c--- /dev/null+++ b/packages/core/src/keyboard/keyboardModel.test.ts@@ -0,0 +1,102 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardModel.test.ts+ * @input vitest, createKeyboardModel, the Android keyboard table+ * @output Tests the keyboard layout guide's core on Chrome. Transitions come+ * from Chrome's reports, dated back to Gboard's start, on Gboard's slides.+ * Also covered: a hide predicted from the blur, the accessory bar's+ * report, and focus that comes back during a predicted hide.+ * @position Unit tests for keyboard/keyboardModel.ts+ */++import {describe, expect, it} from 'vitest';+import {createKeyboardModel} from './keyboardModel';+import {keyboard as androidKeyboard} from '../motion/android';+import {cubicBezier} from '../motion/bezier';++describe('createKeyboardModel on Chrome', () => {+ const ease = cubicBezier(androidKeyboard.hideCurve);+ const chrome = () => createKeyboardModel(0);++ it('rides a keyboard coming up from its report, dated back to Gboard’s start, on Gboard’s slide (FR8)', () => {+ const model = chrome();+ const show = model.report(312, 1000);+ const start = 1000 - androidKeyboard.showReportLagMs;+ expect(show).toMatchObject({+ kind: 'show',+ from: 0,+ to: 312,+ start,+ animated: true,+ curve: {+ durationMs: androidKeyboard.showMs,+ points: androidKeyboard.showCurve,+ },+ });+ // Joined where the slide is at the report, then on Gboard's curve.+ const easeUp = cubicBezier(androidKeyboard.showCurve);+ expect(model.presentation(1000)).toBeCloseTo(+ 312 * easeUp(androidKeyboard.showReportLagMs / androidKeyboard.showMs),+ 6,+ );+ expect(model.presentation(start + androidKeyboard.showMs)).toBe(312);+ });++ it('rides to the last keyboard’s height for the accessory bar’s report, then confirms it', () => {+ const model = chrome();+ model.report(312, 1000);+ model.report(0, 2000);+ const show = model.report(48, 3000);+ expect(show).toMatchObject({to: 312, animated: true, predicted: true});+ expect(model.report(312, 3120)).toBeNull();+ expect(model.transition.predicted).toBe(false);+ });++ it('moves once if the keyboard that comes is not the last one', () => {+ const model = chrome();+ model.report(312, 1000);+ model.report(0, 2000);+ model.report(48, 3000);+ const change = model.report(260, 3120);+ expect(change).toMatchObject({kind: 'change', to: 260, animated: false});+ });++ it('rides a hide down from hideAfterBlurMs after a blur, on the hide curve', () => {+ const model = chrome();+ model.report(312, 1000);+ const hide = model.blurred(2000);+ const start = 2000 + androidKeyboard.hideAfterBlurMs;+ expect(hide).toMatchObject({kind: 'hide', to: 0, start, predicted: true});+ expect(hide?.curve?.durationMs).toBe(androidKeyboard.hideMs);+ const half = androidKeyboard.hideMs / 2;+ expect(model.presentation(start + half)).toBeCloseTo(+ 312 * (1 - ease(0.5)),+ 6,+ );+ expect(model.presentation(start + androidKeyboard.hideMs)).toBe(0);+ // Chrome's report confirms the prediction.+ expect(model.report(0, start + 2)).toBeNull();+ });++ it('rides a hide nothing predicted (Back) down from its report, dated back to Gboard’s start', () => {+ const model = chrome();+ model.report(312, 1000);+ const hide = model.report(0, 2010);+ expect(hide).toMatchObject({+ kind: 'hide',+ to: 0,+ start: 2010 - androidKeyboard.hideReportLagMs,+ animated: true,+ });+ });++ it('turns back up on Gboard’s slide when focus returns during a predicted hide', () => {+ const model = chrome();+ model.report(312, 1000);+ model.blurred(2000);+ const back = model.focused(2060);+ expect(back).toMatchObject({kind: 'show', to: 312, animated: true});+ expect(back?.curve?.durationMs).toBe(androidKeyboard.showMs);+ });+});diff --git a/packages/core/src/keyboard/keyboardModel.ts b/packages/core/src/keyboard/keyboardModel.tsnew file mode 100644index 0000000000..9e411170dd--- /dev/null+++ b/packages/core/src/keyboard/keyboardModel.ts@@ -0,0 +1,301 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboardModel.ts+ * @input `keyboard` from the Android table: Gboard's slides and Chrome's+ * report timings+ * @output createKeyboardModel, the keyboard layout guide's clock-free core,+ * and the KeyboardTransition and KeyboardModel types+ * @position The state of the keyboard layout guide (keyboardLayoutGuide.ts).+ * It infers the keyboard's transition from the visual viewport's reports+ * and focus changes, each input with its own time. It is internal to core.+ *+ * SYNC: When modified, update /packages/core/src/keyboard/README.md+ */++import {keyboard as androidKeyboard} from '../motion/android/keyboard';+import {cubicBezier} from '../motion/bezier';++/** Which browser's keyboard reports the guide reads. */+export type KeyboardProfile = 'chromium';++/** An eased slide: the curve a transition plays (Gboard going up or down). */+export interface KeyboardCurve {+ /** Length, ms. */+ readonly durationMs: number;+ /** Cubic-bézier control points. */+ readonly points: readonly [number, number, number, number];+}++/** How the keyboard's cover changes. */+export type KeyboardTransitionKind = 'show' | 'hide' | 'change';++/** One change of the keyboard's cover, as the guide reports it. */+export interface KeyboardTransition {+ readonly kind: KeyboardTransitionKind;+ /** Inset presented at `start`, CSS px. */+ readonly from: number;+ /** Inset the keyboard comes to rest at, CSS px. */+ readonly to: number;+ /**+ * When the keyboard starts to move, ms on the document timeline+ * (`performance.now()`). For a slide Chrome reported, the guide dates it+ * back to Gboard's start. For a hide after a blur, it is shortly ahead.+ */+ readonly start: number;+ /** The inset's velocity at `start`, px/s (0 unless it interrupts one). */+ readonly velocity: number;+ /** False when the inset jumps at `start` (another keyboard while one is up). */+ readonly animated: boolean;+ /** True until the visual viewport confirms a transition the guide inferred. */+ readonly predicted: boolean;+ /**+ * The eased slide the keyboard moves on (Gboard in Chrome on Android), or+ * null when the inset jumps. A surface riding the keyboard plays it from+ * `start`, as rideKeyboard does. It is the keyboard's own motion, with no+ * motion role.+ */+ readonly curve: KeyboardCurve | null;+}++/** The guide's clock-free core: inputs carry their own times. */+export interface KeyboardModel {+ /** The inset the keyboard rests at (or is heading to), CSS px. */+ readonly inset: number;+ /** The latest transition. */+ readonly transition: KeyboardTransition;+ /** The inset presented at `time`, CSS px. */+ presentation(time: number): number;+ /** The presented inset's velocity at `time`, px/s. */+ velocity(time: number): number;+ /**+ * The visual viewport reports an inset (null when unknown) at `time` (the+ * event's timestamp). Returns the transition the report starts, if any.+ */+ report(inset: number | null, time: number): KeyboardTransition | null;+ /**+ * A control that brings up a keyboard lost focus to nothing that brings+ * up one.+ */+ blurred(time: number): KeyboardTransition | null;+ /** A control that brings up a keyboard gained focus. */+ focused(time: number): KeyboardTransition | null;+ /**+ * Checks a predicted transition against the viewport once it should have+ * ended; moves to what the viewport says when they disagree.+ */+ verify(inset: number | null, time: number): KeyboardTransition | null;+}++const EPSILON = 0.5;++/** The inset and its velocity, seconds after a transition's start. */+interface InsetCurve {+ value(t: number): number;+ velocity(t: number): number;+}++/**+ * Creates the guide's core. Tests drive it with explicit times, and the+ * window's guide feeds it events.+ *+ * Chrome reports each keyboard slide through the visual viewport just after+ * it starts (README.md, "What the page sees"). Content rides Gboard's own+ * slides, fitted on Chromium 158 with Gboard (motion/android/keyboard.ts).+ *+ * - Show: from the report, dated back `androidKeyboard.showReportLagMs`, on+ * `showCurve` over `showMs`, joining the slide where it is. The report's+ * first painted frame trails Gboard's first moved frame by 14 to 35 ms. An+ * `<input>` that brings an accessory bar first gives a smaller report+ * before the keyboard's. It rides to the last keyboard's height instead, as+ * a prediction, and the keyboard's report confirms it.+ * - Hide: on `hideCurve` over `hideMs`. It starts+ * `androidKeyboard.hideAfterBlurMs` after a blur that brings no keyboard,+ * as a prediction, because Gboard starts down at the blur. When nothing+ * predicted it, as with Back, it starts from Chrome's report, dated back+ * `hideReportLagMs`, the lag measured on blurs.+ * - A keyboard that changes while up, such as another keyboard, lays out at+ * once.+ *+ * A prediction the viewport has not confirmed by its end gives way to what+ * the viewport says (`verify`).+ */+export function createKeyboardModel(initialInset = 0): KeyboardModel {+ let transition: KeyboardTransition = {+ kind: 'change',+ from: initialInset,+ to: initialInset,+ start: -Infinity,+ velocity: 0,+ animated: false,+ predicted: false,+ curve: null,+ };+ // The inset over seconds since the transition's start.+ let curve: InsetCurve | null = null;+ // An eased slide's value and velocity.+ const easedCurve = (+ from: number,+ to: number,+ slide: KeyboardCurve,+ ): InsetCurve => {+ const span = slide.durationMs / 1000;+ const ease = cubicBezier(slide.points);+ const value = (t: number) =>+ from + (to - from) * ease(Math.min(1, Math.max(0, t / span)));+ return {+ value,+ velocity: (t: number) => {+ if (t >= span) {+ return 0;+ }+ const a = Math.max(0, t - 0.001);+ const b = Math.min(span, t + 0.001);+ return (value(b) - value(a)) / (b - a);+ },+ };+ };+ // Gboard's slides, as Chrome draws them: the table's show and hide curves.+ const showSlide: KeyboardCurve = {+ durationMs: androidKeyboard.showMs,+ points: androidKeyboard.showCurve,+ };+ const hideSlide: KeyboardCurve = {+ durationMs: androidKeyboard.hideMs,+ points: androidKeyboard.hideCurve,+ };+ // How long the current transition moves for.+ const lengthOf = () =>+ transition.curve != null ? transition.curve.durationMs : 0;+ // The inset of the last keyboard that was up, for a hide that turns back.+ let shownInset = initialInset;++ const presentation = (time: number): number => {+ // A jump has happened at its start; a curve starts from `from`.+ if (time < transition.start) {+ return transition.from;+ }+ if (curve == null || time >= transition.start + lengthOf()) {+ return transition.to;+ }+ return curve.value((time - transition.start) / 1000);+ };+ const velocity = (time: number): number => {+ if (time <= transition.start) {+ return transition.velocity;+ }+ if (curve == null || time >= transition.start + lengthOf()) {+ return 0;+ }+ return curve.velocity((time - transition.start) / 1000);+ };++ const begin = (+ kind: KeyboardTransitionKind,+ to: number,+ start: number,+ {animated = true, predicted = false} = {},+ ): KeyboardTransition => {+ // Never date a transition before the one it interrupts.+ const at = Math.max(start, transition.start);+ const from = presentation(at);+ const v = animated ? velocity(at) : 0;+ const slide = animated ? (to > from ? showSlide : hideSlide) : null;+ transition = {+ kind,+ from,+ to,+ start: at,+ velocity: v,+ animated,+ predicted,+ curve: slide,+ };+ curve =+ slide != null && Math.abs(to - from) + Math.abs(v) > 0+ ? easedCurve(from, to, slide)+ : null;+ if (to > EPSILON) {+ shownInset = to;+ }+ return transition;+ };+ const confirm = (): null => {+ if (transition.predicted) {+ transition = {...transition, predicted: false};+ }+ return null;+ };++ return {+ get inset() {+ return transition.to;+ },+ get transition() {+ return transition;+ },+ presentation,+ velocity,+ report(inset, time) {+ if (inset == null) {+ return null;+ }+ const target = transition.to;+ if (Math.abs(inset - target) < EPSILON) {+ return confirm();+ }+ if (inset <= EPSILON) {+ // A hide nothing predicted (Back): Chrome reports it just after+ // Gboard starts down, so it rides from that moment.+ return begin('hide', 0, time - androidKeyboard.hideReportLagMs);+ }+ if (target <= EPSILON) {+ // Chrome reports the show just after Gboard starts up: ride from+ // that moment, joining the slide where it is. A smaller first+ // report is the accessory bar, the keyboard's own following: ride+ // to the last keyboard's height and let its report confirm it.+ const predicted = shownInset > inset + EPSILON;+ return begin(+ 'show',+ predicted ? shownInset : inset,+ time - androidKeyboard.showReportLagMs,+ {predicted},+ );+ }+ // The keyboard changed while up (another keyboard, or the keyboard's+ // report after the accessory bar's): Chrome lays the page out at once.+ return begin('change', inset, time, {animated: false});+ },+ blurred(time) {+ if (transition.to <= EPSILON) {+ return null;+ }+ return begin('hide', 0, time + androidKeyboard.hideAfterBlurMs, {+ predicted: true,+ });+ },+ focused(time) {+ if (transition.kind !== 'hide' || !transition.predicted) {+ return null;+ }+ // Focus came back before the predicted hide finished: the keyboard+ // turns back to the inset it had.+ return begin('show', shownInset, Math.max(time, transition.start), {+ predicted: true,+ });+ },+ verify(inset, time) {+ if (+ !transition.predicted ||+ inset == null ||+ time < transition.start + lengthOf()+ ) {+ return null;+ }+ if (Math.abs(inset - transition.to) < EPSILON) {+ return confirm();+ }+ return begin(inset > transition.to ? 'show' : 'hide', inset, time);+ },+ };+}diff --git a/packages/core/src/keyboard/rideKeyboard.test.ts b/packages/core/src/keyboard/rideKeyboard.test.tsnew file mode 100644index 0000000000..4bafafa0fe--- /dev/null+++ b/packages/core/src/keyboard/rideKeyboard.test.ts@@ -0,0 +1,156 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file rideKeyboard.test.ts+ * @input vitest, rideKeyboard, a stand-in animator+ * @output Tests that a ride plays its transition's curve from the+ * transition's start and asks for an entrance. A jump or an ended slide+ * lands at once.+ * @position Unit tests for keyboard/rideKeyboard.ts+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import type {Animator} from '../motion/animator';+import {keyboard as androidKeyboard} from '../motion/android';+import type {KeyboardTransition} from './keyboardModel';+import {rideKeyboard} from './rideKeyboard';++function standInAnimator() {+ const handle = {finished: Promise.resolve(true)};+ return {+ animate: vi.fn(() => handle),+ play: vi.fn(() => handle),+ set: vi.fn(),+ get: vi.fn(() => 0),+ };+}++const transition = (+ overrides: Partial<KeyboardTransition>,+): KeyboardTransition => ({+ kind: 'show',+ from: 0,+ to: 300,+ start: 1000,+ velocity: 0,+ animated: true,+ predicted: false,+ curve: null,+ ...overrides,+});++describe('rideKeyboard', () => {+ // The transitions start at 1000 ms, and a ride called after its slide has+ // ended lands at once. So the clock reads the slide's start unless a case+ // sets it.+ beforeEach(() => {+ vi.spyOn(performance, 'now').mockReturnValue(1000);+ });+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('plays the eased slide the transition publishes where it has one', () => {+ const animator = standInAnimator();++ rideKeyboard(+ animator as unknown as Animator,+ {y: -300},+ transition({+ curve: {+ durationMs: androidKeyboard.showMs,+ points: androidKeyboard.showCurve,+ },+ }),+ );++ expect(animator.animate).not.toHaveBeenCalled();+ expect(animator.play).toHaveBeenCalledTimes(1);+ const [curves, options] = animator.play.mock.calls[0] as unknown as [+ Record<string, {duration: number; at: (t: number) => number}>,+ {at: number},+ ];+ expect(options).toEqual({at: 1000});+ expect(curves.y.duration).toBeCloseTo(androidKeyboard.showMs / 1000, 9);+ expect(curves.y.at(curves.y.duration)).toBe(-300);+ });++ it("plays the transition's own curve, even a show published with the hide slide", () => {+ const animator = standInAnimator();++ rideKeyboard(+ animator as unknown as Animator,+ {y: -300},+ transition({+ kind: 'show',+ curve: {+ durationMs: androidKeyboard.hideMs,+ points: androidKeyboard.hideCurve,+ },+ }),+ );++ const [curves] = animator.play.mock.calls[0] as unknown as [+ Record<string, {duration: number; at: (t: number) => number}>,+ ];+ expect(curves.y.duration).toBeCloseTo(androidKeyboard.hideMs / 1000, 9);+ });++ it('lands at once when the slide has ended by the call, as a page busy through the slide reads its report', () => {+ const animator = standInAnimator();+ vi.spyOn(performance, 'now').mockReturnValue(+ 1000 + androidKeyboard.showMs + 50,+ );++ const handle = rideKeyboard(+ animator as unknown as Animator,+ {y: 0},+ transition({+ curve: {+ durationMs: androidKeyboard.showMs,+ points: androidKeyboard.showCurve,+ },+ }),+ );++ expect(handle).toBeNull();+ expect(animator.play).not.toHaveBeenCalled();+ expect(animator.set).toHaveBeenCalledWith({y: 0});+ });++ it('asks the animator for its entrance under Reduce Motion where the ride is an entrance', () => {+ const animator = standInAnimator();+ const slide = transition({+ curve: {+ durationMs: androidKeyboard.showMs,+ points: androidKeyboard.showCurve,+ },+ });++ rideKeyboard(animator as unknown as Animator, {y: 0}, slide, {+ entrance: true,+ });+ rideKeyboard(animator as unknown as Animator, {y: 0}, slide);++ const calls = animator.play.mock.calls as unknown as [+ unknown,+ Record<string, unknown>,+ ][];+ expect(calls[0][1]).toEqual({at: 1000, crossfadeAs: 'entrance'});+ expect(calls[1][1]).toEqual({at: 1000});+ });++ it('lands at once when the keyboard jumps', () => {+ const animator = standInAnimator();++ expect(+ rideKeyboard(+ animator as unknown as Animator,+ {y: -300},+ transition({animated: false}),+ ),+ ).toBeNull();+ expect(animator.set).toHaveBeenCalledWith({y: -300});+ expect(animator.animate).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/keyboard/rideKeyboard.ts b/packages/core/src/keyboard/rideKeyboard.tsnew file mode 100644index 0000000000..49c0c6bcdf--- /dev/null+++ b/packages/core/src/keyboard/rideKeyboard.ts@@ -0,0 +1,100 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file rideKeyboard.ts+ * @input An animator, target values and a keyboard transition, with its+ * start and the curve the guide publishes with it, and ride options+ * @output rideKeyboard, which moves an element with the keyboard on the+ * keyboard's own motion+ * @position Keyboard module, internal to core. A guide subscriber calls it+ * for each transition, as BottomSheet's hook does.+ *+ * SYNC: When modified, update /packages/core/src/keyboard/README.md+ */++import type {+ Animator,+ MotionCurve,+ MotionHandle,+ MotionProperty,+ MotionValues,+} from '../motion/animator';+import {cubicBezier} from '../motion/bezier';+import type {KeyboardTransition} from './keyboardModel';++/** How a ride treats Reduce Motion. */+export interface RideOptions {+ /**+ * Under Reduce Motion, lands the element at once and fades it in. Without+ * it, the animator's own Reduce Motion plan applies.+ */+ readonly entrance?: boolean;+}++/**+ * Moves `animator`'s element to `to` with the keyboard: on its curve from+ * `transition.start`, or at once when the keyboard jumps.+ *+ * Android's keyboard moves on Gboard's slides up and down+ * (motion/android/keyboard.ts). The transition publishes the slide+ * (`curve`), and the ride plays it. Every ride starts at the transition's+ * start, so content that joins a slide late lands where the keyboard is. A+ * transition that is not animated lands at once, such as a keyboard changing+ * while up. So does a slide that has ended by the call. These values are the+ * keyboard's own motion, with no motion role. The system moves the keyboard+ * on them whatever the page does, so any other curve would leave the element+ * out of step.+ *+ * @example+ * ```+ * guide.subscribe(t => rideKeyboard(dock.animator, {y: -lift(t.to)}, t));+ * ```+ */+export function rideKeyboard(+ animator: Animator,+ to: MotionValues,+ transition: KeyboardTransition,+ {entrance = false}: RideOptions = {},+): MotionHandle | null {+ // A frame after a busy task still draws an animation at that task's+ // start. The ride sets a slide that has already ended, so no frame shows the+ // element short of its target.+ if (+ !transition.animated ||+ transition.curve == null ||+ performance.now() >= transition.start + transition.curve.durationMs+ ) {+ animator.set(to);+ return null;+ }+ // Under Reduce Motion nothing travels. The animator's default cross-fades+ // the element to its new place on a touch screen, and elsewhere moves it at+ // once. An entrance lands it at once and fades it in.+ const options = entrance+ ? {at: transition.start, crossfadeAs: 'entrance' as const}+ : {at: transition.start};+ const span = transition.curve.durationMs / 1000;+ const ease = cubicBezier(transition.curve.points);+ const curves: Partial<Record<MotionProperty, MotionCurve>> = {};+ for (const [property, target] of Object.entries(to) as [+ MotionProperty,+ number,+ ][]) {+ const from = animator.get(property, transition.start);+ const at = (t: number) =>+ from + (target - from) * ease(Math.min(1, Math.max(0, t / span)));+ curves[property] = {+ duration: span,+ at,+ velocity: t => {+ if (t >= span) {+ return 0;+ }+ const a = Math.max(0, t - 0.001);+ const b = Math.min(span, t + 0.001);+ return (at(b) - at(a)) / (b - a);+ },+ };+ }+ return animator.play(curves, options);+}diff --git a/packages/core/src/keyboard/useMobileKeyboard.ts b/packages/core/src/keyboard/useMobileKeyboard.tsnew file mode 100644index 0000000000..c59259c3fc--- /dev/null+++ b/packages/core/src/keyboard/useMobileKeyboard.ts@@ -0,0 +1,866 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useMobileKeyboard.ts+ * @input A target element and its scroll area, the keyboard module's reports+ * and focus claim, and the layout guide+ * @output useMobileKeyboard, which keeps a focused field in the target above+ * the on-screen keyboard and returns the inset and a dismiss+ * @position Keyboard module, internal to core. BottomSheet passes its panel.+ *+ * SYNC: When modified, update /packages/core/src/keyboard/README.md+ */++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 {subscribeInput} from '../utils/inputStream';+import {layoutViewportHeight} from '../utils/layoutViewport';+import {observeResize} from '../utils/sharedResizeObserver';+import {TOUCH_QUERY} from '../utils/touchPresentation';+import {+ KEYBOARD_EPSILON,+ findTextEntryControl,+ getKeyboardHeight,+ isKeyboardMeasurable,+ isNodeTarget,+ isTextEntryControl,+ refuseFocusReveal,+ subscribeKeyboardHeight,+ watchRevealPan,+} from './keyboardHeight';+import {getKeyboardLayoutGuide, keyboardProfileOf} from './keyboardLayoutGuide';+import type {KeyboardTransition} from './keyboardModel';+import {rideKeyboard} from './rideKeyboard';++// Chrome on Android pans the page itself if the keyboard still covers the+// focused field about 100 to 170 ms after the report. A field a fraction of a+// pixel under the keyboard's top still counts as covered. So the reveal sets+// the field 4 px above that top in the report's own commit, and only the rest+// rides.+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.+ */+ move: 'ride';+ /**+ * Reserves the keyboard's inset at the end of the target's scroll area,+ * the first element inside it that `useScrollableArea` marks with+ * `data-scroll-axis`.+ */+ inset?: boolean;+ /** The gap kept between the focused field and the keyboard, CSS px. */+ offset: number;+ /** Whether the target follows the keyboard at all. */+ isEnabled: boolean;+ /** Whether the target is at its full height, where it reveals fields. */+ isExpanded: boolean;+ /** Whether the target is open. Focus that leaves for nothing parks on it. */+ isOpen: boolean;+ /** Whether the page's own scroll is locked under the target. */+ isPageScrollLocked: boolean;+}++/** What useMobileKeyboard returns. */+export interface MobileKeyboard {+ /** The inset the target lays out at its scroller's content end, CSS px. */+ readonly inset: number;+ /**+ * Dismisses the keyboard, keeping the inset while the keyboard goes. The+ * focused field blurs, or `focusTarget` takes focus.+ */+ readonly dismiss: (focusTarget?: HTMLElement) => void;+}++interface KeyboardGeometry {+ bodyBottom: number;+}++function getObstructionTop(): number {+ return layoutViewportHeight(window) - getKeyboardHeight(window);+}++// Windows whose browser revealed a focused field itself right after the+// keyboard's report, by panning the visual viewport to it. Firefox for+// Android does so 54 to 143 ms after the report while the field is under the+// keyboard. The module learns this from the behavior, never from the user+// agent.+// From then on, a sheet there reveals its field at once, in the report's own+// frame.+let revealsAtReport = new WeakSet<Window>();++/** Forgets every window's recorded reveal, for tests. */+export function __resetRevealsAtReportForTest(): void {+ revealsAtReport = new WeakSet<Window>();+}++// How far the body runs under the keyboard's top, CSS px. The keyboard's top+// comes from `innerHeight`, a whole number of CSS px, but the visual viewport+// and element rects are fractional. On the Android emulator, Chrome's visual+// viewport is 754.3 px over a 754 px layout viewport. A sheet sized to it+// then ends 0.3 px below `innerHeight` with no keyboard up. So an overlap+// under one CSS px is `innerHeight`'s precision, not an obstruction.+function overlapOf(bodyBottom: number, obstructionTop: number): number {+ const overlap = bodyBottom - obstructionTop;+ return overlap > KEYBOARD_EPSILON ? overlap : 0;+}++// Under half a pixel is rounding, not a keyboard.+function isVisualViewportRecovered(): boolean {+ return getKeyboardHeight(window) <= 0.5;+}++/**+ * 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+ * the inset in the panel's scroll area. Returns the inset the keyboard takes+ * at the end of that area's content, CSS px, or 0 without a keyboard, and a+ * dismiss.+ *+ * @example+ * ```+ * const keyboard = useMobileKeyboard(panelRef, {move: 'ride', inset: true, offset: 48, isEnabled, isExpanded, isOpen, isPageScrollLocked});+ * ```+ */+export function useMobileKeyboard(+ targetRef: RefObject<HTMLElement | null>,+ {+ inset: reservesInset = false,+ offset,+ isEnabled,+ isExpanded,+ isOpen,+ isPageScrollLocked,+ }: 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+ // functional style.+ const [keyboardInset, setKeyboardInset] = useState(0);+ const hasKeyboardLayoutRef = useRef(false);+ const retainKeyboardLayoutRef = useRef(false);+ const isEnabledRef = useRef(isEnabled);+ const isExpandedRef = useRef(isExpanded);+ const isOpenRef = useRef(isOpen);+ isEnabledRef.current = isEnabled;+ isExpandedRef.current = isExpanded;+ isOpenRef.current = isOpen;+ // Touch-only work, the ride and the reveal-pan watch, attaches only under a+ // coarse primary pointer (the touch query). Under a fine one, the hook+ // registers no touch listener.+ const isTouch = useMediaQuery(TOUCH_QUERY, false);++ const dismiss = useCallback(+ (focusTarget?: HTMLElement) => {+ const target = targetRef.current;+ const activeElement = document.activeElement;+ if (+ !isEnabledRef.current ||+ target == null ||+ !(activeElement instanceof HTMLElement) ||+ activeElement === target ||+ !target.contains(activeElement)+ ) {+ return;+ }+ // Keep the current keyboard scroll range while the keyboard goes.+ // Viewport resize events unwind that layout as the visual viewport+ // recovers, avoiding a content jump on the first drag frame.+ retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;+ if (focusTarget == null) {+ activeElement.blur();+ } else {+ focusTarget.focus({preventScroll: true});+ }+ },+ [targetRef],+ );++ // Syncs the on-screen keyboard with closing: a target that closes blurs its+ // focused field, which dismisses the keyboard.+ useEffect(() => {+ if (isEnabled && !isOpen) {+ dismiss();+ }+ }, [dismiss, isEnabled, isOpen]);++ useAttachment(+ targetRef,+ sheet => {+ const body = sheet.querySelector<HTMLElement>('[data-scroll-axis]');+ if (!isEnabled || !reservesInset || body == null) {+ return () => {};+ }++ let keyboardGeometry: KeyboardGeometry | null = null;+ // Where a smooth reveal under way is taking the body's scrollTop.+ let smoothTarget: number | null = null;+ // The inset laid out at the end of the body's content, CSS px, and the+ // scroll range it adds there. The inset's drop takes that range back. The+ // two can differ: Chrome 124 added 344 px of range for a 360 px inset.+ let laidOutInset = 0;+ let insetRange = 0;+ // Where the keyboard layout guide publishes the keyboard's own slide, as+ // Gboard's in Chrome on Android, the sheet's content rides it. This needs+ // a coarse primary pointer and Chrome's schedule. Under a fine pointer+ // nothing of the ride attaches. In a browser without the VirtualKeyboard+ // API, such as iOS Safari or Firefox for Android, the guide never starts.+ // There the inset follows the reports. The hook subscribes to the guide+ // before the keyboard module below, so the guide publishes a report's+ // transition before the reveal reads it.+ const guide =+ isTouch && keyboardProfileOf(window) === 'chromium'+ ? getKeyboardLayoutGuide(window)+ : null;+ const contentAnimator = (): Animator | null => {+ const content = body.firstElementChild;+ return guide != null && content instanceof HTMLElement+ ? animatorFor(content)+ : null;+ };+ // How far a ride has moved the content from where its layout puts it, as+ // the page draws it now. The reveal reads a control's rect in the same+ // frame.+ const rideOffset = () => {+ const content = body.firstElementChild;+ if (!(content instanceof HTMLElement)) {+ return 0;+ }+ const translate = getComputedStyle(content).translate;+ return parseFloat(translate.split(' ')[1] ?? '') || 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+ // the report that late, and the ride then lands at once.+ const showOnSlide = (atReport: boolean): KeyboardTransition | null => {+ const transition = guide?.transition;+ return transition != null &&+ transition.kind === 'show' &&+ transition.animated &&+ transition.curve != null &&+ (atReport ||+ performance.now() < transition.start + transition.curve.durationMs)+ ? transition+ : null;+ };+ // A hide the hook holds the inset through (see holdInsetThrough).+ let heldHide: {readonly release: () => void} | 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.+ let keyboardObstructionTop: number | null = null;+ let bodyScrollTopAtKeyboard: number | null = null;+ // The hook takes focus moves over where this window measures the+ // keyboard, never by user agent, and only under a coarse primary pointer.+ // Under a fine one, it registers no touch-only listener.+ // Desktop Safari and Firefox measure too, but show no on-screen keyboard+ // and keep the browser's own focus. The effect runs again when the+ // pointer changes, so a tablet that docks a mouse drops the claim.+ const ownsFocusTransitions = isTouch && isKeyboardMeasurable(window);++ // Lays the inset out before anything measures or scrolls the body: the+ // reveal scrolls into the inset it adds in the same frame.+ const writeInset = (inset: number) => {+ const changes = inset !== laidOutInset;+ const rangeBefore = changes ? body.scrollHeight : 0;+ laidOutInset = inset;+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the reveal scrolls into this inset in the same frame, so it must be laid out before the reveal measures+ flushSync(() => setKeyboardInset(inset));+ if (changes) {+ insetRange =+ inset === 0+ ? 0+ : Math.max(0, insetRange + body.scrollHeight - rangeBefore);+ }+ };++ const clearKeyboardLayout = () => {+ writeInset(0);+ if (bodyScrollTopAtKeyboard != null) {+ smoothTarget = null;+ body.scrollTop = bodyScrollTopAtKeyboard;+ }+ keyboardGeometry = null;+ keyboardObstructionTop = null;+ bodyScrollTopAtKeyboard = null;+ documentScrollAtKeyboard = null;+ hasKeyboardLayoutRef.current = false;+ retainKeyboardLayoutRef.current = false;+ };++ // `within` is how far below its resting place the control can sit and+ // still clear the keyboard.+ const scrollBodyBy = (+ distance: number,+ smoothly: boolean,+ ride: KeyboardTransition | null = null,+ within: number | null = null,+ ) => {+ smoothTarget = null;+ const animator = ride == null ? null : contentAnimator();+ if (ride != null && animator != null) {+ // The body lands at once, and its content rides the keyboard's slide+ // up from the slide's start. The content starts no lower than+ // `within`, so the control clears the keyboard in this commit. Content+ // that joins the slide late is where the keyboard is (rideKeyboard). A+ // further scroll during the slide adds to the same ride.+ const before = body.scrollTop;+ body.scrollTop = before + distance;+ const moved = body.scrollTop - before;+ // Only what the body actually scrolled rides. A remainder under the+ // scroll position's precision moves nothing, so the ride under way+ // stays on its curve.+ if (moved !== 0) {+ const from = animator.get('y', ride.start) + moved;+ animator.set({y: within == null ? from : Math.min(from, within)});+ rideKeyboard(animator, {y: 0}, ride, {entrance: within != null});+ }+ return;+ }+ if (typeof body.scrollBy !== 'function') {+ body.scrollTop += distance;+ return;+ }+ // Reduce Motion applies on any pointer.+ const reduceMotion =+ typeof window.matchMedia === 'function' &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ const behavior = smoothly && !reduceMotion ? 'smooth' : 'instant';+ if (behavior === 'smooth') {+ smoothTarget = body.scrollTop + distance;+ }+ body.scrollBy({+ top: distance,+ // Not 'auto', which defers to the element's computed+ // `scroll-behavior`. A consumer's `scroll-behavior: smooth` would then+ // animate a scroll this hook needs to land in the same frame.+ behavior,+ });+ };++ // The distance a smooth reveal under way has still to scroll, as far as+ // the body can scroll. It is 0 once it has landed, or with none under way.+ const smoothDistanceLeft = () => {+ if (smoothTarget == null) {+ return 0;+ }+ const maxScroll = Math.max(+ body.scrollTop,+ body.scrollHeight - body.clientHeight,+ );+ const target = Math.min(smoothTarget, maxScroll);+ const left = target - body.scrollTop;+ return Math.abs(left) < 1 ? 0 : left;+ };++ // Scroll `control` into the part of the body the keyboard leaves visible,+ // reading live geometry each time.+ const scrollControlIntoSafeArea = (+ control: HTMLElement,+ smoothly: boolean,+ ride: KeyboardTransition | null = null,+ ) => {+ const measuredBodyRect = body.getBoundingClientRect();+ const measuredControlRect = control.getBoundingClientRect();+ const obstructionTop = getObstructionTop();+ // Under a pixel of overhang is `innerHeight`'s precision, not a+ // keyboard: no suggestion clearance then (overlapOf).+ const overlap = overlapOf(measuredBodyRect.bottom, obstructionTop);+ const clearance = overlap > 0 ? offset : 0;+ const safeTop = measuredBodyRect.top;+ const safeBottom = Math.min(+ 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.+ // Firefox keeps adding a smooth scrollBy's distance after another+ // scroll. A ride's translate is not where the layout puts the control+ // either.+ const pending = smoothDistanceLeft() + rideOffset();+ const controlBottom = measuredControlRect.bottom - pending;+ const controlTop = measuredControlRect.top - pending;+ if (controlBottom > safeBottom) {+ scrollBodyBy(+ controlBottom - safeBottom,+ smoothly,+ ride,+ Math.max(+ 0,+ obstructionTop - safeBottom - FIELD_CLEARANCE_AT_REPORT,+ ),+ );+ } else if (controlTop < safeTop) {+ scrollBodyBy(controlTop - safeTop, smoothly, ride);+ }+ };++ const applyKeyboardGeometry = (geometry: KeyboardGeometry) => {+ const obstructionTop = getObstructionTop();+ // A collapsed detent can extend the body below the layout viewport even+ // after the keyboard closes, so body overlap alone cannot identify+ // recovery. Once the visual viewport is full height again, release the+ // retained keyboard layout unconditionally.+ if (isVisualViewportRecovered()) {+ clearKeyboardLayout();+ return;+ }+ const overlap = overlapOf(geometry.bodyBottom, obstructionTop);+ if (overlap === 0) {+ clearKeyboardLayout();+ return;+ }++ const inset = Math.max(+ 0,+ geometry.bodyBottom - (obstructionTop - offset),+ );+ writeInset(inset);+ };++ // Take every focus move into a field over before the browser performs it+ // (refuseFocusReveal). That handler does not reveal the field. Focusing+ // it raises focusin, and the viewport report that follows the keyboard+ // raises another. Both schedule the reveal below, which knows the safe+ // area and scrolls only the sheet's own body.+ //+ // The keyboard's Done button parks focus on the body. The handler parks+ // focus that leaves for nothing on the sheet instead. Then a second tap on+ // the same field is still a move the handler sees. Left on the body, the field+ // is already `document.activeElement` on the next tap. Then no blur fires,+ // and the browser reveals the field its own way. This applies only while+ // the sheet is open. Closing blurs the field too, and no next tap needs a+ // claim. The host restores focus to whatever opened the sheet.+ const claimFocusTransitions = () =>+ refuseFocusReveal(document, {+ isActive: () => isExpandedRef.current,+ claim: destination => findTextEntryControl(destination, body),+ park: origin => {+ if (isOpenRef.current && findTextEntryControl(origin, body)) {+ sheet.focus({preventScroll: true});+ }+ },+ });++ const revealFocusedControl = (atReport = false) => {+ // Through a hide the sheet rides, its layout holds until the end.+ if (heldHide != null) {+ return;+ }+ const obstructionTop = getObstructionTop();+ const activeElement = document.activeElement;+ const focusedControl =+ activeElement instanceof HTMLElement &&+ body.contains(activeElement) &&+ isTextEntryControl(activeElement)+ ? activeElement+ : null;+ // The keyboard can close while its field keeps focus, as a downward+ // dismissal does on iOS. The full clear puts back the inset and the+ // body's scroll. The hook then reveals the field still focused in the+ // restored body, because it may not be the field that opened the+ // keyboard.+ if (hasKeyboardLayoutRef.current && isVisualViewportRecovered()) {+ clearKeyboardLayout();+ if (isExpandedRef.current && focusedControl != null) {+ scrollControlIntoSafeArea(focusedControl, false);+ }+ return;+ }+ if (!isExpandedRef.current || focusedControl == null) {+ if (retainKeyboardLayoutRef.current && keyboardGeometry) {+ applyKeyboardGeometry(keyboardGeometry);+ return;+ }+ clearKeyboardLayout();+ return;+ }++ // An iOS keyboard dismissed by a drag can leave its accessory bar, so+ // the visual viewport grows short of full height. The body goes back+ // to its scroll from before the keyboard as soon as that starts. The+ // reveal below still clears what covers a low field. The new top is+ // kept, so a later content change does not repeat this.+ if (+ hasKeyboardLayoutRef.current &&+ keyboardObstructionTop != null &&+ obstructionTop > keyboardObstructionTop + 0.5 &&+ bodyScrollTopAtKeyboard != null+ ) {+ smoothTarget = null;+ body.scrollTop = bodyScrollTopAtKeyboard;+ keyboardObstructionTop = obstructionTop;+ }++ retainKeyboardLayoutRef.current = false;++ const measuredBodyRect = body.getBoundingClientRect();+ const overlap = overlapOf(measuredBodyRect.bottom, obstructionTop);+ // The extra clearance leaves space for mobile suggestion UI, but only+ // while the visual viewport actually overlaps the sheet. With no+ // obstruction, ordinary desktop and hardware-keyboard focus must not+ // shift an already visible control.+ const clearance = overlap > 0 ? offset : 0;+ keyboardGeometry =+ overlap > 0+ ? {+ bodyBottom: measuredBodyRect.bottom,+ }+ : null;+ // Where the document sits with the keyboard up and nothing yet shifted:+ // the position handleDocumentScroll returns to. Captured on the+ // transition only — a reveal that runs after the browser has already+ // scrolled would otherwise record the shifted position as correct.+ if (overlap > 0 && !hasKeyboardLayoutRef.current) {+ keyboardObstructionTop = obstructionTop;+ bodyScrollTopAtKeyboard = body.scrollTop;+ if (isPageScrollLocked) {+ documentScrollAtKeyboard = {x: window.scrollX, y: window.scrollY};+ }+ }+ hasKeyboardLayoutRef.current = overlap > 0;++ const inset =+ overlap > 0+ ? Math.max(+ 0,+ measuredBodyRect.bottom - (obstructionTop - clearance),+ )+ : 0;+ writeInset(inset);++ scrollControlIntoSafeArea(+ focusedControl,+ overlap > 0 && !revealsAtReport.has(window),+ overlap > 0 ? showOnSlide(atReport) : null,+ );+ };++ // Where the body's scroll rests once the keyboard is gone, as+ // revealFocusedControl leaves it. The clear puts back the scroll from+ // before the keyboard, within the range left once the inset drops. The+ // reveal then brings a field that keeps focus into the body's view.+ const restingScrollTop = (): number => {+ const scrollTop = body.scrollTop;+ const maxAtRest = Math.max(+ 0,+ body.scrollHeight - insetRange - body.clientHeight,+ );+ let resting = Math.min(maxAtRest, bodyScrollTopAtKeyboard ?? scrollTop);+ const active = document.activeElement;+ if (+ isExpandedRef.current &&+ active instanceof HTMLElement &&+ body.contains(active) &&+ isTextEntryControl(active)+ ) {+ const bodyRect = body.getBoundingClientRect();+ const rect = active.getBoundingClientRect();+ // Where the layout puts the control at the resting scroll.+ const shift = scrollTop - resting - rideOffset();+ if (rect.bottom + shift > bodyRect.bottom) {+ resting += rect.bottom + shift - bodyRect.bottom;+ } else if (rect.top + shift < bodyRect.top) {+ resting += rect.top + shift - bodyRect.top;+ }+ resting = Math.min(maxAtRest, Math.max(0, resting));+ }+ return resting;+ };++ // 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.+ const holdInsetThrough = (transition: KeyboardTransition) => {+ heldHide?.release();+ const animator = contentAnimator();+ const drop = body.scrollTop - restingScrollTop();+ const handle =+ animator != null && drop !== 0+ ? rideKeyboard(animator, {y: drop}, transition)+ : null;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const hold = {+ release: () => {+ clearTimeout(timer);+ if (heldHide === hold) {+ heldHide = null;+ }+ },+ };+ heldHide = hold;+ const commit = () => {+ if (heldHide !== hold) {+ return;+ }+ heldHide = null;+ revealFocusedControl();+ animator?.set({y: 0});+ };+ if (handle == null) {+ const end = transition.start + (transition.curve?.durationMs ?? 0);+ timer = setTimeout(commit, Math.max(0, end - performance.now()));+ } else {+ void handle.finished.then(commit);+ }+ };+ const unsubscribeGuide = guide?.subscribe(transition => {+ // A jump lands with the reports: only a slide rides.+ if (transition.curve == null) {+ return;+ }+ if (transition.kind === 'hide') {+ if (hasKeyboardLayoutRef.current && transition.animated) {+ holdInsetThrough(transition);+ }+ return;+ }+ if (heldHide != null) {+ // The keyboard comes back before it is down (focus returns): the+ // inset never left, so the content rides back to its place with it.+ heldHide.release();+ const animator = contentAnimator();+ if (animator != null) {+ rideKeyboard(animator, {y: 0}, transition);+ }+ }+ });++ let animationFrame = 0;+ const scheduleReveal = () => {+ cancelAnimationFrame(animationFrame);+ animationFrame = requestAnimationFrame(() => revealFocusedControl());+ };++ // Resuming the app re-reveals the focused field with no focus event to+ // claim. The reveal above never runs, and the document scrolls with the+ // fixed sheet. Put that scroll back on the event that reports it, and+ // reveal again inside the sheet.+ //+ // This applies only while the page is locked. Only then can a document+ // scroll not be the user's own. Behind a non-modal sheet the page stays+ // scrollable, and a revert there would fight the user.+ const handleDocumentScroll = () => {+ const expected = documentScrollAtKeyboard;+ if (+ expected == null ||+ (window.scrollX === expected.x && window.scrollY === expected.y)+ ) {+ return;+ }+ window.scrollTo(expected.x, expected.y);+ const activeElement = document.activeElement;+ if (+ activeElement instanceof HTMLElement &&+ body.contains(activeElement) &&+ isTextEntryControl(activeElement)+ ) {+ scrollControlIntoSafeArea(activeElement, false);+ }+ };++ let stopObserving: (() => void)[] = [];+ const refreshObservedLayout = () => {+ if (typeof ResizeObserver === 'undefined') {+ return;+ }+ for (const stop of stopObserving) {+ stop();+ }+ stopObserving = [];++ // Body and sheet box changes include public height and xstyle updates.+ // The inset pseudo-element is the content box's last box. Where the+ // content grows with it, the observation runs the reveal again. The+ // reveal computes the same inset from the body's unchanged box, so+ // nothing feeds back into the sheet's geometry.+ const targets = new Set<Element>([body, sheet]);+ for (const child of body.children) {+ targets.add(child);+ }+ const activeElement = document.activeElement;+ if (+ activeElement instanceof HTMLElement &&+ body.contains(activeElement)+ ) {+ for (+ let element: HTMLElement | null = activeElement;+ element && element !== body;+ element = element.parentElement+ ) {+ targets.add(element);+ }+ }+ for (const target of targets) {+ stopObserving.push(observeResize(target, scheduleReveal));+ }+ };+ const mutationObserver =+ typeof MutationObserver === 'undefined'+ ? null+ : new MutationObserver(records => {+ // Skip the sheet's own attribute writes on the body. Consumer+ // DOM, text, class, style, or visibility changes can all move the+ // focused control without a viewport event. The inset's write on+ // the content box schedules one more reveal, which finds the same+ // inset and settles.+ if (+ records.every(+ record =>+ record.type === 'attributes' && record.target === body,+ )+ ) {+ return;+ }+ refreshObservedLayout();+ scheduleReveal();+ });+ const handleFocusIn = () => {+ refreshObservedLayout();+ scheduleReveal();+ };+ const handleFocusOut = () => {+ // Keep the added scroll range while the keyboard animates away. A focus+ // transition to another text-entry control cancels this in focusin.+ retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;+ scheduleReveal();+ };+ const handleSheetTransitionEnd = (event: TransitionEvent) => {+ if (event.target === sheet && event.propertyName === 'transform') {+ scheduleReveal();+ }+ };++ const stopClaiming = ownsFocusTransitions+ ? claimFocusTransitions()+ : null;+ // The hook reveals a keyboard report in its own frame, not the next. A browser+ // that reveals a focused field itself pans the visual viewport to it a few+ // frames after the report. It does so if the keyboard still covers the+ // field. Such a pan moves the visual viewport down within the layout+ // viewport, with no touch, document scroll or zoom since the report. Once+ // the sheet lands the field itself, the hook puts the pan back: it scrolls+ // the full-viewport dialog's top into view. On every later report, the field+ // lands at once.+ let lastHeight = getKeyboardHeight(window);+ // Under a coarse primary pointer only: the watch reads touches, and an+ // on-screen keyboard's pan comes with a touch screen.+ const revealPan = isTouch+ ? watchRevealPan(window, {+ owns: focused =>+ hasKeyboardLayoutRef.current && body.contains(focused),+ // The reader's own scroll may stop a smooth reveal short: forget+ // where it was going.+ onTouch: () => {+ smoothTarget = null;+ },+ })+ : null;+ // Every keyboard report reaches the reveal through the keyboard module's+ // one set of listeners.+ const unsubscribe = subscribeKeyboardHeight(window, event => {+ if (event.type !== 'viewport') {+ return;+ }+ if (event.height !== lastHeight) {+ lastHeight = event.height;+ revealPan?.report();+ cancelAnimationFrame(animationFrame);+ revealFocusedControl(true);+ return;+ }+ if (revealPan?.isRevealPan(event.height) === true) {+ revealsAtReport.add(window);+ cancelAnimationFrame(animationFrame);+ // A smooth reveal still under way lands the field where it is going.+ // Another scroll on top of it would overshoot in Firefox, which keeps+ // adding a smooth scrollBy's distance after an instant scroll. The+ // field ended 244 px too high there. With none under way, the field+ // lands at once.+ const distanceLeft = smoothDistanceLeft();+ if (distanceLeft === 0) {+ revealFocusedControl();+ }+ // The hook puts the pan back only if the sheet holds the field above+ // the keyboard with its own scroller. Rects are in layout-viewport+ // coordinates, which the pan does not move. A ride still draws the+ // field lower than its layout, so its offset does not count. A field+ // the sheet cannot bring up keeps the browser's reveal.+ const activeElement = document.activeElement;+ const dialog = sheet.closest('dialog');+ if (+ dialog != null &&+ activeElement instanceof HTMLElement &&+ activeElement.getBoundingClientRect().bottom -+ rideOffset() -+ distanceLeft <=+ getObstructionTop()+ ) {+ // The full-viewport dialog is fixed at the layout viewport's top.+ revealPan?.putBack(dialog);+ }+ return;+ }+ scheduleReveal();+ });+ body.addEventListener('focusin', handleFocusIn);+ body.addEventListener('focusout', handleFocusOut);+ sheet.addEventListener('transitionend', handleSheetTransitionEnd);+ // The window's capture phase hears every element's scroll too, and only+ // the page's own scroll moves the document.+ const stopDocumentScroll = subscribeInput(window, 'scroll', event => {+ const target = event.target;+ if (!isNodeTarget(target) || (target as Node).nodeType === 9) {+ handleDocumentScroll();+ }+ });+ mutationObserver?.observe(body, {+ attributes: true,+ characterData: true,+ childList: true,+ subtree: true,+ });+ refreshObservedLayout();+ // The dialog enters the top layer in a later effect. Wait until the next+ // frame so flex geometry is final before measuring the body.+ scheduleReveal();++ return () => {+ cancelAnimationFrame(animationFrame);+ stopClaiming?.();+ unsubscribe();+ unsubscribeGuide?.();+ heldHide?.release();+ contentAnimator()?.set({y: 0});+ revealPan?.stop();+ body.removeEventListener('focusin', handleFocusIn);+ body.removeEventListener('focusout', handleFocusOut);+ sheet.removeEventListener('transitionend', handleSheetTransitionEnd);+ stopDocumentScroll();+ for (const stop of stopObserving) {+ stop();+ }+ mutationObserver?.disconnect();+ setKeyboardInset(0);+ hasKeyboardLayoutRef.current = false;+ retainKeyboardLayoutRef.current = false;+ };+ },+ `${isEnabled}|${reservesInset}|${isPageScrollLocked}|${isTouch}|${offset}`,+ );+ return {inset: keyboardInset, dismiss};+}diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex fa0341f398..352a45bbd9 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -27,6 +27,7 @@ roles through `resolveMotion`.| `uikit/segmented.ts` | UISegmentedControl: the selection indicator's spring; under Reduce Motion the animator's cross-fade replaces it. || `uikit/switch.ts` | UISwitch on iOS 26.2: geometry, the lift, settle, travel and tracking springs, the flip distance, the track colour. || `uikit/datePicker.ts` | UIDatePicker: the rules it adds to its wheels. |+| `android/keyboard.ts` | Android's software keyboard (Chrome with Gboard): its slides' durations and curves (no theme's) and when they start against Chrome's report and a blur. || `roles.ts` | The internal motion roles: the springs, durations and curves `spec:AST-094` FR4 names, registered by the shared tables, and a role's CSS form read back. || `roleValue.ts` | A role's CSS form, written: a spring's duration and bounce, a duration in ms, a curve's `cubic-bezier()`. || `resolveMotion.ts` | A role's value: its table value, as the per-role tables stay internal (`spec:AST-094` DEC-15). |diff --git a/packages/core/src/motion/android/android.test.ts b/packages/core/src/motion/android/android.test.tsnew file mode 100644index 0000000000..339326537f--- /dev/null+++ b/packages/core/src/motion/android/android.test.ts@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file android.test.ts+ * @input The Android constants table's files and values, the motion roles+ * @output Tests that every leaf carries a source, the values, and that the+ * table registers no motion role+ * @position Testing for /packages/core/src/motion/android+ */++import fs from 'node:fs';+import path from 'node:path';+import {describe, expect, it} from 'vitest';+import {motionRole} from '../roles';+import {keyboard} from '.';++const SOURCE_KINDS =+ /^@source (aosp frameworks\/|measured: .*Android \d|GUESS — )/;+const TABLE_FILES = fs+ .readdirSync(__dirname)+ .filter(+ f => f.endsWith('.ts') && f !== 'index.ts' && !f.endsWith('.test.ts'),+ );++describe('the Android constants table', () => {+ it('gives every leaf a source', () => {+ for (const file of TABLE_FILES) {+ const text = fs.readFileSync(path.resolve(__dirname, file), 'utf8');+ const body = text.slice(text.indexOf('export const'));+ const leaves = [...body.matchAll(/\/\*\*([\s\S]*?)\*\/\s*\n\s*(\w+):/g)];+ expect(leaves.length, file).toBeGreaterThan(0);+ for (const [, doc, key] of leaves) {+ const sources = doc+ .split('\n')+ .map(line => line.replace(/^\s*\*\s?/, ''))+ .filter(line => line.startsWith('@source'));+ expect(sources.length, `${file} ${key}`).toBeGreaterThan(0);+ for (const source of sources) {+ expect(source, `${file} ${key}`).toMatch(SOURCE_KINDS);+ }+ }+ }+ });++ it('slides the keyboard up and down on Gboard’s measured curves', () => {+ expect(keyboard.showCurve).toEqual([0.1, 0, 0, 1]);+ expect(keyboard.showMs).toBe(267);+ expect(keyboard.hideCurve).toEqual([0.3, 0.1, 0.2, 0.9]);+ expect(keyboard.hideMs).toBe(167);+ expect(keyboard.showReportLagMs).toBeGreaterThan(0);+ });++ it('is the keyboard’s own motion, no motion role', () => {+ for (const key of Object.keys(keyboard)) {+ expect(motionRole(`androidKeyboard.${key}`), key).toBeUndefined();+ }+ });+});diff --git a/packages/core/src/motion/android/index.ts b/packages/core/src/motion/android/index.tsnew file mode 100644index 0000000000..158f280996--- /dev/null+++ b/packages/core/src/motion/android/index.ts@@ -0,0 +1,18 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file index.ts+ * @input The domain files of the Android constants table+ * @output Re-exports `keyboard`+ * @position Entry of the Android constants table (motion/android). It is+ * internal to core, not exported from the package entry point.+ *+ * Where a touch presentation follows something Android draws itself, such as+ * the software keyboard, its numbers come from here with their sources. The+ * UIKit table does the same for iOS.+ *+ * SYNC: When you add a domain file, re-export it here and list it in+ * /packages/core/src/motion/README.md.+ */++export {keyboard} from './keyboard';diff --git a/packages/core/src/motion/android/keyboard.ts b/packages/core/src/motion/android/keyboard.tsnew file mode 100644index 0000000000..c1d0daaa1a--- /dev/null+++ b/packages/core/src/motion/android/keyboard.ts@@ -0,0 +1,96 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file keyboard.ts+ * @input None+ * @output `keyboard`: how the software keyboard moves on Android, in Chrome+ * with Gboard, as the page sees it. It holds the slides' durations and+ * curves, and when they start against Chrome's report and a blur.+ * @position The keyboard domain of the Android constants table, read by+ * keyboard/keyboardModel.ts. The UIKit table holds iOS's keyboard.+ *+ * SYNC: When modified, update /packages/core/src/keyboard/README.md+ */++// Chrome reports the keyboard once per slide, through the visual viewport,+// just after the slide starts, never per frame. Content that rides the+// keyboard plays these curves from the slide's start, so it moves in step+// with Gboard. They are Gboard's own motion, with no motion role. The system+// moves the keyboard on them whatever the page does, so any other curve+// would leave the content out of step.+//+// The values come from the Android 15 emulator with Chromium 158 and Gboard.+// A screen recording at 540 × 1200 gives Gboard's top in every frame, beside+// a marker the page paints on each report. Every leaf carries one or more+// `@source`, and android.test.ts enforces it.+export const keyboard = {+ /**+ * How long Gboard takes to slide up, in ms: from its first moved frame to+ * its resting top.+ *+ * @source measured: Chromium 158 with Gboard on Android 15 (API 35+ * emulator); 20 shows recorded frame by frame: 250 to 282 ms, 18 of+ * them 264 to 268 ms, Oct 25 2026+ */+ showMs: 267,+ /**+ * The curve of Gboard's slide up, cubic-bézier control points: fast out,+ * a long settle.+ *+ * @source measured: Chromium 158 with Gboard on Android 15 (API 35+ * emulator); the same 20 shows fit this curve over `showMs` within+ * 2.4 px rms, Oct 25 2026+ */+ showCurve: [0.1, 0, 0, 1],+ /**+ * How long after Gboard starts to slide up Chrome's report of it fires, in+ * ms. A show rides from the report dated back by this, joining the slide+ * where it is.+ *+ * @source measured: Chromium 158 with Gboard on Android 15 (API 35+ * emulator); twelve shows: the first frame the page painted after the+ * visual viewport's resize came 14 to 35 ms (median 33) after Gboard's+ * first moved frame, less the 8 ms an event takes on average to reach+ * the screen, Oct 25 2026+ */+ showReportLagMs: 25,+ /**+ * How long Gboard takes to slide down out of the page, in ms.+ *+ * @source measured: Chromium 158 with Gboard on Android 15 (API 35+ * emulator); 21 hides recorded frame by frame, from Gboard's first+ * moved frame until it leaves the screen: 148 to 153 ms in 20 of them;+ * this length with `hideCurve` fits them within 7.7 px rms,+ * Oct 25 2026+ */+ hideMs: 167,+ /**+ * The curve of Gboard's slide down, cubic-bézier control points: a slow+ * first frame, then fast.+ *+ * @source measured: Chromium 158 with Gboard on Android 15 (API 35+ * emulator); the same 21 hides, a free fit over `hideMs`, Oct 25 2026+ */+ hideCurve: [0.3, 0.1, 0.2, 0.9],+ /**+ * How long after the focused field blurs (to nothing that brings up a+ * keyboard) Gboard starts to slide down, in ms.+ *+ * @source measured: Chromium 158 with Gboard on Android 15 (API 35+ * emulator); five scripted blurs with a marker the page paints on the+ * blur: Gboard's first moved frame came from a frame before the marker+ * to 33 ms after it (median 16), Oct 25 2026+ */+ hideAfterBlurMs: 16,+ /**+ * How long after Gboard starts to slide down Chrome's report of the hide+ * fires, in ms, measured on blurs. A hide nothing predicts, such as Back,+ * reuses it, though Chrome can report Back later in the slide.+ *+ * @source measured: Chromium 158 with Gboard on Android 15 (API 35+ * emulator); twelve scripted blurs: the visual viewport's resize came+ * 42 to 52 ms after the blur (median 49), less `hideAfterBlurMs`,+ * Oct 25 2026+ */+ hideReportLagMs: 33,+} as const;diff --git a/packages/core/src/utils/layoutViewport.test.ts b/packages/core/src/utils/layoutViewport.test.tsnew file mode 100644index 0000000000..8a1c3f1456--- /dev/null+++ b/packages/core/src/utils/layoutViewport.test.ts@@ -0,0 +1,104 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file layoutViewport.test.ts+ * @input vitest, a stand-in window, visual viewport and document root. The+ * horizontal scrollbar's cases run on jsdom's window, in+ * keyboard/keyboardHeight.test.ts.+ * @output Tests layoutViewportHeight. It is innerHeight at a scale of 1, a+ * classic scrollbar included. The function scales it back where WebKit+ * reports it in the zoomed visual viewport's px, as in Safari on iOS 26.2.+ * It leaves innerHeight as is where innerHeight ignores the zoom, or with no+ * visual viewport.+ * @position Unit tests for utils/layoutViewport.ts+ */++import {describe, expect, it} from 'vitest';+import {layoutViewportHeight} from './layoutViewport';++function windowWith({+ innerHeight,+ innerWidth,+ viewport,+}: {+ innerHeight: number;+ innerWidth: number;+ viewport: {width: number; height: number; scale: number} | null;+}): Window {+ // A root as tall and as wide as the window: no horizontal scrollbar.+ const documentElement = {+ clientHeight: innerHeight,+ clientWidth: innerWidth,+ scrollWidth: innerWidth,+ };+ return {+ innerHeight,+ innerWidth,+ visualViewport: viewport,+ document: {documentElement},+ } as unknown as Window;+}++describe('layoutViewportHeight', () => {+ it('is innerHeight at a scale of 1', () => {+ const win = windowWith({+ innerHeight: 714,+ innerWidth: 402,+ viewport: {width: 402, height: 377, scale: 1},+ });+ expect(layoutViewportHeight(win)).toBe(714);+ });++ it('is innerHeight beside a classic scrollbar, which innerWidth counts and the visual viewport does not', () => {+ // A desktop page with a 17 px vertical scrollbar: the layout viewport is+ // still innerHeight tall.+ const win = windowWith({+ innerHeight: 800,+ innerWidth: 1280,+ viewport: {width: 1263, height: 800, scale: 1},+ });+ expect(layoutViewportHeight(win)).toBe(800);+ });++ it('scales innerHeight back where WebKit reports it in the zoomed visual viewport\u2019s px', () => {+ // Safari on iOS 26.2 at a 1.33 and a 2.56 zoom of a 402 × 714 layout+ // viewport.+ const zoomed = windowWith({+ innerHeight: 536,+ innerWidth: 302,+ viewport: {width: 301.5, height: 282.75, scale: 4 / 3},+ });+ expect(Math.abs(layoutViewportHeight(zoomed) - 714)).toBeLessThan(1);+ const deep = windowWith({+ innerHeight: 279,+ innerWidth: 157,+ viewport: {width: 157.03, height: 147.3, scale: 2.56},+ });+ expect(Math.abs(layoutViewportHeight(deep) - 714)).toBeLessThan(1);+ });++ it('leaves innerHeight as it is where it ignores the zoom', () => {+ // innerWidth stays the layout width: the visual viewport's width times+ // its scale.+ const win = windowWith({+ innerHeight: 714,+ innerWidth: 402,+ viewport: {width: 201, height: 357, scale: 2},+ });+ expect(layoutViewportHeight(win)).toBe(714);+ });++ it('follows the layout viewport WebKit clamps to the document after a scroll', () => {+ const win = windowWith({+ innerHeight: 666,+ innerWidth: 402,+ viewport: {width: 402, height: 377, scale: 1},+ });+ expect(layoutViewportHeight(win)).toBe(666);+ });++ it('is innerHeight without a visual viewport', () => {+ const win = windowWith({innerHeight: 714, innerWidth: 402, viewport: null});+ expect(layoutViewportHeight(win)).toBe(714);+ });+});diff --git a/packages/core/src/utils/layoutViewport.ts b/packages/core/src/utils/layoutViewport.tsnew file mode 100644index 0000000000..4072b179f4--- /dev/null+++ b/packages/core/src/utils/layoutViewport.ts@@ -0,0 +1,104 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file layoutViewport.ts+ * @input A window: its innerHeight and innerWidth, its visual viewport's+ * width and scale, and its document's root box+ * @output layoutViewportHeight, the layout viewport's height in layout px+ * less a classic horizontal scrollbar, and __resetLayoutViewportForTest+ * @position Internal shared measurement, not re-exported from the utils+ * entry. The keyboard module, BottomSheet's keyboard obstruction and any+ * layout that sizes against the layout viewport read it.+ */++/**+ * The layout viewport's height, CSS px, in the units of element rects.+ *+ * `innerHeight` is the layout viewport's height in most engines. WebKit+ * reports `innerHeight` and `innerWidth` in the pinch-zoomed visual+ * viewport's px instead. At a 1.33 zoom of a 402 × 714 layout viewport,+ * Safari on iOS 26.2 reports 536 and 302. Element rects and the visual+ * viewport's height times its scale stay in layout px. So, read as is, a zoom+ * shrinks the layout viewport by the zoom, and the function scales the height+ * back.+ */+export function layoutViewportHeight(win: Window): number {+ const viewport = win.visualViewport;+ const width = viewport?.width ?? 0;+ if (viewport == null || !(width > 0)) {+ return win.innerHeight - horizontalScrollbarHeight(win);+ }+ const scale = viewport.scale;+ // Which units `innerWidth` is in tells the two apart without naming an+ // engine. It is the visual viewport's width where the zoom applies, and+ // that width times the scale where it does not. `innerWidth` is a whole+ // number of px against a fractional width, so it never equals either, and+ // the nearest wins with no tolerance constant. At a scale of 1 the two+ // widths are equal, so the function takes `innerHeight` as it is. A classic+ // scrollbar, which `innerWidth` counts, then changes nothing.+ const fromVisual = Math.abs(win.innerWidth - width);+ const fromLayout = Math.abs(win.innerWidth - width * scale);+ const height =+ fromVisual < fromLayout ? win.innerHeight * scale : win.innerHeight;+ return height - horizontalScrollbarHeight(win);+}++/**+ * The document's classic horizontal scrollbar, CSS px. It is in+ * `innerHeight` but not in the visual viewport's height. On a desktop page+ * wider than its window, Chromium's `innerHeight` is 800 for a 785 px visual+ * viewport. It is the part of `innerHeight` the root's client height leaves+ * out, up to the thickness of a scrollbar that takes room. Where scrollbars+ * overlay the content, as on every phone, that thickness is 0. So the room a+ * hidden toolbar adds to `innerHeight` is never taken for a scrollbar. Chrome+ * on Android sizes the root to the viewport with its toolbar shown.+ */+function horizontalScrollbarHeight(win: Window): number {+ const root = win.document.documentElement;+ const gap = win.innerHeight - root.clientHeight;+ if (!(gap > 0) || root.scrollWidth <= root.clientWidth) {+ return 0;+ }+ return Math.min(gap, scrollbarThickness(win.document));+}++// The scrollbar thickness each document measured, and the device pixel ratio+// it measured it at. A browser zoom changes the ratio, and with it how many+// CSS px a classic scrollbar takes. Measuring writes a probe to the document+// and forces a layout, so it runs once per document and zoom. Every later+// measurement stays one layout read.+let thicknesses = new WeakMap<+ Document,+ {devicePixelRatio: number; thickness: number}+>();++/** How much room a scrollbar takes from a scrolling box: 0 where overlaid. */+function scrollbarThickness(doc: Document): number {+ const devicePixelRatio = doc.defaultView?.devicePixelRatio ?? 1;+ const known = thicknesses.get(doc);+ if (known != null && known.devicePixelRatio === devicePixelRatio) {+ return known.thickness;+ }+ const thickness = measureScrollbarThickness(doc);+ thicknesses.set(doc, {devicePixelRatio, thickness});+ return thickness;+}++function measureScrollbarThickness(doc: Document): number {+ const probe = doc.createElement('div');+ probe.style.position = 'absolute';+ probe.style.top = '-200px';+ probe.style.width = '100px';+ probe.style.height = '100px';+ probe.style.overflow = 'scroll';+ probe.style.visibility = 'hidden';+ (doc.body ?? doc.documentElement).append(probe);+ const thickness = probe.offsetHeight - probe.clientHeight;+ probe.remove();+ return thickness;+}++/** Forgets every measured scrollbar thickness. Tests only. */+export function __resetLayoutViewportForTest(): void {+ thicknesses = new WeakMap();+}diff --git a/scripts/sync-exports.js b/scripts/sync-exports.jsindex b97ec5af95..ea99de61df 100644--- a/scripts/sync-exports.js+++ b/scripts/sync-exports.js@@ -43,7 +43,7 @@ const UTILITY_DIRS = new Set(['hooks', 'theme', 'utils']);* publicly exported. These are shared implementation details* consumed by other components via relative imports.*/-const INTERNAL_DIRS = new Set(['NavItem', 'gestures']);+const INTERNAL_DIRS = new Set(['NavItem', 'gestures', 'keyboard']);/*** Additional exports that can't be auto-discovered from directory structure.