diff --git a/.changeset/browser-support-ios-keyboard-ride.md b/.changeset/browser-support-ios-keyboard-ride.md
new file mode 100644
index 0000000000000..f866e6ed0751a
--- /dev/null
+++ b/.changeset/browser-support-ios-keyboard-ride.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] The browser-support guide's on-screen keyboard section describes the ride in Safari on iOS: ChatLayout's composer and a Tall BottomSheet's focused field ride UIKit's keyboard motion, the scroll room stays until Safari reports the keyboard gone, and the ride starts once the page has loaded Core's touch support.
+
+@vjeux
diff --git a/.changeset/keyboard-ride-ios.md b/.changeset/keyboard-ride-ios.md
new file mode 100644
index 0000000000000..76182458a651d
--- /dev/null
+++ b/.changeset/keyboard-ride-ios.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] In Safari on iOS, ChatLayout's composer and a Tall BottomSheet's focused field ride the on-screen keyboard on UIKit's own keyboard motion. They rise from Safari's report as the keyboard starts up; before, they moved up in one step. The composer also goes down from the blur that takes the keyboard down, as the sheet already did. The ride starts once the page has loaded Core's touch support, shortly after first paint; before that, they move in one step. Chrome on Android and Firefox for Android are unchanged. Under Reduce Motion nothing travels.
+
+@vjeux
diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md
index aee80bf99fcd2..bed37ad21faca 100644
--- a/docs/architecture/react-component-runtime.md
+++ b/docs/architecture/react-component-runtime.md
@@ -347,8 +347,16 @@ those contracts.
and Switch work by taps, clicks and keys, with no drag tracking and no slide
or spring, and a tap under a finger or under Reduce Motion changes them at
once, with no cross-fade; a bottom sheet still drags, and a drag that closes
- it takes the stylesheet exit instead of the spring. A gesture in that window
- does not start the load. The bundler keeps one copy per page however many
+ it takes the stylesheet exit instead of the spring. ChatLayout loads the touch
+ runtime after first paint under a coarse pointer, for the keyboard ride; it
+ adds no gesture, and under a fine pointer it never loads it. The runtime
+ exposes Safari on iOS's keyboard schedule
+ (`keyboard/uikitKeyboardSchedule.ts`): UIKit's keyboard spring and the
+ layout guide's focus rules there. The keyboard riders build it with the
+ duration and focus checks they hold, and register it with the layout guide.
+ No first-load module imports it. The layout guide cannot hold it, since
+ nearly every page loads the guide first. A gesture in that
+ window does not start the load. The bundler keeps one copy per page however many
components use them. If the runtime's chunk fails to load, the page stays as
it is before the load: components work by taps, clicks and keys, and no
gesture retries the load. The loader's `import()` targets
diff --git a/docs/specs/AST-099-mobile-keyboard/spec.md b/docs/specs/AST-099-mobile-keyboard/spec.md
index 1c0e3e12c5fba..3823dd1010d8f 100644
--- a/docs/specs/AST-099-mobile-keyboard/spec.md
+++ b/docs/specs/AST-099-mobile-keyboard/spec.md
@@ -141,7 +141,8 @@ app to turn on.
comes from FR2 there too and FR8 governs how surfaces ride the keyboard, on any
device that shows an on-screen keyboard; a browser that offers the report but
shows no on-screen keyboard reads 0. A page that is not a secure context gets
- no such report, so FR8 does not apply there.
+ no such report, so FR8 does not apply there. In Safari on iOS, which WebKit's
+ touch capabilities identify, FR8 governs the ride too (DEC-12).
- **FR7 — Top-level documents only.** Inside an iframe the frame's visual
viewport does not change when the keyboard opens, so the keyboard height is
0 there and nothing changes. Behavior and evidence for this record come
@@ -170,6 +171,13 @@ app to turn on.
FR2 reads 0: a keyboard-aware field's keyboard height is 0 there and it
does not ride, since the browser has already made the room. Everywhere
else, keyboard-aware surfaces ride the visual-viewport height (DEC-4).
+ Safari on iOS reports the keyboard's show once, as UIKit's keyboard starts
+ up, and its hide only once the keyboard is down. There Core's
+ keyboard-aware surfaces ride UIKit's keyboard motion (DEC-12): on show from
+ that report, and on hide from the blur that takes the keyboard down, as FR3
+ sets out for a fully expanded sheet. A hide that no blur predicts rides from
+ Safari's report. Focus that moves into a frame, a custom element or an open
+ shadow root whose field can keep the keyboard up predicts no hide.
An Android browser without a keyboard geometry API
that shrinks only its visual viewport, such as Firefox for Android, gets
FR2–FR5 under FR6.
@@ -197,10 +205,11 @@ app to turn on.
it when the keyboard hides. Nothing else moves.
- **Docked containers.** A field docked at the bottom of the viewport, in a
bottom bar, a fixed toolbar, or a sheet, rides the keyboard: its docked
- container moves up as the keyboard opens and back down as it closes, on
- FR8's ride (DEC-2) where that applies, and following the visual-viewport
- height (FR2) elsewhere, such as Safari on iOS. A Core host rides by applying
- the keyboard height on its own element (FR3), and the field inside it is not
+ container moves up as the keyboard opens and back down as it closes. It
+ moves on FR8's ride where that applies: in Chrome on Android (DEC-2) and
+ Safari on iOS (DEC-12). Elsewhere, such as in Firefox for Android, it
+ follows the visual-viewport height (FR2). A Core host rides by applying the
+ keyboard height on its own element (FR3), and the field inside it is not
moved a second time.
- **App-owned docked containers.** A container the app owns rides too when it
is fixed-position, does not fill the viewport, and is docked: its layout
@@ -256,12 +265,13 @@ app to turn on.
- Supported feature/engine floor: the package's supported browsers
(`spec:AST-013` FR3). FR2–FR5 apply to Safari on iOS, in the browser and as a
home-screen app, and to Firefox for Android; FR8's ride applies wherever the
- browser reports the keyboard itself, such as Chrome on Android.
+ browser reports the keyboard itself, such as Chrome on Android, and in
+ Safari on iOS on UIKit's keyboard motion (DEC-12).
- Unsupported behavior: with no on-screen keyboard, or no visual-viewport
support, the keyboard height is 0 and nothing changes. During server render it
renders nothing and reads no viewport.
- Browser evidence: Safari on iOS, in the iOS Simulator or on a device and in a
- top-level document, proves the iOS claims of FR2–FR5, and Chrome on Android
+ top-level document, proves the iOS claims of FR2–FR5 and FR8, and Chrome on Android
in the Android emulator with Gboard proves FR8, with Firefox for Android in
the emulator proving FR2–FR5 there
(`spec:AST-013` FR10); DOM and visual-viewport tests prove the rest of
@@ -319,7 +329,10 @@ app to turn on.
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.
+ each platform's behavior. In Safari on iOS, the keyboard layout guide reads
+ UIKit's keyboard schedule, so the same sheet, ChatLayout's dock and a docked
+ container ride UIKit's keyboard motion (FR8, DEC-12). 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).
@@ -371,11 +384,12 @@ No covered field meets FR9 on `main`. Each gap below is open.
until one does, an element that has nothing to scroll does not count as a
scroller (the field keeps the browser's own reveal). BottomSheet's inset
stays local to its own sheet.
-- **Gap 12 — A fully expanded sheet's hide in Firefox for Android.** Firefox
- for Android reports no keyboard slide, so the sheet takes the same path as in
- Safari on iOS (`packages/core/src/keyboard/useMobileKeyboard.ts`). But
- Firefox reports the keyboard's hide once, at its end. The sheet's content
- moves at that report, in one frame, instead of riding from the blur (FR3).
+- **Gap 12 — A fully expanded sheet's hide in Firefox for Android.** Firefox for
+ Android reports no keyboard slide and has no keyboard schedule, so the sheet
+ follows the visual viewport's reports
+ (`packages/core/src/keyboard/useMobileKeyboard.ts`). But Firefox reports the
+ keyboard's hide once, at its end. The sheet's content moves at that report, in
+ one frame, instead of riding from the blur (FR3).
- **Gap 13 — A field focused before the touch runtime loads.** Until the shared
loader has run (after first paint, at idle within its cap; `spec:AST-080`
DEC-5), a focused field keeps the browser's own reveal and does not ride the
@@ -404,6 +418,7 @@ that sets its own `translate`, to the app.
| 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 |
| FR3–FR4 | ChatLayout's keyboard tests in jsdom and its interaction proofs in Chromium and WebKit | the fixed and the sticky dock with the keyboard shown and hidden; the message area's end padding; a transcript at its newest message; a page pinch-zoomed with the keyboard up; focus by tap, Tab, `focus()` and Done, under a finger and under a mouse | The dock left under the keyboard or lifted with none; the newest message unable to scroll above the composer; a transcript at its newest message left behind; the page panned to the composer's text under a finger; focus left in the text after Done, or the composer group focusable outside Done's park |
| FR8 | ChatLayout's interaction proofs in Chromium with Chrome's keyboard report | the dock riding Gboard's slide up from the report and down from the blur; reduced motion on | The dock lagging Gboard's slide, laying out or painting per frame, or jumping at the hand-back; the dock travelling under reduced motion instead of DR2's cross-fade |
+| FR8 | Safari on iOS in the Simulator, every drawn frame read; release gate: a physical iPhone (DEC-3) | ChatLayout's composer and a Tall sheet: keyboard shown, and hidden by a blur; a main thread blocked from the frame after Safari's report; reduced motion on; focus moving into a frame, a custom element or an open shadow root | A surface jumps at Safari's report, falls more than a frame behind the keyboard, or waits for the hide report instead of riding from the blur. Timing runs from Safari's report, so a ride that starts after its frame fails. A field inside a frame rides its hide from the report (FR7). |
| FR9 | ChatLayout's keyboard tests in jsdom | ChatComposer in the fixed and the sticky dock, above the keyboard after each focus route | ChatComposer ending under the keyboard, or moved a second time inside its dock, after any focus route |
| FR9 | TBD (Gap 1–11): a focus test per covered field, driving one keyboard change | each covered field in the page, a Tall and a `hug` BottomSheet, ChatLayout's fixed and sticky dock, an app's fixed bar docked to the bottom edge with no `translate` of its own, and a fixed Toolbar docked there; focus by tap, Tab, and `focus()`; a field in scrolling content in the page and in a nested scroller; a field near its scroller's end; a field in a scroller inside a full-viewport fixed container | A focused page field or Core-host field left under the keyboard or less than 10 CSS px above it (a field with no scroller between it and a fixed container FR9 leaves to the app keeps the browser's own reveal and is not a failure; a field that a scroller holds inside such a container, left under the keyboard, is a failure), a field in an app's docked bar whose bar's bottom does not meet the keyboard's top, scroll range left at the scroller's end after the keyboard hides, a page pan or translate, a reveal later than the frame the keyboard is reported in, or a second offset inside a host that already applies the height |
| FR9 | TBD (Gap 1): a source boundary check over the covered fields | every covered field's props type and source | A public prop, option, or context for the behavior |
@@ -548,6 +563,33 @@ 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.
+### DEC-12 — Safari on iOS rides the keyboard on UIKit's motion
+
+**Reference:** `spec:AST-099/DEC-12`
+**Decider:** pending
+
+Safari on iOS reports the keyboard's show once, as UIKit's keyboard starts
+up, and its hide only once the keyboard is down. A surface that lands at the
+report jumps while the keyboard slides, and a surface that waits for the hide
+report sits over the page the keyboard has left. So Core's keyboard-aware
+surfaces ride UIKit's own keyboard frame animation, as Astryx's UIKit tables
+measure it: a critically damped spring that Core Animation cuts at the
+duration the keyboard notifications report. The show rides from Safari's
+report. The hide rides from the blur that takes the keyboard down, as a
+prediction that Safari's report confirms, as FR3 sets out for a fully expanded
+sheet. A hide that no blur predicts, such as a downward dismissal, rides from
+Safari's report: the keyboard is already down, and the ride keeps the surface
+from jumping. A field inside a frame, a custom element or an open shadow root
+can keep the keyboard up, so focus that moves there predicts no hide. A ride
+starts once the task that delivers Safari's report ends, so work inside that
+task delays it; work after it does not. UIKit's schedule loads with the touch
+runtime after the page's first paint; until then, Safari on iOS moves in one
+step, as before. WebKit's
+touch capabilities select this schedule, never the user agent. Simulator
+evidence gates merge, and a physical iPhone gates release (DEC-3).
+
+Rejected: landing in one step at Safari's report, which jumps while the keyboard slides; a cubic-bézier stand-in for the spring, which drifts from the keyboard's own motion.
+
## Open questions
None.
diff --git a/packages/cli/assets/docs/browser-support.doc.mjs b/packages/cli/assets/docs/browser-support.doc.mjs
index b55a912125e8d..f54841e676c2f 100644
--- a/packages/cli/assets/docs/browser-support.doc.mjs
+++ b/packages/cli/assets/docs/browser-support.doc.mjs
@@ -154,6 +154,10 @@ export const docs = {
type: 'prose',
text: 'In Chrome on Android, ChatLayout\u2019s composer rides the keyboard as Gboard slides it up and down. 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 `` 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 those components measure no keyboard and change nothing: the browser has already made the room.',
},
+ {
+ type: 'prose',
+ text: 'In Safari on iOS, in the browser and as a home-screen app, ChatLayout\u2019s composer and a Tall BottomSheet\u2019s focused field ride the keyboard on UIKit\u2019s own keyboard motion. They rise from Safari\u2019s report of the keyboard, which comes as the keyboard starts up, and go down from the blur that takes the keyboard down. Safari reports the keyboard gone only once it is down, so the scroll room stays until then. The ride starts once the page has loaded Core\u2019s touch support, shortly after first paint; before that, they move in one step.',
+ },
{
type: 'code',
lang: 'html',
diff --git a/packages/cli/test/__golden__/no-icon-set/docs-topics.json b/packages/cli/test/__golden__/no-icon-set/docs-topics.json
index 2552288849b42..7e5643f9bad4d 100644
--- a/packages/cli/test/__golden__/no-icon-set/docs-topics.json
+++ b/packages/cli/test/__golden__/no-icon-set/docs-topics.json
@@ -117,7 +117,7 @@
"supporting-older-browsers",
"how-these-tiers-move-over-time"
],
- "skeleton": "463a740e90118dea23181c46a2cca01695d9295027863282835518f0bd655bdb",
+ "skeleton": "5aafc0d8f21d2f2961fb98ee722499ec146ae6cac841b036e019c03e4cdf8073",
"mentions": []
},
"color": {
diff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjs
index 06e163571d801..938e58de65d2c 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. 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`).",
+ "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. In Safari on iOS the content rides UIKit\u2019s keyboard motion, up from Safari\u2019s report and down from the blur (`astryx docs browser-support`).",
default: "'capped'",
},
{
diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsx
index a4fbe47969fa8..396a16e3f539c 100644
--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx
@@ -37,9 +37,16 @@ import {getFocusableElements} from '../hooks/useFocusTrap';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
import {__focusTakeoverCallersForTest} from '../keyboard/keyboardHeight';
import {__resetRevealsAtReportForTest} from '../keyboard/useMobileKeyboard';
-import {getKeyboardLayoutGuide} from '../keyboard/keyboardLayoutGuide';
+import {
+ getKeyboardLayoutGuide,
+ keyboardProfileOf,
+} from '../keyboard/keyboardLayoutGuide';
import {animatorFor} from '../motion/animator';
-import {__loadTouchRuntimeForTest} from '../utils/touchRuntime';
+import {timing as uikitTiming} from '../motion/uikit/timing';
+import {
+ __loadTouchRuntimeForTest,
+ __resetTouchRuntimeForTest,
+} from '../utils/touchRuntime';
// These cases drive touch motion, which comes with the shared touch runtime
// once the page has loaded it.
@@ -194,6 +201,13 @@ function mockIOSWebKit() {
maxTouchPoints: {configurable: true, value: 5},
});
vi.stubGlobal('navigator', navigatorMock);
+ // WebKit on iOS: the one engine with -webkit-touch-callout. The keyboard
+ // layout guide reads UIKit's keyboard schedule from it.
+ vi.stubGlobal('CSS', {
+ ...globalThis.CSS,
+ supports: (property: string, value?: string) =>
+ property === '-webkit-touch-callout' && value === 'none',
+ });
mockPrimaryPointer('coarse');
}
@@ -2905,6 +2919,40 @@ describe('BottomSheet', () => {
expect(body.scrollTop).toBe(248);
});
+ it('keeps its room and scroll when the touch runtime loads with the keyboard up', async () => {
+ __resetTouchRuntimeForTest();
+ const subscribe = vi.spyOn(getKeyboardLayoutGuide(window), 'subscribe');
+ try {
+ const {body, content, input, report} = renderChromeSheet({
+ instantScrollBy: true,
+ });
+ const attaches = subscribe.mock.calls.length;
+ act(() => input.focus());
+ report(500);
+ expect(keyboardInsetOf(body)).toBe(348);
+ expect(body.scrollTop).toBe(248);
+ const seen: [number, number][] = [];
+ const observer = new MutationObserver(() =>
+ seen.push([keyboardInsetOf(body), body.scrollTop]),
+ );
+ observer.observe(body, {attributes: true, subtree: true});
+ await act(async () => {
+ await __loadTouchRuntimeForTest();
+ });
+ await afterTheSlide();
+ observer.disconnect();
+ // The runtime's load attached the sheet again.
+ expect(subscribe.mock.calls.length).toBeGreaterThan(attaches);
+ expect(keyboardInsetOf(body)).toBe(348);
+ expect(body.scrollTop).toBe(248);
+ expect(content.style.translate).toBe('');
+ expect(seen.filter(([inset]) => inset !== 348)).toEqual([]);
+ } finally {
+ subscribe.mockRestore();
+ await __loadTouchRuntimeForTest();
+ }
+ });
+
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,
@@ -3121,13 +3169,13 @@ describe('BottomSheet', () => {
});
});
- 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.
+ it('subscribes no keyboard layout guide where the browser has no keyboard schedule, as Firefox for Android (spec:AST-099 FR8)', () => {
+ // Firefox for Android has neither the VirtualKeyboard API nor UIKit's
+ // keyboard, 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();
+ mockPrimaryPointer('coarse');
const guide = getKeyboardLayoutGuide(window);
const subscribe = vi.spyOn(guide, 'subscribe');
render(
@@ -3680,6 +3728,19 @@ describe('BottomSheet', () => {
});
describe('in iOS Safari, which reports the keyboard once it is gone (spec:AST-099 FR3)', () => {
+ // jsdom dates events on the epoch clock, but a browser dates them on
+ // performance.now()'s, which the keyboard guide reads them against.
+ let eventTime: {mockRestore: () => void} | null = null;
+ beforeEach(() => {
+ eventTime = vi
+ .spyOn(Event.prototype, 'timeStamp', 'get')
+ .mockImplementation(() => performance.now());
+ });
+ afterEach(() => {
+ eventTime?.mockRestore();
+ eventTime = null;
+ });
+
// A Tall sheet in iOS Safari: a visual viewport, no keyboard geometry
// API, and a coarse pointer. Its body, from top 100 to bottom 800, holds
// 800 px of content and the room after it. A reveal's scroll lands at
@@ -3757,15 +3818,175 @@ describe('BottomSheet', () => {
act(async () => {
await new Promise(resolve => requestAnimationFrame(resolve));
});
+ // A blur to nothing decides the hide on the next task, dated at the blur.
+ const afterTheBlur = async () =>
+ act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ });
const afterTheHide = async () =>
act(async () => {
await new Promise(resolve => setTimeout(resolve, 450));
});
+ // UIKit's keyboard spring lands at the notification's duration.
+ const afterTheShow = afterTheHide;
+
+ it('rides the content up from Safari\u2019s report on UIKit\u2019s keyboard spring, through the layout guide (spec:AST-099 FR8)', async () => {
+ const guide = getKeyboardLayoutGuide(window);
+ const subscribe = vi.spyOn(guide, 'subscribe');
+ const {body, input, report, drawnTop} = renderIOSSheet();
+ expect(subscribe).toHaveBeenCalled();
+ act(() => input.focus());
+ report(500);
+ const {start, curve} = guide.transition;
+ expect(curve).toMatchObject({
+ durationMs: uikitTiming.keyboardNotificationMs,
+ progress: expect.any(Function),
+ });
+ // The room and the scroll land at the report. The content is drawn
+ // where it was, then rises with the keyboard a little each frame, and
+ // lands where the reveal puts it. No frame jumps.
+ expect(body.scrollTop).toBe(248);
+ expect(keyboardInsetOf(body)).toBe(348);
+ expect(drawnTop(start)).toBeCloseTo(0, 6);
+ const samples = Array.from({length: 25}, (_, frame) =>
+ drawnTop(start + frame * 16),
+ );
+ for (let frame = 1; frame < samples.length; frame += 1) {
+ const step = (samples[frame] ?? 0) - (samples[frame - 1] ?? 0);
+ expect(step).toBeLessThanOrEqual(0.01);
+ expect(step).toBeGreaterThan(-40);
+ }
+ expect(drawnTop(start + uikitTiming.keyboardNotificationMs)).toBe(-248);
+ await afterTheShow();
+ expect(drawnTop()).toBe(-248);
+ subscribe.mockRestore();
+ });
+
+ it('keeps the field\u2019s resting place when a reveal runs after a long task mid-ride, though WebKit keeps the ridden rects from before the task', async () => {
+ const guide = getKeyboardLayoutGuide(window);
+ const {body, content, input, report, drawnTop} = renderIOSSheet();
+ act(() => input.focus());
+ report(500);
+ const {start} = guide.transition;
+ expect(body.scrollTop).toBe(248);
+ const sheet = body.parentElement as HTMLElement;
+ // The body and the content share the sheet as their offset parent,
+ // with the content at the body's top.
+ for (const element of [body, content]) {
+ Object.defineProperties(element, {
+ offsetParent: {configurable: true, get: () => sheet},
+ offsetTop: {configurable: true, get: () => 0},
+ });
+ }
+ // WebKit draws the ride on its compositor. The ridden content's rects
+ // keep the translate of the content's last style resolution, the frame
+ // after the report. Its computed translate follows the ride.
+ const drawn = (time: number) => animatorFor(content).get('y', time);
+ const frozen = drawn(start + 36);
+ vi.spyOn(content, 'getBoundingClientRect').mockImplementation(() =>
+ rect({
+ top: 100 - body.scrollTop + frozen,
+ bottom: 900 - body.scrollTop + frozen,
+ }),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>
+ rect({
+ top: 660 - body.scrollTop + frozen,
+ bottom: 700 - body.scrollTop + frozen,
+ }),
+ );
+ const contentStyles = new WeakSet();
+ const computedStyle = window.getComputedStyle.bind(window);
+ vi.spyOn(window, 'getComputedStyle').mockImplementation(
+ (element, pseudo) => {
+ const style = computedStyle(element, pseudo);
+ if (element === content) {
+ contentStyles.add(style);
+ }
+ return style;
+ },
+ );
+ const translate = Object.getOwnPropertyDescriptor(
+ CSSStyleDeclaration.prototype,
+ 'translate',
+ );
+ vi.spyOn(
+ CSSStyleDeclaration.prototype,
+ 'translate',
+ 'get',
+ ).mockImplementation(function (this: CSSStyleDeclaration): string {
+ return contentStyles.has(this)
+ ? `0px ${drawn(performance.now())}px`
+ : String(translate?.get?.call(this) ?? '');
+ });
+ // A long task holds the page until 286 ms into the slide. A reveal the
+ // sheet's observers scheduled before it runs then.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(start + 286);
+ act(() => input.setAttribute('data-long-task', ''));
+ await nextFrame();
+ now.mockRestore();
+ expect(body.scrollTop).toBe(248);
+ await afterTheShow();
+ expect(drawnTop()).toBe(-248);
+ });
+
+ it('moves nothing at rest when the content sits a fraction of a pixel off the whole-pixel offsets', async () => {
+ const {body, content, input, report} = renderIOSSheet();
+ act(() => input.focus());
+ report(500);
+ await afterTheShow();
+ expect(body.scrollTop).toBe(248);
+ const sheet = body.parentElement as HTMLElement;
+ // The content sits 25.5 px below the body's top. Its offset rounds to
+ // 26 px.
+ Object.defineProperties(body, {
+ offsetParent: {configurable: true, get: () => sheet},
+ offsetTop: {configurable: true, get: () => 0},
+ });
+ Object.defineProperties(content, {
+ offsetParent: {configurable: true, get: () => sheet},
+ offsetTop: {configurable: true, get: () => 26},
+ });
+ vi.spyOn(content, 'getBoundingClientRect').mockImplementation(() =>
+ rect({top: 125.5 - body.scrollTop, bottom: 925.5 - body.scrollTop}),
+ );
+ act(() => input.setAttribute('data-content-change', ''));
+ await nextFrame();
+ expect(body.scrollTop).toBe(248);
+ });
+
+ it('rides once the touch runtime loads, for a sheet that opened before it', async () => {
+ __resetTouchRuntimeForTest();
+ try {
+ const {input, report, drawnTop} = renderIOSSheet();
+ // Safari on iOS's keyboard schedule comes with the runtime.
+ expect(keyboardProfileOf(window)).toBeNull();
+ await act(async () => {
+ await __loadTouchRuntimeForTest();
+ });
+ expect(keyboardProfileOf(window)).toBe('uikit');
+ act(() => input.focus());
+ report(500);
+ const guide = getKeyboardLayoutGuide(window);
+ const {start} = guide.transition;
+ expect(guide.transition).toMatchObject({kind: 'show', to: 300});
+ // The content rises from where it was drawn, on the keyboard's spring.
+ expect(drawnTop(start)).toBeCloseTo(0, 6);
+ expect(drawnTop(start + 100)).toBeLessThan(-1);
+ expect(drawnTop(start + 100)).toBeGreaterThan(-248);
+ await afterTheShow();
+ expect(drawnTop()).toBe(-248);
+ } finally {
+ await __loadTouchRuntimeForTest();
+ }
+ });
it('rides the content down on the keyboard\u2019s spring from the blur, and the report then moves nothing', async () => {
const {body, content, input, report, drawnTop} = renderIOSSheet();
act(() => input.focus());
report(500);
+ await afterTheShow();
expect(body.scrollTop).toBe(248);
expect(keyboardInsetOf(body)).toBe(348);
expect(drawnTop()).toBe(-248);
@@ -3773,7 +3994,7 @@ describe('BottomSheet', () => {
// Done: the field loses focus to nothing, and the keyboard goes down.
const blurAt = performance.now();
act(() => input.blur());
- await nextFrame();
+ await afterTheBlur();
// Sampled every 16 ms through the keyboard's slide, the content moves
// down a little each frame. It lands where the scroll from before the
// keyboard draws it. No frame jumps.
@@ -3810,7 +4031,7 @@ describe('BottomSheet', () => {
report(500);
const settled = drawnTop();
act(() => input.blur());
- await nextFrame();
+ await afterTheBlur();
expect(drawnTop(performance.now() + 450)).toBe(settled);
report(800);
expect(keyboardInsetOf(body)).toBe(0);
@@ -3822,8 +4043,9 @@ describe('BottomSheet', () => {
});
act(() => input.focus());
report(500);
+ await afterTheShow();
act(() => input.blur());
- await nextFrame();
+ await afterTheBlur();
// The cross-fade lands the content on a timer, so the samples are
// read as the frames pass.
const animator = animatorFor(content);
@@ -3862,6 +4084,7 @@ describe('BottomSheet', () => {
});
act(() => input.focus());
report(500);
+ await afterTheShow();
const settled = drawnTop();
act(() => screen.getByLabelText('Picker').focus());
await nextFrame();
@@ -3910,6 +4133,7 @@ describe('BottomSheet', () => {
.appendChild(document.createElement('button'));
act(() => input.focus());
report(500);
+ await afterTheShow();
act(() => button.focus());
expect(document.activeElement).toBe(host);
await nextFrame();
@@ -3928,6 +4152,7 @@ describe('BottomSheet', () => {
.appendChild(document.createElement('button'));
act(() => input.focus());
report(500);
+ await afterTheShow();
// The browser runs the blur's frame after focus settles on the button.
const frames: FrameRequestCallback[] = [];
vi.mocked(requestAnimationFrame).mockImplementation(callback => {
@@ -3954,6 +4179,7 @@ describe('BottomSheet', () => {
renderWithHiddenField(kind);
act(() => input.focus());
report(500);
+ await afterTheShow();
const settled = drawnTop();
focusHiddenField();
await nextFrame();
@@ -3967,8 +4193,9 @@ describe('BottomSheet', () => {
const {body, input, report, drawnTop} = renderIOSSheet();
act(() => input.focus());
report(500);
+ await afterTheShow();
act(() => input.blur());
- await nextFrame();
+ await afterTheBlur();
// Focus comes back to the field mid-slide, so the keyboard stays.
act(() => input.focus());
await nextFrame();
@@ -3984,8 +4211,9 @@ describe('BottomSheet', () => {
renderWithHiddenField(kind);
act(() => input.focus());
report(500);
+ await afterTheShow();
act(() => input.blur());
- await nextFrame();
+ await afterTheBlur();
// Focus moves to a field inside the holder mid-slide, so the
// keyboard stays.
focusHiddenField();
@@ -3996,10 +4224,11 @@ describe('BottomSheet', () => {
},
);
- it('glides the content to its new place when the keyboard goes while its field keeps focus, as a downward dismissal leaves it', () => {
+ it('glides the content to its new place when the keyboard goes while its field keeps focus, as a downward dismissal leaves it', async () => {
const {body, input, report, drawnTop} = renderIOSSheet();
act(() => input.focus());
report(500);
+ await afterTheShow();
expect(drawnTop()).toBe(-248);
// The clock holds still through the report, so the glide starts at
// `reportAt` however slowly the test runs.
@@ -4012,12 +4241,18 @@ describe('BottomSheet', () => {
} finally {
clock.mockRestore();
}
- expect(keyboardInsetOf(body)).toBe(0);
- expect(body.scrollTop).toBe(0);
// Drawn where it was at the report, then down on the keyboard's spring:
- // two frames in, it has hardly moved.
+ // two frames in, it has hardly moved. The room and the scroll stay
+ // through the ride.
+ expect(keyboardInsetOf(body)).toBe(348);
expect(drawnTop(reportAt + 32)).toBeLessThan(-200);
expect(drawnTop(reportAt + 450)).toBeCloseTo(0, 0);
+ // Once it lands, the room drops and the scroll goes back with the
+ // translate in one commit, so nothing drawn moves.
+ await afterTheHide();
+ expect(keyboardInsetOf(body)).toBe(0);
+ expect(body.scrollTop).toBe(0);
+ expect(drawnTop()).toBeCloseTo(0, 0);
});
});
diff --git a/packages/core/src/Chat/ChatLayout.doc.mjs b/packages/core/src/Chat/ChatLayout.doc.mjs
index 7d6ec5361e6c6..1e95685c67fee 100644
--- a/packages/core/src/Chat/ChatLayout.doc.mjs
+++ b/packages/core/src/Chat/ChatLayout.doc.mjs
@@ -6,7 +6,7 @@ export const docs = {
name: 'ChatLayout',
subComponentOf: 'Chat',
displayName: 'Chat Layout',
- description: 'Layout shell for full chat interfaces. Messages flow in normal page flow, composer is fixed to the bottom with a frosted glass dock. Set density (compact/balanced/spacious) to control spacing, message max-width, and blur layer sizing. Includes built-in auto-scroll, a "New messages" scroll-to-bottom button, and a frosted glass blur layer behind the composer. By default the layout root is the scroll container; pass scrollRef to delegate scrolling to a parent element or the document body. Where the visual viewport shrinks for the software keyboard, the composer stays on top of the keyboard, and a conversation at its newest message stays there. In Chrome on Android the composer rides Gboard\u2019s slides in step with them. In Safari on iOS (in the browser and as a home-screen app) and in Firefox for Android, it moves above the keyboard once the browser reports it. On a touch screen, in a top-level page, every way into the composer\u2019s text (a tap, the keyboard\u2019s previous and next buttons, Tab, the input\u2019s focus()) focuses it without scrolling the page; under a mouse or inside an iframe the browser\u2019s own focus applies. Where your page sets interactive-widget=resizes-content, Chrome on Android shrinks the page for the keyboard itself and the composer stays above it without moving (see the browser-support guide).',
+ description: 'Layout shell for full chat interfaces. Messages flow in normal page flow, composer is fixed to the bottom with a frosted glass dock. Set density (compact/balanced/spacious) to control spacing, message max-width, and blur layer sizing. Includes built-in auto-scroll, a "New messages" scroll-to-bottom button, and a frosted glass blur layer behind the composer. By default the layout root is the scroll container; pass scrollRef to delegate scrolling to a parent element or the document body. Where the visual viewport shrinks for the software keyboard, the composer stays on top of the keyboard, and a conversation at its newest message stays there. In Chrome on Android the composer rides Gboard\u2019s slides in step with them. In Safari on iOS (in the browser and as a home-screen app) it rides UIKit\u2019s keyboard motion, up from Safari\u2019s report and down from the blur. In Firefox for Android, it moves above the keyboard once the browser reports it. On a touch screen, in a top-level page, every way into the composer\u2019s text (a tap, the keyboard\u2019s previous and next buttons, Tab, the input\u2019s focus()) focuses it without scrolling the page; under a mouse or inside an iframe the browser\u2019s own focus applies. Where your page sets interactive-widget=resizes-content, Chrome on Android shrinks the page for the keyboard itself and the composer stays above it without moving (see the browser-support guide).',
props: [
{
name: 'children',
@@ -139,7 +139,7 @@ export const docsZh = {
export const docsDense = {
name: 'ChatLayout',
displayName: 'Chat Layout',
- description: 'layout shell for full chat; msgs in page flow, composer fixed bottom w/ frosted glass dock; density prop (default balanced); scrollRef delegates to parent/body; in Chrome on Android (Gboard) the composer rides the software keyboard in step; in Safari on iOS and Firefox for Android it moves above the keyboard once reported (Chrome with interactive-widget=resizes-content: the page resizes, no move); transcript stays at newest msg, on a touch screen in a top-level page every focus route (tap, prev/next, Tab, focus()) w/o page scroll and Done rests focus on the composer group (no name, ring after keyboard input only, no tab stop); under a mouse or in an iframe: plain wrapper, browser focus',
+ description: 'layout shell for full chat; msgs in page flow, composer fixed bottom w/ frosted glass dock; density prop (default balanced); scrollRef delegates to parent/body; in Chrome on Android (Gboard) the composer rides the software keyboard in step; in Safari on iOS it rides UIKit\u2019s keyboard motion, up from the report and down from the blur; in Firefox for Android it moves above the keyboard once reported (Chrome with interactive-widget=resizes-content: the page resizes, no move); transcript stays at newest msg, on a touch screen in a top-level page every focus route (tap, prev/next, Tab, focus()) w/o page scroll and Done rests focus on the composer group (no name, ring after keyboard input only, no tab stop); under a mouse or in an iframe: plain wrapper, browser focus',
usage: {
bestPractices: [
{guidance: true, description: 'Pass ChatMessageList as children and ChatComposer as composer prop for complete chat.'},
diff --git a/packages/core/src/Chat/useChatKeyboard.runtime.test.tsx b/packages/core/src/Chat/useChatKeyboard.runtime.test.tsx
new file mode 100644
index 0000000000000..4f5e9eb4f4bae
--- /dev/null
+++ b/packages/core/src/Chat/useChatKeyboard.runtime.test.tsx
@@ -0,0 +1,119 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useChatKeyboard.runtime.test.tsx
+ * @input vitest, Testing Library, ChatLayout alone on the page, the shared
+ * touch loader with its frame and idle callbacks under test control, a
+ * stand-in CSS.supports for WebKit on iOS
+ * @output Tests that ChatLayout, under a finger, schedules the touch
+ * runtime's load, so UIKit's keyboard schedule registers on a page with no
+ * other touch component, and that under a fine pointer it schedules nothing
+ * @position Unit tests for Chat/useChatKeyboard.ts and utils/touchRuntime.ts
+ * together; useChatKeyboard.test.tsx covers the ride itself
+ */
+
+import {act, render} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {ChatLayout} from './ChatLayout';
+import {
+ keyboardProfileOf,
+ registerUIKitKeyboardSchedule,
+} from '../keyboard/keyboardLayoutGuide';
+import {
+ __resetTouchRuntimeForTest,
+ getTouchRuntime,
+} from '../utils/touchRuntime';
+
+/** Lets the runtime module's `import()` settle. */
+async function settleImport(): Promise {
+ await vi.dynamicImportSettled();
+ await act(async () => {
+ await Promise.resolve();
+ });
+}
+
+describe('ChatLayout alone on a page in Safari on iOS', () => {
+ let frames: FrameRequestCallback[];
+ let idle: IdleRequestCallback[];
+
+ const stubPointer = (pointer: 'coarse' | 'fine') => {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: query === `(pointer: ${pointer})`,
+ media: query,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ }));
+ };
+
+ beforeEach(() => {
+ __resetTouchRuntimeForTest();
+ // No other component on the page has loaded the runtime.
+ registerUIKitKeyboardSchedule(null);
+ vi.useFakeTimers();
+ frames = [];
+ idle = [];
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
+ frames.push(callback);
+ return frames.length;
+ });
+ window.requestIdleCallback = vi.fn(callback => {
+ idle.push(callback);
+ return idle.length;
+ });
+ // WebKit on iOS is the one engine with -webkit-touch-callout.
+ vi.stubGlobal('CSS', {
+ supports: (property: string, value: string) =>
+ property === '-webkit-touch-callout' && value === 'none',
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ // @ts-expect-error -- jsdom has no requestIdleCallback of its own.
+ delete window.requestIdleCallback;
+ __resetTouchRuntimeForTest();
+ });
+
+ function paint(): void {
+ const pending = frames.splice(0);
+ for (const callback of pending) {
+ callback(performance.now());
+ }
+ vi.advanceTimersByTime(0);
+ }
+
+ function renderLayout() {
+ return render(
+ }>
+
Hello
+ ,
+ );
+ }
+
+ it('schedules the touch runtime under a finger, so UIKit’s keyboard schedule registers', async () => {
+ stubPointer('coarse');
+ renderLayout();
+ expect(keyboardProfileOf(window)).toBeNull();
+
+ // The loader waits for first paint, then for idle.
+ paint();
+ expect(idle).toHaveLength(1);
+ idle[0]({didTimeout: false, timeRemaining: () => 50});
+ await settleImport();
+
+ expect(getTouchRuntime()).not.toBeNull();
+ expect(keyboardProfileOf(window)).toBe('uikit');
+ });
+
+ it('schedules nothing under a fine pointer', async () => {
+ stubPointer('fine');
+ renderLayout();
+ paint();
+ await settleImport();
+ expect(idle).toHaveLength(0);
+ expect(getTouchRuntime()).toBeNull();
+ expect(keyboardProfileOf(window)).toBeNull();
+ });
+});
diff --git a/packages/core/src/Chat/useChatKeyboard.test.tsx b/packages/core/src/Chat/useChatKeyboard.test.tsx
index c97ec8e1bdf4f..df9e89f2e8e6d 100644
--- a/packages/core/src/Chat/useChatKeyboard.test.tsx
+++ b/packages/core/src/Chat/useChatKeyboard.test.tsx
@@ -7,8 +7,9 @@
* lift, the message area's room and the dock's ride down at a blur. It
* also covers the touches the composer claims, focus moves and Done's park
* on the composer group
- * @position Unit tests for Chat/useChatKeyboard.ts; the browser spec proves
- * Chrome's ride
+ * @position Unit tests for Chat/useChatKeyboard.ts. They cover Chrome's ride
+ * and Safari on iOS's ride on UIKit's keyboard spring. The browser spec
+ * proves Chrome's ride
*/
import fs from 'node:fs';
@@ -20,6 +21,8 @@ import {ChatComposer} from './ChatComposer';
import {ChatLayout} from './ChatLayout';
import {editableToClaim} from './useChatKeyboard';
import {getKeyboardLayoutGuide} from '../keyboard/keyboardLayoutGuide';
+import {timing as uikitTiming} from '../motion/uikit/timing';
+import {__loadTouchRuntimeForTest} from '../utils/touchRuntime';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
import {__focusTakeoverCallersForTest} from '../keyboard/keyboardHeight';
@@ -163,16 +166,24 @@ describe('ChatLayout and the software keyboard', () => {
});
};
- it('rides nothing without the VirtualKeyboard API, as in Safari on iOS: the layout follows the height alone', async () => {
- const guide = getKeyboardLayoutGuide(window);
- const subscribe = vi.spyOn(guide, 'subscribe');
+ // Safari on iOS: WebKit on iOS is the one engine with -webkit-touch-callout,
+ // and the guide publishes UIKit's keyboard spring there.
+ const stubUIKitKeyboard = async () => {
+ // UIKit's schedule comes with the touch runtime, which ChatLayout reads.
+ await __loadTouchRuntimeForTest();
+ vi.stubGlobal('CSS', {
+ supports: (property: string, value: string) =>
+ property === '-webkit-touch-callout' && value === 'none',
+ });
+ };
+
+ it('rides nothing without a keyboard schedule, as in Firefox for Android: the layout follows the height alone', async () => {
const {container} = renderLayout();
report(window.innerHeight - 300);
expect(dockOf(container).style.translate).toBe('');
await settle();
expect(layoutLift(dockOf(container))).toBe(300);
- expect(subscribe).not.toHaveBeenCalled();
- subscribe.mockRestore();
+ expect(dockOf(container).style.translate).toBe('');
});
it('attaches nothing of the ride under a fine pointer: the layout follows the height alone', async () => {
@@ -311,6 +322,52 @@ describe('ChatLayout and the software keyboard', () => {
expect(dockOf(container).style.translate).toBe('');
});
+ it('rides the dock up from Safari’s one report on UIKit’s keyboard spring, in Safari on iOS (spec:AST-099 FR8)', async () => {
+ await stubUIKitKeyboard();
+ const guide = getKeyboardLayoutGuide(window);
+ const subscribe = vi.spyOn(guide, 'subscribe');
+ const {container} = renderLayout();
+ const field = screen.getByRole('textbox', {name: 'Message'});
+ act(() => field.focus());
+ report(window.innerHeight - 300);
+ expect(subscribe).toHaveBeenCalled();
+ expect(guide.transition).toMatchObject({kind: 'show', to: 300});
+ expect(guide.transition.curve).toMatchObject({
+ durationMs: uikitTiming.keyboardNotificationMs,
+ progress: expect.any(Function),
+ });
+ await settle();
+ expect(layoutLift(dockOf(container))).toBe(300);
+ expect(dockOf(container).style.translate).toBe('');
+ subscribe.mockRestore();
+ });
+
+ it('rides the dock down from the blur on the same spring, ahead of Safari’s report of the keyboard down, in Safari on iOS', async () => {
+ await stubUIKitKeyboard();
+ const {container} = renderLayout();
+ const field = screen.getByRole('textbox', {name: 'Message'});
+ act(() => field.focus());
+ report(window.innerHeight - 300);
+ await settle();
+ act(() => field.blur());
+ // A blur to nothing decides the hide on the next task, dated at the blur.
+ await settle();
+ expect(getKeyboardLayoutGuide(window).transition).toMatchObject({
+ kind: 'hide',
+ to: 0,
+ predicted: true,
+ });
+ // Safari reports the keyboard down only once it is gone. The layout keeps
+ // its lift until then, and the ride takes the dock down on top of it.
+ expect(layoutLift(dockOf(container))).toBe(300);
+ expect(dockOf(container).style.translate).toBe('0px 300px');
+ report(window.innerHeight);
+ await settle();
+ expect(layoutLift(dockOf(container))).toBe(0);
+ expect(keyboardRoom(messagesOf())).toBe(0);
+ expect(dockOf(container).style.translate).toBe('');
+ });
+
it('keeps the lift when the page is pinch-zoomed past 2x with the keyboard up', async () => {
// WebKit reports innerWidth and innerHeight in the zoomed visual
// viewport's px. At 2x, innerHeight alone reads no keyboard, and the dock
diff --git a/packages/core/src/Chat/useChatKeyboard.ts b/packages/core/src/Chat/useChatKeyboard.ts
index 7648f01a8b9fc..1724d626d9fdd 100644
--- a/packages/core/src/Chat/useChatKeyboard.ts
+++ b/packages/core/src/Chat/useChatKeyboard.ts
@@ -33,12 +33,14 @@ import {
} from '../keyboard/keyboardLayoutGuide';
import {
deliverTap,
+ followTouchRuntimeKeyboardSchedule,
followsKeyboard,
watchPans,
} from '../keyboard/keyboardTarget';
import type {KeyboardTransition} from '../keyboard/keyboardModel';
import {rideKeyboard} from '../keyboard/rideKeyboard';
import {layoutViewportHeight} from '../utils/layoutViewport';
+import {scheduleTouchRuntimeLoad} from '../utils/touchRuntime';
import {
useInteractionModalityTrackingFor,
type InteractionModality,
@@ -262,6 +264,12 @@ export function useChatKeyboard({
// keyboard's own motion. These are values, not motion roles, since the
// system moves the keyboard on them whatever the page does.
const follow = (transition: KeyboardTransition) => {
+ // Without a keyboard schedule, the layout follows the height alone.
+ // Safari on iOS's schedule arrives with the touch runtime, so the guide
+ // is followed from the mount and rides once it has one.
+ if (keyboardProfileOf(win) == null) {
+ return;
+ }
// The ride: the dock goes where the guide says the keyboard will be,
// from the keyboard's start, relative to the layout it rests in now.
const target = liftRef.current - liftFor(transition.to);
@@ -318,12 +326,16 @@ export function useChatKeyboard({
.catch(() => undefined);
};
// The ride attaches only under a coarse primary pointer, where the guide
- // publishes the keyboard's own slide: Gboard's, in Chrome on Android.
- // Elsewhere the layout follows the height alone.
- const unsubscribe =
- isTouch && keyboardProfileOf(win) === 'chromium'
- ? getKeyboardLayoutGuide(win).subscribe(follow)
- : undefined;
+ // publishes the keyboard's own motion: Gboard's slide in Chrome on Android,
+ // and UIKit's keyboard spring in Safari on iOS. UIKit's schedule comes with
+ // the touch runtime, so the layout schedules the page's one load of it.
+ if (isTouch) {
+ followTouchRuntimeKeyboardSchedule();
+ scheduleTouchRuntimeLoad();
+ }
+ const unsubscribe = isTouch
+ ? getKeyboardLayoutGuide(win).subscribe(follow)
+ : undefined;
// A height change the guide has no ride for, as for a resize or a
// rotation, takes its lift at once. This listener comes after the guide's,
// so a ride claims the change first.
diff --git a/packages/core/src/keyboard/README.md b/packages/core/src/keyboard/README.md
index ee3b113789ad0..2501a82df0bbc 100644
--- a/packages/core/src/keyboard/README.md
+++ b/packages/core/src/keyboard/README.md
@@ -132,33 +132,36 @@ that times motion with it. Everything here is internal to
`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
+ guide publishes the keyboard's own motion (Gboard's slides in Chrome on
+ Android, UIKit's keyboard spring in Safari on iOS), the sheet rides it
+ (FR8). A reveal during the show scrolls the body at once, and the content
+ box rides the show's curve from where it was drawn. It reads the ride's
+ offset from the content box's own rect, as WebKit can keep a composited
+ box's rects from its last style resolution. In Chrome, the same
+ commit first sets the content box so the field sits 4 px above the
+ keyboard's top (DEC-6). 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. A busy page reads Chrome's
report of the keyboard gone after the slide. Until then the content box
stays where the slide leaves it, and that report commits. Under a fine
pointer nothing of
the ride attaches: no guide subscription, and the inset follows the
- reports. A browser without the VirtualKeyboard API (iOS Safari, Firefox for
- Android) publishes no slide: iOS Safari reports the keyboard gone about half
- a second after a blur, once it is down. There, under a coarse pointer, a
- blur that takes the keyboard down rides the content box to where the body's
- scroll rests, on UIKit's keyboard spring (`KEYBOARD_SPRING`) from the blur,
- while the inset stays. The report then drops the inset and puts the scroll
- back in one commit with the translate, so nothing moves. A report of the
- keyboard gone with no ride under way, as after a downward dismissal, glides
- the content to its place on the same spring. A field focused before the
- keyboard is down rides it back up. Focus moving to a select starts no ride:
- iOS puts the select's picker where the keyboard was. Nor does focus moving
- to a field inside an open shadow root, or into a frame or a custom element
- whose field the page cannot see. A plain control inside an open shadow root
- rides as any control does. Firefox for Android takes the same path, but
- reports the hide once, at its end, and the content moves at that report
- (AST-099 Gap 12). Safari's and Firefox's reveals are unchanged.
+ reports. Safari on iOS reports the keyboard gone about half a second after
+ a blur, once it is down, so there the guide starts the hide at the blur, on
+ UIKit's keyboard spring (`KEYBOARD_SPRING`). Safari's report then drops the
+ inset and puts the scroll back in one commit with the translate, so nothing
+ moves. A report of the keyboard gone with no blur before it, as after a
+ downward dismissal, rides the content to its place on the same spring. A
+ field focused before the keyboard is down rides it back up. Focus moving to
+ a select starts no ride: iOS puts the select's picker where the keyboard
+ was. Nor does focus moving to a field inside an open shadow root, or into a
+ frame or a custom element whose field the page cannot see. A plain control
+ inside an open shadow root rides as any control does. A browser with
+ neither schedule, such as Firefox for Android, publishes no slide. There,
+ under a coarse pointer, a blur that takes the keyboard down rides the
+ content box on UIKit's keyboard spring from the blur while the inset stays,
+ but Firefox reports the hide once, at its end, and the content moves at that
+ report (AST-099 Gap 12). Safari's and Firefox's reveals are unchanged.
- **When the keyboard goes:** the body's scroll goes back to where it 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
@@ -186,7 +189,8 @@ Each transition is
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
+Android or UIKit's keyboard spring, cut at the notification's duration, in
+Safari on iOS, 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
@@ -264,28 +268,57 @@ keyboard module measures them from the visual viewport, as in every browser
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).
+## What the page sees (Safari on iOS)
+
+The guide reads UIKit's keyboard schedule where WebKit on iOS runs
+(`keyboardProfileOf`: the engine's `-webkit-touch-callout` support, never the
+user agent). The schedule (`uikitKeyboardSchedule.ts`) comes with the touch
+runtime, which the page loads after its first paint, so a page that never
+loads it carries none of it. Until it loads, Safari on iOS rides nothing, as
+before. The keyboard riders register it with the guide
+(`followTouchRuntimeKeyboardSchedule`), and give it what the page's first load
+already holds: the notification duration, `mayKeepKeyboard` and `isElement`.
+So the schedule imports only the spring's table and the spring solver. The
+curve is UIKit's own keyboard frame animation, `../motion/uikit/springs.ts`'s
+`KEYBOARD_SPRING` (critically damped), cut at the duration the keyboard
+notifications report (`../motion/uikit/timing.ts`'s `keyboardNotificationMs`).
+
+- Show: Safari sends one `resize` of the visual viewport, as the keyboard
+ starts up. The guide rides UIKit's spring from it. Safari reports the
+ keyboard with its accessory bar in one height, so the guide predicts no
+ second height.
+- Hide: Safari reports the keyboard gone only once it is down. The guide
+ starts the hide at the blur, as a prediction that report confirms. Its
+ check after the spring keeps the hide while Safari still reads the keyboard
+ up. A hide with no blur before it rides from Safari's report.
+- Focus that moves into a frame, a custom element or an open shadow root
+ waits until focus settles there. A field there can keep the keyboard up, so
+ the guide predicts no hide, and turns a predicted hide back up.
+
## 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).
+ focused field in the keyboard report's own event, and rides the content box
+ on the keyboard's own motion, Gboard's slides in Chrome and UIKit's spring
+ in Safari on iOS (`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. |
-| `keyboardTarget.ts` | The targets: their registry, a docked or scrolling target, and a field's own path. |
-| `revealBand.ts` | `distanceIntoBand`: the scroll that brings a box inside a band, shared by the field's and the sheet's reveals. |
-| `keyboardModel.ts` | The clock-free core of the guide: transitions from keyboard reports and focus changes. |
-| `keyboardLayoutGuide.ts` | One guide per window, fed by the keyboard module: the verification timer, the focus handoff. |
-| `rideKeyboard.ts` | Moves an element with the keyboard on the curve its transition publishes, or at once (tests: `rideKeyboard.test.ts`). |
-| `index.ts` | Entry point. |
+| 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. |
+| `keyboardTarget.ts` | The targets: their registry, a docked or scrolling target, and a field's own path. |
+| `revealBand.ts` | `distanceIntoBand`: the scroll that brings a box inside a band, shared by the field's and the sheet's reveals. |
+| `keyboardModel.ts` | The clock-free core of the guide: transitions from keyboard reports and focus changes. |
+| `keyboardLayoutGuide.ts` | One guide per window, fed by the keyboard module: the verification timer, the focus handoff. |
+| `rideKeyboard.ts` | Moves an element with the keyboard on the curve its transition publishes, or at once (tests: `rideKeyboard.test.ts`). |
+| `uikitKeyboardSchedule.ts` | Safari on iOS's schedule, which the touch runtime publishes and the keyboard riders register with the guide. |
+| `index.ts` | Entry point. |
The timing constants live in `../motion/android/keyboard.ts` (Chrome with
-Gboard).
+Gboard) and in `../motion/uikit/springs.ts` and `../motion/uikit/timing.ts`
+(UIKit's keyboard in Safari on iOS).
diff --git a/packages/core/src/keyboard/keyboardLayoutGuide.ts b/packages/core/src/keyboard/keyboardLayoutGuide.ts
index 1bfca2baff47d..450adb68d2138 100644
--- a/packages/core/src/keyboard/keyboardLayoutGuide.ts
+++ b/packages/core/src/keyboard/keyboardLayoutGuide.ts
@@ -25,20 +25,88 @@ import {
type KeyboardModel,
type KeyboardProfile,
type KeyboardTransition,
+ type KeyboardCurveSchedule,
} from './keyboardModel';
-import {sharedWeakMap} from '../utils/sharedRealm';
+import {isElement} from '../utils/nodeType';
+import {sharedState, sharedWeakMap} from '../utils/sharedRealm';
/**
- * 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.
+ * The rules a keyboard schedule gives the guide for focus that moves to a
+ * field the page cannot see.
+ */
+export interface KeyboardFocusRules {
+ /** Focus moved: true when the focused element may keep a keyboard up. */
+ readonly focused: () => boolean;
+ /**
+ * A field lost focus to `next` at `blurAt`: true when the rules decide the
+ * hide later, through the guide's `hide`.
+ */
+ readonly blurred: (next: EventTarget | null, blurAt: number) => boolean;
+ /** Stops anything the rules wait for. */
+ readonly dispose: () => void;
+}
+
+/** The guide's own field check, which a schedule's focus rules use. */
+export interface KeyboardFocusChecks {
+ readonly hidesField: (target: Element) => boolean;
+}
+
+/**
+ * Safari on iOS's keyboard schedule, with the windows it applies to and the
+ * focus rules the guide follows under it.
+ */
+export interface UIKitKeyboardSchedule extends KeyboardCurveSchedule {
+ readonly appliesTo: (win: Window) => boolean;
+ readonly focusRules: (
+ win: Window,
+ hide: (blurAt: number) => void,
+ checks: KeyboardFocusChecks,
+ ) => KeyboardFocusRules;
+}
+
+// Where the guide reads Safari on iOS's schedule. The touch runtime publishes
+// the schedule, and a keyboard rider registers this reader as it attaches
+// (keyboardTarget.ts).
+const uikit = sharedState(
+ 'keyboard/keyboard-layout-guide/uikit-schedule',
+ 2,
+ (): {read: (() => UIKitKeyboardSchedule | null) | null} => ({read: null}),
+);
+
+/**
+ * Registers how the guide reads Safari on iOS's keyboard schedule; null
+ * forgets it. Until the reader returns a schedule, no surface rides the
+ * keyboard in Safari on iOS, as before the ride.
+ */
+export function registerUIKitKeyboardSchedule(
+ read: (() => UIKitKeyboardSchedule | null) | null,
+): void {
+ uikit.read = read;
+}
+
+const uikitScheduleOf = (): UIKitKeyboardSchedule | null =>
+ uikit.read?.() ?? null;
+
+/**
+ * Whose keyboard schedule the guide reads. `chromium`: the browser has the
+ * VirtualKeyboard API. `uikit`: Safari on iOS or iPadOS, once the touch
+ * runtime gives the guide UIKit's schedule. Otherwise null. Without the
+ * profile, no surface rides the guide. Chrome reports the keyboard as each
+ * slide starts, and Safari reports its show as UIKit's keyboard starts up.
+ * The profile is a capability, never the user agent.
*/
export function keyboardProfileOf(win: Window): KeyboardProfile | null {
- return hasVirtualKeyboard(win) ? 'chromium' : null;
+ if (hasVirtualKeyboard(win)) {
+ return 'chromium';
+ }
+ return uikitScheduleOf()?.appliesTo(win) === true ? 'uikit' : null;
}
+// The schedule the guide's model reads under `profile`. Chrome's is the
+// model's own.
+const scheduleOf = (profile: KeyboardProfile | null) =>
+ profile === 'uikit' ? (uikitScheduleOf() ?? undefined) : undefined;
+
/** A window's keyboard layout guide. */
export interface KeyboardLayoutGuide {
/** The inset the keyboard rests at (or is heading to), CSS px. */
@@ -130,21 +198,24 @@ const guides = sharedWeakMap(
* 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.
+ * The model reads the profile's schedule. Chrome reports each slide just
+ * after it starts, and Safari reports its show as UIKit's keyboard starts
+ * up. A surface rides the guide only where it has a profile. 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.
*
* A busy page reads Chrome's reports late, after Gboard's slide. So once a
* hide predicted from a blur is under way, a report of the keyboard partway
* down, or still up, starts nothing. Only the report of the keyboard gone
- * confirms the hide. Focus that comes back still turns it around. Focus in a
- * frame, an open shadow host or a custom element can keep up a keyboard the
- * guide cannot see. There the viewport decides, as before. A closed shadow
- * root on a built-in element reads as nothing focused.
+ * confirms the hide. Focus that comes back still turns it around. A field in
+ * a frame, an open shadow host or a custom element can keep up a keyboard
+ * the guide cannot see. Under the `uikit` profile, focus that moves there
+ * predicts no hide, and Safari's report decides. Under the `chromium`
+ * profile, the blur still predicts the hide, and the check after the slide
+ * turns it back while the keyboard stays up. A closed shadow root on a
+ * built-in element reads as nothing focused.
*
* @example
* ```
@@ -166,7 +237,10 @@ export function getKeyboardLayoutGuide(win: Window): KeyboardLayoutGuide {
function createGuide(win: Window): KeyboardLayoutGuide {
const listeners = new Set<(transition: KeyboardTransition) => void>();
let profile = keyboardProfileOf(win);
- let model: KeyboardModel = createKeyboardModel(getKeyboardHeight(win));
+ let model: KeyboardModel = createKeyboardModel(
+ getKeyboardHeight(win),
+ scheduleOf(profile),
+ );
let verifyTimer: ReturnType | null = null;
let detach: (() => void) | null = null;
// Whether focusing `target` keeps an input view where the keyboard is. On
@@ -220,8 +294,35 @@ function createGuide(win: Window): KeyboardLayoutGuide {
};
const attach = () => {
- profile = keyboardProfileOf(win);
- model = createKeyboardModel(getKeyboardHeight(win));
+ let rules: KeyboardFocusRules | null = null;
+ let synced = false;
+ // The schedule follows the profile, which changes once the touch runtime
+ // registers UIKit's schedule.
+ const sync = () => {
+ const next = keyboardProfileOf(win);
+ if (synced && next === profile) {
+ return;
+ }
+ synced = true;
+ profile = next;
+ model = createKeyboardModel(getKeyboardHeight(win), scheduleOf(profile));
+ rules?.dispose();
+ rules =
+ profile === 'uikit'
+ ? (uikitScheduleOf()?.focusRules(
+ win,
+ blurAt => publish(model.blurred(blurAt)),
+ {hidesField},
+ ) ?? null)
+ : null;
+ };
+ sync();
+ // A field in a shadow root or a custom element blurs with its host as the
+ // target. So does a frame's field once focus leaves the frame. Under
+ // UIKit's rules that blur waits as a field's does, and the element that
+ // focus settles on decides.
+ const leavesHiddenField = (target: EventTarget | null): boolean =>
+ rules != null && isElement(target) && hidesField(target);
// When a field that brings up a keyboard last gained focus.
let keyboardFocusAt = -Infinity;
let handoffTimer: ReturnType | null = null;
@@ -256,16 +357,21 @@ function createGuide(win: Window): KeyboardLayoutGuide {
return model.report(height, time);
};
const onReport = (event: KeyboardHeightEvent) => {
+ sync();
if (event.type === 'viewport') {
publish(report(event.height, event.timeStamp));
} else if (event.type === 'focusin') {
+ const keeps = rules?.focused() ?? false;
if (keepsInputView(event.target)) {
keyboardFocusAt = event.timeStamp;
publish(model.focused(event.timeStamp));
+ } else if (keeps) {
+ publish(model.focused(event.timeStamp));
}
} else if (
- keepsInputView(event.target) &&
- !keepsInputView(event.relatedTarget)
+ (keepsInputView(event.target) || leavesHiddenField(event.target)) &&
+ !keepsInputView(event.relatedTarget) &&
+ rules?.blurred(event.relatedTarget, event.timeStamp) !== true
) {
publish(model.blurred(event.timeStamp));
}
@@ -273,6 +379,7 @@ function createGuide(win: Window): KeyboardLayoutGuide {
const unsubscribe = subscribeKeyboardHeight(win, onReport, {focus: true});
return () => {
unsubscribe();
+ rules?.dispose();
if (handoffTimer != null) {
clearTimeout(handoffTimer);
handoffTimer = null;
diff --git a/packages/core/src/keyboard/keyboardModel.test.ts b/packages/core/src/keyboard/keyboardModel.test.ts
index d6b437227ca93..81456e23c37d7 100644
--- a/packages/core/src/keyboard/keyboardModel.test.ts
+++ b/packages/core/src/keyboard/keyboardModel.test.ts
@@ -6,7 +6,9 @@
* @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.
+ * report, and focus that comes back during a predicted hide. On iOS,
+ * transitions ride UIKit's keyboard spring from Safari's report and from
+ * the blur.
* @position Unit tests for keyboard/keyboardModel.ts
*/
@@ -14,6 +16,17 @@ import {describe, expect, it} from 'vitest';
import {createKeyboardModel} from './keyboardModel';
import {keyboard as androidKeyboard} from '../motion/android';
import {cubicBezier} from '../motion/bezier';
+import {KEYBOARD_SPRING} from '../motion/uikit/springs';
+import {timing as uikitTiming} from '../motion/uikit/timing';
+import {isElement} from '../utils/nodeType';
+import {mayKeepKeyboard} from './keyboardTarget';
+import {createUIKitKeyboardSchedule} from './uikitKeyboardSchedule';
+
+const uikitKeyboardSchedule = createUIKitKeyboardSchedule({
+ notificationMs: uikitTiming.keyboardNotificationMs,
+ mayKeepKeyboard,
+ isElement,
+});
describe('createKeyboardModel on Chrome', () => {
const ease = cubicBezier(androidKeyboard.hideCurve);
@@ -100,3 +113,82 @@ describe('createKeyboardModel on Chrome', () => {
expect(back?.curve?.durationMs).toBe(androidKeyboard.showMs);
});
});
+
+describe('createKeyboardModel on iOS Safari', () => {
+ const safari = () => createKeyboardModel(0, uikitKeyboardSchedule);
+ // UIKit's keyboard spring is critically damped: 1 − (1 + ω₀t)·e^(−ω₀t).
+ const omega = Math.sqrt(KEYBOARD_SPRING.stiffness / KEYBOARD_SPRING.mass);
+ const progress = (ms: number) =>
+ 1 - (1 + (omega * ms) / 1000) * Math.exp((-omega * ms) / 1000);
+ const span = uikitTiming.keyboardNotificationMs;
+
+ it('rides a keyboard coming up from Safari’s one report, on UIKit’s keyboard spring cut at the notification’s duration (FR8)', () => {
+ const model = safari();
+ const show = model.report(336, 1000);
+ expect(show).toMatchObject({
+ kind: 'show',
+ from: 0,
+ to: 336,
+ start: 1000,
+ animated: true,
+ predicted: false,
+ curve: uikitKeyboardSchedule.curve,
+ });
+ expect(model.presentation(1000)).toBe(0);
+ expect(model.presentation(1100)).toBeCloseTo(336 * progress(100), 6);
+ expect(model.presentation(1200)).toBeCloseTo(336 * progress(200), 6);
+ // Core Animation cuts the spring at the notification's duration.
+ expect(model.presentation(1000 + span)).toBe(336);
+ });
+
+ it('takes Safari’s one report as the keyboard’s own height, accessory bar included, with no prediction', () => {
+ const model = safari();
+ model.report(336, 1000);
+ model.report(0, 2000);
+ const show = model.report(290, 3000);
+ expect(show).toMatchObject({kind: 'show', to: 290, predicted: false});
+ });
+
+ it('rides a hide down from the blur on the same spring, and Safari’s report once the keyboard is down confirms it (FR3)', () => {
+ const model = safari();
+ model.report(336, 1000);
+ const hide = model.blurred(2000);
+ expect(hide).toMatchObject({
+ kind: 'hide',
+ from: 336,
+ to: 0,
+ start: 2000,
+ animated: true,
+ predicted: true,
+ curve: uikitKeyboardSchedule.curve,
+ });
+ expect(model.presentation(2100)).toBeCloseTo(336 * (1 - progress(100)), 6);
+ expect(model.presentation(2000 + span)).toBe(0);
+ // Safari reports the hide about half a second after the blur.
+ expect(model.report(0, 2500)).toBeNull();
+ expect(model.transition.predicted).toBe(false);
+ });
+
+ it('rides a hide no blur predicted down from Safari’s report, never at once', () => {
+ const model = safari();
+ model.report(336, 1000);
+ const hide = model.report(0, 2000);
+ expect(hide).toMatchObject({
+ kind: 'hide',
+ to: 0,
+ start: 2000,
+ animated: true,
+ curve: {durationMs: span},
+ });
+ });
+
+ it('turns back up on the spring when focus returns during a hide it predicted', () => {
+ const model = safari();
+ model.report(336, 1000);
+ model.blurred(2000);
+ const back = model.focused(2100);
+ expect(back).toMatchObject({kind: 'show', to: 336, animated: true});
+ expect(back?.from).toBeCloseTo(336 * (1 - progress(100)), 6);
+ expect(back?.curve).toBe(uikitKeyboardSchedule.curve);
+ });
+});
diff --git a/packages/core/src/keyboard/keyboardModel.ts b/packages/core/src/keyboard/keyboardModel.ts
index 9e411170dd67c..056062444e934 100644
--- a/packages/core/src/keyboard/keyboardModel.ts
+++ b/packages/core/src/keyboard/keyboardModel.ts
@@ -3,7 +3,8 @@
/**
* @file keyboardModel.ts
* @input `keyboard` from the Android table: Gboard's slides and Chrome's
- * report timings
+ * report timings. A schedule the caller passes, as the touch runtime's UIKit
+ * schedule (uikitKeyboardSchedule.ts)
* @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).
@@ -16,17 +17,47 @@
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';
+/**
+ * Which keyboard's reports the guide reads: Gboard's in Chrome, or UIKit's in
+ * Safari on iOS.
+ */
+export type KeyboardProfile = 'chromium' | 'uikit';
-/** An eased slide: the curve a transition plays (Gboard going up or down). */
-export interface KeyboardCurve {
+/** An eased slide: Gboard going up or down. */
+export interface KeyboardSlideCurve {
/** Length, ms. */
readonly durationMs: number;
/** Cubic-bézier control points. */
readonly points: readonly [number, number, number, number];
}
+/**
+ * A curve with its own progress: UIKit's keyboard spring, cut at
+ * `durationMs` (uikitKeyboardSchedule.ts).
+ */
+export interface KeyboardProgressCurve {
+ /** Length, ms. The motion lands on its target here. */
+ readonly durationMs: number;
+ /** How far along the curve the keyboard is, 0 to 1, `t` seconds in. */
+ readonly progress: (t: number) => number;
+}
+
+/** The curve a transition plays. */
+export type KeyboardCurve = KeyboardSlideCurve | KeyboardProgressCurve;
+
+/**
+ * How far along `curve` the keyboard is, from 0 to 1, `t` seconds after the
+ * transition's start.
+ */
+export function keyboardProgress(curve: KeyboardCurve): (t: number) => number {
+ if ('progress' in curve) {
+ return curve.progress;
+ }
+ const span = curve.durationMs / 1000;
+ const ease = cubicBezier(curve.points);
+ return t => ease(Math.min(1, Math.max(0, t / span)));
+}
+
/** How the keyboard's cover changes. */
export type KeyboardTransitionKind = 'show' | 'hide' | 'change';
@@ -50,10 +81,11 @@ export interface KeyboardTransition {
/** 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.
+ * The curve the keyboard moves on, or null when the inset jumps. It is
+ * Gboard's slide in Chrome on Android, and UIKit's keyboard spring in Safari
+ * on iOS. 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;
}
@@ -95,6 +127,37 @@ interface InsetCurve {
velocity(t: number): number;
}
+/**
+ * When a keyboard moves against its reports, in the Android table's shape:
+ * one slide for the show and one for the hide.
+ */
+export interface KeyboardSlideSchedule {
+ readonly showMs: number;
+ readonly showCurve: readonly [number, number, number, number];
+ readonly hideMs: number;
+ readonly hideCurve: readonly [number, number, number, number];
+ /** How long before its report the show starts, ms. */
+ readonly showReportLagMs: number;
+ /** How long before its report a hide nothing predicted starts, ms. */
+ readonly hideReportLagMs: number;
+ /** How long after a blur the keyboard starts down, ms. */
+ readonly hideAfterBlurMs: number;
+}
+
+/**
+ * A keyboard that moves on one curve, show and hide alike. It reports its
+ * height once, accessory bar included, as UIKit's does in Safari on iOS.
+ */
+export interface KeyboardCurveSchedule {
+ readonly curve: KeyboardProgressCurve;
+ readonly showReportLagMs: number;
+ readonly hideReportLagMs: number;
+ readonly hideAfterBlurMs: number;
+}
+
+/** When a keyboard moves against its reports, and on what curve. */
+export type KeyboardSchedule = KeyboardSlideSchedule | KeyboardCurveSchedule;
+
/**
* Creates the guide's core. Tests drive it with explicit times, and the
* window's guide feeds it events.
@@ -117,10 +180,16 @@ interface InsetCurve {
* - A keyboard that changes while up, such as another keyboard, lays out at
* once.
*
+ * Another `schedule` sets other curves and timings, as the touch runtime's
+ * schedule for Safari on iOS does (uikitKeyboardSchedule.ts).
+ *
* A prediction the viewport has not confirmed by its end gives way to what
* the viewport says (`verify`).
*/
-export function createKeyboardModel(initialInset = 0): KeyboardModel {
+export function createKeyboardModel(
+ initialInset = 0,
+ schedule: KeyboardSchedule = androidKeyboard,
+): KeyboardModel {
let transition: KeyboardTransition = {
kind: 'change',
from: initialInset,
@@ -133,16 +202,15 @@ export function createKeyboardModel(initialInset = 0): KeyboardModel {
};
// The inset over seconds since the transition's start.
let curve: InsetCurve | null = null;
- // An eased slide's value and velocity.
+ // A curve'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)));
+ const progress = keyboardProgress(slide);
+ const value = (t: number) => from + (to - from) * progress(t);
return {
value,
velocity: (t: number) => {
@@ -155,15 +223,15 @@ export function createKeyboardModel(initialInset = 0): KeyboardModel {
},
};
};
- // 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,
- };
+ // Gboard's slides, as Chrome draws them, unless the schedule has one curve.
+ const showSlide: KeyboardCurve =
+ 'curve' in schedule
+ ? schedule.curve
+ : {durationMs: schedule.showMs, points: schedule.showCurve};
+ const hideSlide: KeyboardCurve =
+ 'curve' in schedule
+ ? schedule.curve
+ : {durationMs: schedule.hideMs, points: schedule.hideCurve};
// How long the current transition moves for.
const lengthOf = () =>
transition.curve != null ? transition.curve.durationMs : 0;
@@ -245,20 +313,23 @@ export function createKeyboardModel(initialInset = 0): KeyboardModel {
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);
+ // A hide nothing predicted, as Back in Chrome: Chrome reports it just
+ // after Gboard starts down, so it rides from that moment. Safari
+ // reports it once the keyboard is down, and the content rides from
+ // the report.
+ return begin('hide', 0, time - schedule.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;
+ const predicted =
+ !('curve' in schedule) && shownInset > inset + EPSILON;
return begin(
'show',
predicted ? shownInset : inset,
- time - androidKeyboard.showReportLagMs,
+ time - schedule.showReportLagMs,
{predicted},
);
}
@@ -270,7 +341,7 @@ export function createKeyboardModel(initialInset = 0): KeyboardModel {
if (transition.to <= EPSILON) {
return null;
}
- return begin('hide', 0, time + androidKeyboard.hideAfterBlurMs, {
+ return begin('hide', 0, time + schedule.hideAfterBlurMs, {
predicted: true,
});
},
diff --git a/packages/core/src/keyboard/keyboardTarget.ts b/packages/core/src/keyboard/keyboardTarget.ts
index f35a09efa5fd6..187f1a0440735 100644
--- a/packages/core/src/keyboard/keyboardTarget.ts
+++ b/packages/core/src/keyboard/keyboardTarget.ts
@@ -13,12 +13,15 @@
*/
import type {Animator} from '../motion/animator';
+import {timing} from '../motion/uikit/timing';
+import {deepActiveElement} from '../utils/flatTree';
import {getTouchRuntime} from '../utils/touchRuntime';
import {isCoarsePointer} from '../utils/coarsePointer';
import {subscribeInput} from '../utils/inputStream';
import {layoutViewportHeight} from '../utils/layoutViewport';
+import {isElement} from '../utils/nodeType';
import {nearestScroller, scrollingAncestor} from '../utils/scrollingAncestor';
-import {sharedWeakMap, sharedWeakSet} from '../utils/sharedRealm';
+import {sharedState, sharedWeakMap, sharedWeakSet} from '../utils/sharedRealm';
import {
KEYBOARD_EPSILON,
claimTapFocus,
@@ -31,7 +34,14 @@ import {
subscribeKeyboardHeight,
watchRevealPan,
} from './keyboardHeight';
-import {getKeyboardLayoutGuide, keyboardProfileOf} from './keyboardLayoutGuide';
+import {
+ bringsUpKeyboard,
+ getKeyboardLayoutGuide,
+ hidesField,
+ keyboardProfileOf,
+ registerUIKitKeyboardSchedule,
+ type UIKitKeyboardSchedule,
+} from './keyboardLayoutGuide';
import type {KeyboardTransition} from './keyboardModel';
import {distanceIntoBand} from './revealBand';
import {rideKeyboard} from './rideKeyboard';
@@ -459,6 +469,47 @@ function focusedFieldIn(target: Element): HTMLElement | null {
: null;
}
+/**
+ * Whether the focused control may keep the keyboard up, read inside open
+ * shadow roots. A frame or a custom element can hold a field the page cannot
+ * see. An open shadow host that has focus itself also counts.
+ */
+export function mayKeepKeyboard(doc: Document): boolean {
+ const target = deepActiveElement(doc);
+ return target != null && (bringsUpKeyboard(target) || hidesField(target));
+}
+
+// Safari on iOS's keyboard schedule, built once from the touch runtime. The
+// riders give it what the page's first load holds, so the runtime's chunk
+// imports none of it.
+const uikit = sharedState(
+ 'keyboard/keyboard-target/uikit-schedule',
+ 1,
+ (): {built: UIKitKeyboardSchedule | null} => ({built: null}),
+);
+
+function readUIKitSchedule(): UIKitKeyboardSchedule | null {
+ const runtime = getTouchRuntime();
+ if (runtime == null) {
+ return null;
+ }
+ uikit.built ??= runtime.createUIKitKeyboardSchedule({
+ notificationMs: timing.keyboardNotificationMs,
+ mayKeepKeyboard,
+ isElement,
+ });
+ return uikit.built;
+}
+
+/**
+ * Lets the keyboard layout guide read Safari on iOS's keyboard schedule from
+ * the touch runtime once the page has loaded it. A keyboard rider calls it as
+ * it attaches under a coarse pointer.
+ */
+export function followTouchRuntimeKeyboardSchedule(): void {
+ registerUIKitKeyboardSchedule(readUIKitSchedule);
+}
+
/**
* Whether `win` keeps fields above a keyboard at all: a top-level document
* whose visual viewport shrinks for the keyboard, under a coarse primary
@@ -499,6 +550,7 @@ export function followKeyboard(
if (!followsKeyboard(win) || (move === 'ride' && getTouchRuntime() == null)) {
return () => {};
}
+ followTouchRuntimeKeyboardSchedule();
const unregister = registerKeyboardTarget(target);
const stopClaim = refuseFocusReveal(doc, {
claim: destination =>
@@ -657,7 +709,7 @@ function rideWithKeyboard(
const animator = runtime.animatorFor(target);
riddenAnimators.set(target, animator);
const guide =
- keyboardProfileOf(win) === 'chromium' ? getKeyboardLayoutGuide(win) : null;
+ keyboardProfileOf(win) != null ? getKeyboardLayoutGuide(win) : null;
// A ride moves the target while it rides or waits for the keyboard to go.
// Once it ends, by itself or by a takeover, it never moves the target.
let state: 'riding' | 'waiting' | 'ended' = 'riding';
diff --git a/packages/core/src/keyboard/keyboardUIKit.test.ts b/packages/core/src/keyboard/keyboardUIKit.test.ts
new file mode 100644
index 0000000000000..e84c6fde0a377
--- /dev/null
+++ b/packages/core/src/keyboard/keyboardUIKit.test.ts
@@ -0,0 +1,405 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file keyboardUIKit.test.ts
+ * @input vitest, jsdom, getKeyboardLayoutGuide with UIKit's schedule
+ * registered, a stand-in visual viewport, a stand-in CSS.supports
+ * @output Tests the guide in Safari on iOS. A keyboard coming up rides from
+ * Safari's one report on UIKit's keyboard spring. A hide rides down from
+ * the blur, as a prediction that Safari's later report confirms. Focus that
+ * moves between fields, to a picker in the keyboard's place, or to a field
+ * the page cannot see, moves nothing. Two pending cases hold a second
+ * report that comes while the keyboard still moves.
+ * @position Unit tests for the iOS part of keyboard/keyboardLayoutGuide.ts
+ */
+
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+import {timing as uikitTiming} from '../motion/uikit/timing';
+import {
+ getKeyboardLayoutGuide,
+ keyboardProfileOf,
+ registerUIKitKeyboardSchedule,
+} from './keyboardLayoutGuide';
+import {isElement} from '../utils/nodeType';
+import {mayKeepKeyboard} from './keyboardTarget';
+import {createUIKitKeyboardSchedule} from './uikitKeyboardSchedule';
+import type {KeyboardTransition} from './keyboardModel';
+
+let view: EventTarget & {height: number; offsetTop: number; scale: number};
+let a: HTMLInputElement;
+let b: HTMLInputElement;
+let date: HTMLInputElement;
+let button: HTMLButtonElement;
+const seen: KeyboardTransition[] = [];
+let unsubscribe: () => void = () => {};
+const uikitKeyboardSchedule = createUIKitKeyboardSchedule({
+ notificationMs: uikitTiming.keyboardNotificationMs,
+ mayKeepKeyboard,
+ isElement,
+});
+const uikitSpring = uikitKeyboardSchedule.curve;
+
+const report = (cover: number) => {
+ view.height = window.innerHeight - cover;
+ view.dispatchEvent(new Event('resize'));
+};
+
+describe('Safari on iOS’s keyboard schedule in the touch runtime’s chunk', () => {
+ // A module the page's first load also holds would make bundlers split a
+ // chunk out of the first load. The schedule reads the spring's table and the
+ // solver the runtime's animator already holds. The keyboard riders give it
+ // everything else.
+ it('imports values only from the spring table and the spring solver', () => {
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ const source = readFileSync(
+ path.join(here, 'uikitKeyboardSchedule.ts'),
+ 'utf8',
+ );
+ const valueImports = [
+ ...source.matchAll(/^import\s+(?!type\b)[^;]*?from\s+'([^']+)';/gms),
+ ].map(match => match[1]);
+ expect(valueImports).toEqual([
+ '../motion/spring',
+ '../motion/uikit/springs',
+ ]);
+ });
+});
+
+describe('the keyboard layout guide in Safari on iOS', () => {
+ // A keyboard rider registers how the guide reads UIKit's schedule.
+ beforeAll(() => {
+ registerUIKitKeyboardSchedule(() => uikitKeyboardSchedule);
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ // One clock for event times and the guide's own reads, as in a browser.
+ vi.spyOn(window.performance, 'now').mockImplementation(() => Date.now());
+ view = Object.assign(new EventTarget(), {
+ height: window.innerHeight,
+ offsetTop: 0,
+ scale: 1,
+ });
+ Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: view,
+ });
+ // WebKit on iOS: the one engine that supports -webkit-touch-callout.
+ vi.stubGlobal('CSS', {
+ supports: (property: string, value: string) =>
+ property === '-webkit-touch-callout' && value === 'none',
+ });
+ vi.stubGlobal(
+ 'matchMedia',
+ (query: string) =>
+ ({
+ matches: query === '(pointer: coarse)',
+ media: query,
+ }) as unknown as MediaQueryList,
+ );
+ document.body.innerHTML =
+ '';
+ a = document.getElementById('a') as HTMLInputElement;
+ b = document.getElementById('b') as HTMLInputElement;
+ date = document.getElementById('date') as HTMLInputElement;
+ button = document.getElementById('go') as HTMLButtonElement;
+ seen.length = 0;
+ unsubscribe = getKeyboardLayoutGuide(window).subscribe(t => seen.push(t));
+ });
+
+ afterEach(() => {
+ unsubscribe();
+ (document.activeElement as HTMLElement | null)?.blur();
+ document.body.innerHTML = '';
+ Reflect.deleteProperty(window, 'visualViewport');
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ it('rides nothing in Safari on iOS until the touch runtime registers UIKit’s schedule, as before the ride', () => {
+ registerUIKitKeyboardSchedule(null);
+ try {
+ expect(keyboardProfileOf(window)).toBeNull();
+ } finally {
+ registerUIKitKeyboardSchedule(() => uikitKeyboardSchedule);
+ }
+ expect(keyboardProfileOf(window)).toBe('uikit');
+ });
+
+ it('reads UIKit’s keyboard schedule from the engine’s capability, never the user agent', () => {
+ expect(keyboardProfileOf(window)).toBe('uikit');
+ expect(getKeyboardLayoutGuide(window).profile).toBe('uikit');
+ });
+
+ it('rides a keyboard coming up from Safari’s one report, on UIKit’s keyboard spring', () => {
+ a.focus();
+ let reportAt = 0;
+ view.addEventListener(
+ 'resize',
+ event => {
+ reportAt = event.timeStamp;
+ },
+ {once: true},
+ );
+ report(336);
+ expect(seen).toHaveLength(1);
+ expect(seen[0]).toMatchObject({
+ kind: 'show',
+ to: 336,
+ animated: true,
+ predicted: false,
+ });
+ expect(seen[0]?.start).toBeCloseTo(reportAt, 6);
+ expect(seen[0]?.curve).toBe(uikitSpring);
+ });
+
+ it('rides a hide down from the blur on the same spring, and keeps it until Safari reports the keyboard down', () => {
+ a.focus();
+ report(336);
+ vi.advanceTimersByTime(1000);
+ let blurAt = 0;
+ a.addEventListener(
+ 'focusout',
+ event => {
+ blurAt = event.timeStamp;
+ },
+ {once: true},
+ );
+ button.focus();
+ const hide = seen.at(-1);
+ expect(hide).toMatchObject({
+ kind: 'hide',
+ to: 0,
+ animated: true,
+ predicted: true,
+ });
+ expect(hide?.start).toBeCloseTo(blurAt, 6);
+ expect(hide?.curve).toBe(uikitSpring);
+ // Safari still reads the keyboard up once the spring ends: the hide
+ // stands, with nothing turned back.
+ vi.advanceTimersByTime(uikitTiming.keyboardNotificationMs + 200);
+ expect(seen.at(-1)).toBe(hide);
+ // Safari's report of the keyboard down confirms it.
+ report(0);
+ expect(seen.at(-1)).toBe(hide);
+ expect(getKeyboardLayoutGuide(window).transition.predicted).toBe(false);
+ });
+
+ it('predicts no hide when focus moves into a frame, whose own field can keep the keyboard up', () => {
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ a.focus();
+ report(336);
+ seen.length = 0;
+ frame.focus();
+ vi.advanceTimersByTime(0);
+ expect(document.activeElement).toBe(frame);
+ expect(seen).toHaveLength(0);
+ });
+
+ it('predicts no hide when focus moves into a frame and Safari names no related target', () => {
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ a.focus();
+ report(336);
+ seen.length = 0;
+ // Safari's focusout names no related target when focus moves into a
+ // frame. The frame becomes the active element only after it.
+ a.dispatchEvent(
+ new FocusEvent('focusout', {bubbles: true, relatedTarget: null}),
+ );
+ frame.focus();
+ vi.advanceTimersByTime(0);
+ expect(document.activeElement).toBe(frame);
+ expect(seen).toHaveLength(0);
+ });
+
+ it('predicts no hide when focus moves into a frame after the page parks focus on its own element', () => {
+ const parking = document.createElement('div');
+ parking.tabIndex = -1;
+ document.body.append(parking);
+ a.focus();
+ report(336);
+ seen.length = 0;
+ // Safari, with focus moving into a frame: the page parks focus on its own
+ // element during the field's blur. The focusout names no related target,
+ // and this window then blurs while its document keeps focus.
+ const active = vi
+ .spyOn(document, 'activeElement', 'get')
+ .mockReturnValue(parking);
+ const hasFocus = vi.spyOn(document, 'hasFocus').mockReturnValue(true);
+ try {
+ a.dispatchEvent(
+ new FocusEvent('focusout', {bubbles: true, relatedTarget: null}),
+ );
+ window.dispatchEvent(new FocusEvent('blur'));
+ vi.advanceTimersByTime(0);
+ expect(seen).toHaveLength(0);
+ } finally {
+ active.mockRestore();
+ hasFocus.mockRestore();
+ }
+ });
+
+ it('still predicts the hide from a blur to nothing when this window keeps focus', () => {
+ const parking = document.createElement('div');
+ parking.tabIndex = -1;
+ document.body.append(parking);
+ a.focus();
+ report(336);
+ vi.advanceTimersByTime(1000);
+ seen.length = 0;
+ const active = vi
+ .spyOn(document, 'activeElement', 'get')
+ .mockReturnValue(parking);
+ try {
+ a.dispatchEvent(
+ new FocusEvent('focusout', {bubbles: true, relatedTarget: null}),
+ );
+ vi.advanceTimersByTime(0);
+ expect(seen.at(-1)).toMatchObject({kind: 'hide', predicted: true});
+ } finally {
+ active.mockRestore();
+ }
+ });
+
+ it('rides a hide down from a blur to nothing, dated at the blur', () => {
+ a.focus();
+ report(336);
+ vi.advanceTimersByTime(1000);
+ seen.length = 0;
+ let blurAt = 0;
+ a.addEventListener(
+ 'focusout',
+ event => {
+ blurAt = event.timeStamp;
+ },
+ {once: true},
+ );
+ a.blur();
+ vi.advanceTimersByTime(0);
+ expect(seen.at(-1)).toMatchObject({kind: 'hide', to: 0, predicted: true});
+ expect(seen.at(-1)?.start).toBeCloseTo(blurAt, 6);
+ });
+
+ it('decides once focus settles inside an open shadow root: a field there keeps the keyboard, a plain button takes it down', () => {
+ const host = document.createElement('x-editor');
+ const root = host.attachShadow({mode: 'open'});
+ const inner = root.appendChild(document.createElement('input'));
+ const plain = root.appendChild(document.createElement('button'));
+ document.body.append(host);
+ a.focus();
+ report(336);
+ seen.length = 0;
+ inner.focus();
+ vi.advanceTimersByTime(0);
+ expect(seen).toHaveLength(0);
+ a.focus();
+ plain.focus();
+ vi.advanceTimersByTime(0);
+ expect(seen.at(-1)).toMatchObject({
+ kind: 'hide',
+ to: 0,
+ predicted: true,
+ });
+ });
+
+ it('predicts no hide when focus moves into a custom element with no shadow root, whose own field can keep the keyboard up', () => {
+ const custom = document.createElement('x-field');
+ custom.tabIndex = 0;
+ document.body.append(custom);
+ a.focus();
+ report(336);
+ seen.length = 0;
+ custom.focus();
+ vi.advanceTimersByTime(0);
+ expect(document.activeElement).toBe(custom);
+ expect(custom.shadowRoot).toBeNull();
+ expect(seen).toHaveLength(0);
+ });
+
+ it('rides a hide down from the blur when Done leaves a field inside an open shadow root', () => {
+ const host = document.createElement('div');
+ const inner = host
+ .attachShadow({mode: 'open'})
+ .appendChild(document.createElement('input'));
+ document.body.append(host);
+ a.focus();
+ report(336);
+ inner.focus();
+ vi.advanceTimersByTime(0);
+ seen.length = 0;
+ inner.blur();
+ vi.advanceTimersByTime(0);
+ expect(seen.at(-1)).toMatchObject({
+ kind: 'hide',
+ to: 0,
+ predicted: true,
+ });
+ });
+
+ it('rides a hide down from the blur when Done leaves a field inside a custom element’s closed shadow root', () => {
+ const host = document.createElement('x-closed-field');
+ const inner = host
+ .attachShadow({mode: 'closed'})
+ .appendChild(document.createElement('input'));
+ document.body.append(host);
+ a.focus();
+ report(336);
+ inner.focus();
+ vi.advanceTimersByTime(0);
+ seen.length = 0;
+ inner.blur();
+ vi.advanceTimersByTime(0);
+ expect(seen.at(-1)).toMatchObject({
+ kind: 'hide',
+ to: 0,
+ predicted: true,
+ });
+ });
+
+ it('turns a predicted hide back up when focus moves into a frame before the keyboard is down', () => {
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ a.focus();
+ report(336);
+ vi.advanceTimersByTime(1000);
+ button.focus();
+ expect(seen.at(-1)).toMatchObject({kind: 'hide', predicted: true});
+ vi.advanceTimersByTime(100);
+ frame.focus();
+ expect(seen.at(-1)).toMatchObject({kind: 'show', to: 336});
+ expect(seen.at(-1)?.curve).toBe(uikitSpring);
+ });
+
+ it('moves nothing while focus moves between fields, or to a date field whose picker takes the keyboard’s place', () => {
+ a.focus();
+ report(336);
+ seen.length = 0;
+ b.focus();
+ date.focus();
+ expect(seen).toHaveLength(0);
+ });
+
+ // Safari reports a second height while the keyboard still comes up. It is
+ // shorter when focus moves to a field without QuickType, and taller for the
+ // emoji keyboard.
+ it.todo(
+ 're-aims the show when Safari reports a shorter keyboard mid-show: 347 px, then 320 px 126 ms or 233 ms in',
+ );
+ it.todo(
+ 're-aims the show when Safari reports a taller keyboard mid-show: 347 px, then 401 px',
+ );
+});
diff --git a/packages/core/src/keyboard/rideKeyboard.test.ts b/packages/core/src/keyboard/rideKeyboard.test.ts
index 4bafafa0fef74..4ccd7355f471f 100644
--- a/packages/core/src/keyboard/rideKeyboard.test.ts
+++ b/packages/core/src/keyboard/rideKeyboard.test.ts
@@ -4,14 +4,25 @@
* @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.
+ * transition's start, Gboard's slide or UIKit's keyboard spring, 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 {KEYBOARD_SPRING} from '../motion/uikit/springs';
+import {timing as uikitTiming} from '../motion/uikit/timing';
+import {isElement} from '../utils/nodeType';
+import {mayKeepKeyboard} from './keyboardTarget';
+import {createUIKitKeyboardSchedule} from './uikitKeyboardSchedule';
+
+const uikitKeyboardSchedule = createUIKitKeyboardSchedule({
+ notificationMs: uikitTiming.keyboardNotificationMs,
+ mayKeepKeyboard,
+ isElement,
+});
import type {KeyboardTransition} from './keyboardModel';
import {rideKeyboard} from './rideKeyboard';
@@ -75,6 +86,33 @@ describe('rideKeyboard', () => {
expect(curves.y.at(curves.y.duration)).toBe(-300);
});
+ it('plays UIKit’s keyboard spring where the transition publishes it, landing at the notification’s duration (iOS)', () => {
+ const animator = standInAnimator();
+
+ rideKeyboard(
+ animator as unknown as Animator,
+ {y: -336},
+ transition({
+ to: 336,
+ curve: uikitKeyboardSchedule.curve,
+ }),
+ );
+
+ expect(animator.play).toHaveBeenCalledTimes(1);
+ const [curves, options] = animator.play.mock.calls[0] as unknown as [
+ Record number}>,
+ {at: number},
+ ];
+ expect(options).toEqual({at: 1000});
+ const span = uikitTiming.keyboardNotificationMs / 1000;
+ expect(curves.y.duration).toBeCloseTo(span, 9);
+ // Critically damped: 1 − (1 + ω₀t)·e^(−ω₀t) of the way at t.
+ const omega = Math.sqrt(KEYBOARD_SPRING.stiffness / KEYBOARD_SPRING.mass);
+ const along = (s: number) => 1 - (1 + omega * s) * Math.exp(-omega * s);
+ expect(curves.y.at(0.1)).toBeCloseTo(-336 * along(0.1), 6);
+ expect(curves.y.at(span)).toBe(-336);
+ });
+
it("plays the transition's own curve, even a show published with the hide slide", () => {
const animator = standInAnimator();
@@ -140,6 +178,64 @@ describe('rideKeyboard', () => {
expect(calls[1][1]).toEqual({at: 1000});
});
+ it('starts no later than the document timeline, as Safari can date the report after its frame', () => {
+ const slide = transition({curve: uikitKeyboardSchedule.curve});
+ try {
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: 999},
+ });
+ const late = standInAnimator();
+ rideKeyboard(late as unknown as Animator, {y: -336}, slide);
+ const lateCalls = late.play.mock.calls as unknown as [
+ unknown,
+ Record,
+ ][];
+ expect(lateCalls[0]?.[1]).toEqual({at: 999});
+ expect(late.get).toHaveBeenCalledWith('y', 999);
+ // A report dated at or before its frame keeps its own start.
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: 1000},
+ });
+ const onTime = standInAnimator();
+ rideKeyboard(onTime as unknown as Animator, {y: -336}, slide);
+ const onTimeCalls = onTime.play.mock.calls as unknown as [
+ unknown,
+ Record,
+ ][];
+ expect(onTimeCalls[0]?.[1]).toEqual({at: 1000});
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
+ it('keeps the start of a predicted hide after a blur, which starts ahead of the frame on purpose', () => {
+ const hide = transition({
+ kind: 'hide',
+ from: 300,
+ to: 0,
+ curve: uikitKeyboardSchedule.curve,
+ predicted: true,
+ });
+ try {
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: 980},
+ });
+ const animator = standInAnimator();
+ rideKeyboard(animator as unknown as Animator, {y: 0}, hide);
+ const calls = animator.play.mock.calls as unknown as [
+ unknown,
+ Record,
+ ][];
+ expect(calls[0]?.[1]).toEqual({at: 1000});
+ expect(animator.get).toHaveBeenCalledWith('y', 1000);
+ } finally {
+ Reflect.deleteProperty(document, 'timeline');
+ }
+ });
+
it('lands at once when the keyboard jumps', () => {
const animator = standInAnimator();
diff --git a/packages/core/src/keyboard/rideKeyboard.ts b/packages/core/src/keyboard/rideKeyboard.ts
index 49c0c6bcdf4b8..30c460992f837 100644
--- a/packages/core/src/keyboard/rideKeyboard.ts
+++ b/packages/core/src/keyboard/rideKeyboard.ts
@@ -19,8 +19,7 @@ import type {
MotionProperty,
MotionValues,
} from '../motion/animator';
-import {cubicBezier} from '../motion/bezier';
-import type {KeyboardTransition} from './keyboardModel';
+import {keyboardProgress, type KeyboardTransition} from './keyboardModel';
/** How a ride treats Reduce Motion. */
export interface RideOptions {
@@ -31,19 +30,27 @@ export interface RideOptions {
readonly entrance?: boolean;
}
+// The document timeline's time, the time of the frame in progress.
+function timelineTime(): number | null {
+ const time =
+ typeof document === 'undefined' ? null : document.timeline?.currentTime;
+ return typeof time === 'number' ? time : null;
+}
+
/**
* 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.
+ * (motion/android/keyboard.ts), and iOS's on UIKit's keyboard spring
+ * (motion/uikit/springs.ts, as keyboard/uikitKeyboardSchedule.ts cuts it).
+ * The transition publishes the curve (`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
* ```
@@ -67,22 +74,29 @@ export function rideKeyboard(
animator.set(to);
return null;
}
+ // Safari can date the event that reports the keyboard a little after the
+ // frame that dispatches it. A ride dated after that frame has not started
+ // there. A long task right after the frame then holds it. So a reported
+ // ride starts no later than the document timeline's time. A predicted hide
+ // after a blur starts ahead on purpose, and keeps its start.
+ const start = transition.predicted
+ ? transition.start
+ : Math.min(transition.start, timelineTime() ?? transition.start);
// 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};
+ ? {at: start, crossfadeAs: 'entrance' as const}
+ : {at: start};
const span = transition.curve.durationMs / 1000;
- const ease = cubicBezier(transition.curve.points);
+ const progress = keyboardProgress(transition.curve);
const curves: Partial> = {};
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)));
+ const from = animator.get(property, start);
+ const at = (t: number) => from + (target - from) * progress(t);
curves[property] = {
duration: span,
at,
diff --git a/packages/core/src/keyboard/uikitKeyboardSchedule.ts b/packages/core/src/keyboard/uikitKeyboardSchedule.ts
new file mode 100644
index 0000000000000..bf7a41d9047f3
--- /dev/null
+++ b/packages/core/src/keyboard/uikitKeyboardSchedule.ts
@@ -0,0 +1,145 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file uikitKeyboardSchedule.ts
+ * @input The UIKit table's keyboard frame spring (`KEYBOARD_SPRING`) and the
+ * spring solver. From the keyboard riders: the duration UIKit's keyboard
+ * notifications report, and their focus checks. From the layout guide: its
+ * field check
+ * @output createUIKitKeyboardSchedule: when and how the keyboard moves in
+ * Safari on iOS, with the spring's progress and the guide's focus rules there
+ * @position Part of the touch runtime (utils/touchRuntimeModules.tsx), which
+ * publishes it. The keyboard riders register it with the layout guide. No
+ * module on a page's first load imports it. It imports the spring's table
+ * and the solver the runtime's animator already uses
+ *
+ * SYNC: When modified, update /packages/core/src/keyboard/README.md
+ */
+
+import {solveSpring} from '../motion/spring';
+import {KEYBOARD_SPRING} from '../motion/uikit/springs';
+import type {
+ KeyboardFocusChecks,
+ KeyboardFocusRules,
+ UIKitKeyboardSchedule,
+} from './keyboardLayoutGuide';
+import type {KeyboardProgressCurve} from './keyboardModel';
+
+/**
+ * What a keyboard rider gives the schedule from modules the page's first load
+ * already holds, so the runtime's chunk shares none of them.
+ */
+export interface UIKitKeyboardScheduleInputs {
+ /** How long UIKit's keyboard notifications say the keyboard moves, ms. */
+ readonly notificationMs: number;
+ /** Whether the focused element, read inside open shadow roots, may keep a keyboard up. */
+ readonly mayKeepKeyboard: (doc: Document) => boolean;
+ /** Whether `value` is an element, from this window or another one. */
+ readonly isElement: (value: unknown) => value is Element;
+}
+
+// The keyboard's progress, 0 to 1, on its spring released at rest.
+const spring = solveSpring(KEYBOARD_SPRING, {from: 0, to: 1});
+
+// Only WebKit on iOS and iPadOS supports `-webkit-touch-callout`, and its
+// keyboard is UIKit's. The check reads a capability, never the user agent.
+function hasUIKitKeyboard(win: Window): boolean {
+ const css = (win as Window & {readonly CSS?: Partial}).CSS;
+ return (
+ typeof css?.supports === 'function' &&
+ css.supports('-webkit-touch-callout', 'none')
+ );
+}
+
+// Safari keeps the keyboard up for a field inside a frame, a custom element or
+// an open shadow root. When focus moves to one of these, the guide waits for
+// focus to settle there. It decides about the hide at the focus event, or on
+// the next task. Safari's focusout names no related target when focus moves
+// into a frame, so a blur to nothing waits too.
+function uikitFocusRules(
+ win: Window,
+ hide: (blurAt: number) => void,
+ {hidesField}: KeyboardFocusChecks,
+ {mayKeepKeyboard: keepsKeyboard, isElement}: UIKitKeyboardScheduleInputs,
+): KeyboardFocusRules {
+ let pendingAt: number | null = null;
+ let timer: ReturnType | null = null;
+ // Focus that moves into a frame blurs this window, and its document keeps
+ // focus. A surface can park focus on its own element first, so the active
+ // element does not show the frame.
+ let windowBlurred = false;
+ // Blur does not bubble, so this listener hears only the window's own blur.
+ const onWindowBlur = () => {
+ windowBlurred = true;
+ };
+ const stopWaiting = () => {
+ if (timer != null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ win.removeEventListener('blur', onWindowBlur);
+ };
+ const mayKeepKeyboard = () => keepsKeyboard(win.document);
+ const settle = () => {
+ stopWaiting();
+ const blurAt = pendingAt;
+ const intoFrame = windowBlurred && win.document.hasFocus();
+ pendingAt = null;
+ windowBlurred = false;
+ if (blurAt != null && !intoFrame && !mayKeepKeyboard()) {
+ hide(blurAt);
+ }
+ };
+ return {
+ focused: () => {
+ settle();
+ return mayKeepKeyboard();
+ },
+ blurred: (next, blurAt) => {
+ if (next != null && (!isElement(next) || !hidesField(next))) {
+ return false;
+ }
+ stopWaiting();
+ pendingAt = blurAt;
+ windowBlurred = false;
+ win.addEventListener('blur', onWindowBlur);
+ timer = setTimeout(settle, 0);
+ return true;
+ },
+ dispose: () => {
+ stopWaiting();
+ pendingAt = null;
+ windowBlurred = false;
+ },
+ };
+}
+
+/**
+ * Safari on iOS reports the keyboard's show once, as UIKit's keyboard starts
+ * up, and its hide only once the keyboard is down. So content rides UIKit's
+ * keyboard spring from the show's report. On hide it rides from the blur that
+ * takes the keyboard down, as a prediction that Safari's later report
+ * confirms. A hide nothing predicted rides from the report. Safari reports the
+ * keyboard with its accessory bar in one height.
+ */
+export function createUIKitKeyboardSchedule(
+ inputs: UIKitKeyboardScheduleInputs,
+): UIKitKeyboardSchedule {
+ const {notificationMs} = inputs;
+ const span = notificationMs / 1000;
+ // UIKit's keyboard moves on one spring, up and down. Core Animation cuts it
+ // at the duration the keyboard notifications report, so it lands there.
+ const curve: KeyboardProgressCurve = {
+ durationMs: notificationMs,
+ progress: t => (t <= 0 ? 0 : t >= span ? 1 : spring.value(t)),
+ };
+ return {
+ curve,
+ showReportLagMs: 0,
+ hideReportLagMs: 0,
+ hideAfterBlurMs: 0,
+ appliesTo: hasUIKitKeyboard,
+ focusRules: (win, hide, checks) =>
+ uikitFocusRules(win, hide, checks, inputs),
+ };
+}
diff --git a/packages/core/src/keyboard/useMobileKeyboard.ts b/packages/core/src/keyboard/useMobileKeyboard.ts
index 2abba38f8925c..531c54c3694b1 100644
--- a/packages/core/src/keyboard/useMobileKeyboard.ts
+++ b/packages/core/src/keyboard/useMobileKeyboard.ts
@@ -21,7 +21,6 @@ import {useMediaQuery} from '../hooks/useMediaQuery';
import type {Animator, MotionHandle} from '../motion/animator';
import {getTouchRuntime, useTouchRuntime} from '../utils/touchRuntime';
import {KEYBOARD_SPRING} from '../motion/uikit/springs';
-import {deepActiveElement} from '../utils/flatTree';
import {subscribeInput} from '../utils/inputStream';
import {layoutViewportHeight} from '../utils/layoutViewport';
import {isDocument, isNode} from '../utils/nodeType';
@@ -38,18 +37,15 @@ import {
subscribeKeyboardHeight,
watchRevealPan,
} from './keyboardHeight';
-import {
- bringsUpKeyboard,
- getKeyboardLayoutGuide,
- hidesField,
- keyboardProfileOf,
-} from './keyboardLayoutGuide';
+import {getKeyboardLayoutGuide, keyboardProfileOf} from './keyboardLayoutGuide';
import type {KeyboardTransition} from './keyboardModel';
import {
FIELD_OFFSET,
drawnOffsetOf,
followKeyboard,
+ followTouchRuntimeKeyboardSchedule,
keepFieldAboveKeyboard,
+ mayKeepKeyboard,
registerKeyboardTarget,
type KeyboardMove,
} from './keyboardTarget';
@@ -146,12 +142,22 @@ function isVisualViewportRecovered(): boolean {
return getKeyboardHeight(window) <= 0.5;
}
-// Whether the focused control may keep the keyboard up, read inside open
-// shadow roots. A frame or a custom element can hold a field the page cannot
-// see. An open shadow host that has focus itself also counts.
-function mayKeepKeyboard(): boolean {
- const target = deepActiveElement(document);
- return target != null && (bringsUpKeyboard(target) || hidesField(target));
+// Where the layout puts `child`'s top in the viewport, with no transform, for
+// a child of the scroller `body`. Offsets ignore transforms and the body's
+// scroll, and round to whole pixels. Null when the two share no offset parent.
+function layoutTopIn(body: HTMLElement, child: HTMLElement): number | null {
+ const parent = child.offsetParent;
+ if (parent == null) {
+ return null;
+ }
+ const bodyTop = body.getBoundingClientRect().top;
+ if (parent === body) {
+ return bodyTop + body.clientTop + child.offsetTop - body.scrollTop;
+ }
+ if (parent === body.offsetParent) {
+ return bodyTop + child.offsetTop - body.offsetTop - body.scrollTop;
+ }
+ return null;
}
/**
@@ -264,16 +270,19 @@ export function useMobileKeyboard(
// 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.
+ // The keyboard layout guide publishes the keyboard's own motion: Gboard's
+ // slide in Chrome on Android, UIKit's keyboard spring in Safari on iOS.
+ // There the sheet's content rides it. This needs a coarse primary
+ // pointer and a keyboard schedule. Under a fine pointer nothing
+ // of the ride attaches. In a browser with neither, such as 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.
+ if (isTouch) {
+ followTouchRuntimeKeyboardSchedule();
+ }
const guide =
- isTouch && keyboardProfileOf(window) === 'chromium'
+ isTouch && keyboardProfileOf(window) != null
? getKeyboardLayoutGuide(window)
: null;
const contentAnimator = (): Animator | null => {
@@ -284,10 +293,25 @@ export function useMobileKeyboard(
};
// 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.
+ // frame. WebKit can keep a composited element's rects from its last style
+ // resolution while its computed translate follows the ride. So the
+ // offset comes from the content's own rect, which moves with the
+ // control's. Without a shared offset parent, the computed translate
+ // stands in.
const rideOffset = () => {
const content = body.firstElementChild;
- return content instanceof HTMLElement ? drawnOffsetOf(content) : 0;
+ if (!(content instanceof HTMLElement)) {
+ return 0;
+ }
+ const drawn = drawnOffsetOf(content);
+ const layoutTop = layoutTopIn(body, content);
+ if (layoutTop == null) {
+ return drawn;
+ }
+ // Offsets round to whole pixels. Rects within a pixel of the computed
+ // translate are current, so the exact translate stands.
+ const fromRect = content.getBoundingClientRect().top - layoutTop;
+ return Math.abs(fromRect - drawn) < 1 ? drawn : fromRect;
};
// 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
@@ -453,14 +477,20 @@ export function useMobileKeyboard(
safeBottom,
);
if (distance > 0) {
+ // Chrome pans the page itself when the control is still below the
+ // keyboard shortly after its report. So in Chrome the control clears
+ // the keyboard in this commit. Safari leaves a claimed control in
+ // place, so it rides the whole way.
scrollBodyBy(
distance,
smoothly,
ride,
- Math.max(
- 0,
- obstructionTop - safeBottom - FIELD_CLEARANCE_AT_REPORT,
- ),
+ guide?.profile === 'chromium'
+ ? Math.max(
+ 0,
+ obstructionTop - safeBottom - FIELD_CLEARANCE_AT_REPORT,
+ )
+ : null,
);
} else if (distance < 0) {
scrollBodyBy(distance, smoothly, ride);
@@ -553,7 +583,7 @@ export function useMobileKeyboard(
if (
isExpandedRef.current &&
hasKeyboardLayoutRef.current &&
- !mayKeepKeyboard()
+ !mayKeepKeyboard(document)
) {
holdThroughUnguidedHide();
}
@@ -655,11 +685,10 @@ export function useMobileKeyboard(
return resting;
};
- // Without the guide, as in iOS Safari and Firefox for Android, nothing
- // publishes the keyboard's slide down. iOS Safari sends one report once
- // the keyboard is gone, about half a second after a blur. Under a coarse
- // primary pointer, the content then moves on UIKit's keyboard spring,
- // never at once.
+ // Without the guide, as in Firefox for Android, nothing publishes the
+ // keyboard's slide down. Where a browser reports the hide only once the
+ // keyboard is gone, the content then moves on UIKit's keyboard spring,
+ // never at once. This needs a coarse primary pointer.
const unguidedAnimator = (): Animator | null => {
const content = body.firstElementChild;
return ownsFocusTransitions &&
@@ -724,7 +753,7 @@ export function useMobileKeyboard(
if (
active instanceof HTMLElement &&
body.contains(active) &&
- mayKeepKeyboard()
+ mayKeepKeyboard(document)
) {
hold.release();
void rideKeyboardSpring(animator, 0);
@@ -1053,7 +1082,9 @@ export function useMobileKeyboard(
retainKeyboardLayoutRef.current = false;
};
},
- `${isEnabled}|${reservesInset}|${isPageScrollLocked}|${isTouch}|${offset}`,
+ // The touch runtime's load re-attaches the sheet: Safari on iOS's keyboard
+ // schedule comes with it.
+ `${isEnabled}|${reservesInset}|${isPageScrollLocked}|${isTouch}|${offset}|${hasTouchRuntime}`,
);
return {inset: keyboardInset, dismiss};
}
diff --git a/packages/core/src/utils/touchRuntimeModules.tsx b/packages/core/src/utils/touchRuntimeModules.tsx
index 9cdcb6e8ffcc6..b9ae6be63e90a 100644
--- a/packages/core/src/utils/touchRuntimeModules.tsx
+++ b/packages/core/src/utils/touchRuntimeModules.tsx
@@ -4,7 +4,9 @@
/**
* @file touchRuntimeModules.tsx
- * @input The shared touch core: the animator
+ * @input The shared touch core: the animator, and Safari on iOS's keyboard
+ * schedule (keyboard/uikitKeyboardSchedule.ts), which the keyboard riders
+ * register with the layout guide
* @output `touchRuntime`, the one object the touch loader publishes
* @position Loaded only through `import()` in utils/touchRuntime.ts. No
* other module imports this file. A component's own touch code is its touch
@@ -13,10 +15,16 @@
*/
import {animatorFor} from '../motion/animator';
+import {createUIKitKeyboardSchedule} from '../keyboard/uikitKeyboardSchedule';
-/** What the touch loader publishes once the page has loaded it. */
+/**
+ * What the touch loader publishes once the page has loaded it. Safari on iOS's
+ * keyboard schedule comes from here, so a page that never loads the runtime
+ * carries none of it.
+ */
export const touchRuntime = {
animatorFor,
+ createUIKitKeyboardSchedule,
} as const;
export type TouchRuntime = typeof touchRuntime;