An open source design system that's fully customizable and agent ready
TypeScript
fix(lab): limit BottomSheet keyboard support to Tall (#5063)
Xinzi Zhou56435d6d87d1
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsxindex 9450e64edf..0a9bb3d1c2 100644--- a/apps/storybook/stories/BottomSheet.stories.tsx+++ b/apps/storybook/stories/BottomSheet.stories.tsx@@ -78,9 +78,16 @@ function MobileKeyboardCommentForm({onPost}: {onPost: () => void}) {<VStack gap={4}><Heading level={3}>Add a comment</Heading><Text type="supporting" color="secondary">- Focus fields throughout this long form to verify that the mobile- keyboard leaves each control visible and the sheet itself stays put.+ Keep the Tall sheet fully expanded, then focus fields near the+ beginning, middle, and end. The outer sheet remains stationary while its+ body scrolls each control above the mobile keyboard. Keyboard+ accommodation is not provided at shorter snap points.</Text>+ <Text type="supporting" color="secondary">+ Move the sheet with its handle or close it with Post comment to verify+ that sheet travel and closing dismiss the keyboard.+ </Text>+ <Button label="Close sheet" onClick={onPost} /><Divider /><TextInputlabel="Title"@@ -144,24 +151,6 @@ function MobileKeyboardCommentForm({onPost}: {onPost: () => void}) {);}-function ShortMobileKeyboardForm({onSave}: {onSave: () => void}) {- const [title, setTitle] = useState('');- const [note, setNote] = useState('');-- return (- <VStack gap={4}>- <Heading level={3}>Quick note</Heading>- <Text type="supporting" color="secondary">- This short sheet keeps its height and lifts only when the mobile- keyboard would otherwise cover the focused field.- </Text>- <TextInput label="Title" value={title} onChange={setTitle} />- <TextArea label="Note" rows={2} value={note} onChange={setNote} />- <Button label="Save note" onClick={onSave} />- </VStack>- );-}-export const Showcase: Story = {render: () => {const [isOpen, setIsOpen] = useState(false);@@ -341,29 +330,8 @@ export const HugHeightWithLongContent: Story = {},};-export const ShortMobileKeyboard: Story = {- name: 'Short sheet with mobile keyboard',- render: () => {- const [isOpen, setIsOpen] = useState(false);- return (- <>- <Button label="Add a quick note" onClick={() => setIsOpen(true)} />- <BottomSheet- isOpen={isOpen}- onOpenChange={setIsOpen}- label="Quick note"- height="hug">- <Section padding={4}>- <ShortMobileKeyboardForm onSave={() => setIsOpen(false)} />- </Section>- </BottomSheet>- </>- );- },-};-export const MobileKeyboard: Story = {- name: 'Support mobile keyboard',+ name: 'Mobile keyboard',render: () => {const [isOpen, setIsOpen] = useState(false);return (diff --git a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs b/packages/lab/src/BottomSheet/BottomSheet.doc.mjsindex bfe69ea7e3..feb2b2c0ed 100644--- a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/lab/src/BottomSheet/BottomSheet.doc.mjs@@ -57,14 +57,14 @@ export const docs = {name: 'children',type: 'ReactNode',description:- 'Sheet content, rendered below the grab handle in a scrollable, mobile-keyboard-aware area.',+ "Sheet content, rendered below the grab handle in a scrollable area. If it includes a text-entry control that can bring up the mobile keyboard, use height='tall' and keep the sheet fully expanded while editing.",required: true,},{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. The user can drag between snap points regardless. On shorter viewports the sheet fills the available height.",+ "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. The user can drag between snap points regardless. On shorter viewports the sheet fills the available height. Only a fully expanded 'tall' sheet provides mobile-keyboard accommodation; shorter Tall detents, Hug, Capped, numeric, and CSS-length heights do not move or add keyboard scroll space.",default: "'capped'",},{@@ -77,7 +77,7 @@ export const docs = {],usage: {description:- 'A mobile touch surface for filters, actions, and detail views that should rise from the bottom of the screen. Opening slides the sheet in; closing keeps its native dialog presented but inert until the slide-out and scrim fade complete. Drag the grab handle to resize: a slow drag settles to the nearest snap point (a short peek, ~half, and ~full detent, filtered to those shorter than the sheet), a fast flick down dismisses, a fast flick up expands. Pulling down on the content when it is scrolled to the top also drags the sheet, giving a larger, more forgiving target. The scrim thins to a faint glance state (but never fully clears) as the sheet collapses onto its shortest "peek" detent; the sheet stays modal, so the background remains inert until dismissed; a residual dim keeps that legible. The sheet is modal: focus is trapped while open and restored to the opener after its exit, and Escape dismisses, so the swipe gesture always has a keyboard equivalent. Visual-viewport overlap adds internal scroll range and keeps focused controls above the mobile keyboard without changing the measured sheet height; short sheets temporarily lift when they otherwise have no usable focus area. Actual sheet travel or closing dismisses the keyboard. Content padding clears the home indicator via env(safe-area-inset-bottom).',+ 'A mobile touch surface for filters, actions, and detail views that should rise from the bottom of the screen. Opening slides the sheet in; closing keeps its native dialog presented but inert until the slide-out and scrim fade complete. Drag the grab handle to resize: a slow drag settles to the nearest snap point (a short peek, ~half, and ~full detent, filtered to those shorter than the sheet), a fast flick down dismisses, a fast flick up expands. Pulling down on the content when it is scrolled to the top also drags the sheet, giving a larger, more forgiving target. The scrim thins to a faint glance state (but never fully clears) as the sheet collapses onto its shortest "peek" detent; the sheet stays modal, so the background remains inert until dismissed; a residual dim keeps that legible. The sheet is modal: focus is trapped while open and restored to the opener after its exit, and Escape dismisses, so the swipe gesture always has a keyboard equivalent. Mobile-keyboard accommodation is supported only while Tall is fully expanded: the outer sheet remains stationary while visual-viewport overlap extends its internal scroll range and the body scrolls focused controls above the keyboard. Shorter Tall detents, Hug, Capped, numeric, and CSS-length heights do not automatically move or add keyboard scroll space. Actual Tall-sheet travel or closing dismisses the keyboard. Content padding clears the home indicator via env(safe-area-inset-bottom).',bestPractices: [{guidance: true,@@ -102,7 +102,7 @@ export const docs = {{guidance: true,description:- "Use 'tall' for long mobile forms. 'hug' also supports short forms by temporarily lifting when the keyboard leaves too little usable space. Keep controls in the built-in scroll body.",+ "If a sheet contains a text-entry control that can bring up the mobile keyboard, use 'tall' and keep it fully expanded while editing. Its outer sheet stays stationary while the built-in body scrolls. Shorter Tall detents, Hug, Capped, numeric, and CSS-length heights do not provide keyboard-aware positioning or scroll space.",},{guidance: true,@@ -167,7 +167,7 @@ export const docs = {</>`,},{- label: 'Mobile keyboard (a long form)',+ label: 'Mobile keyboard',code: `const [isOpen, setIsOpen] = useState(false);<BottomSheetisOpen={isOpen}@@ -175,17 +175,6 @@ export const docs = {label="Add a comment"height="tall"><LongCommentForm />-</BottomSheet>`,- },- {- label: 'Mobile keyboard (a short form)',- code: `const [isOpen, setIsOpen] = useState(false);-<BottomSheet- isOpen={isOpen}- onOpenChange={setIsOpen}- label="Quick note"- height="hug">- <QuickNoteForm /></BottomSheet>`,},{@@ -205,10 +194,10 @@ export const docs = {/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsDense = {description:- 'mobile touch sheet rising from the bottom edge (native <dialog>): grab handle, drag-to-resize snap points, swipe-to-dismiss, visual-viewport mobile-keyboard handling, named height scale, modal (default) or non-modal (hasScrim={false}) presentation',+ 'mobile touch sheet rising from the bottom edge (native <dialog>): grab handle, drag-to-resize snap points, swipe-to-dismiss, fully-expanded Tall visual-viewport mobile-keyboard handling, named height scale, modal (default) or non-modal (hasScrim={false}) presentation',usage: {description:- 'Mobile surface for filters, actions, forms, and detail views. Drag the handle to resize between snap points; flick down to dismiss, up to expand. Modal: focus trap + restore, and Escape dismisses so swipe has a keyboard equivalent. Focused form controls scroll above the visual-viewport keyboard; short sheets temporarily lift without changing height. Actual sheet travel or closing dismisses the keyboard. Content clears the home indicator via safe-area inset.',+ 'Mobile surface for filters, actions, forms, and detail views. Drag the handle to resize between snap points; flick down to dismiss, up to expand. Modal: focus trap + restore, and Escape dismisses so swipe has a keyboard equivalent. Only fully expanded Tall accommodates the mobile keyboard: its outer sheet stays stationary while its body gains scroll space and reveals focused controls. Shorter Tall detents, Hug, Capped, and custom heights do not move or add keyboard scroll space. Tall-sheet travel or closing dismisses the keyboard. Content clears the home indicator via safe-area inset.',bestPractices: [{guidance: true,@@ -232,7 +221,7 @@ export const docsDense = {{guidance: true,description:- "Use 'tall' for long forms. 'hug' supports short forms by lifting temporarily when the keyboard leaves too little usable space.",+ "If a sheet contains a text-entry control that can bring up the mobile keyboard, use 'tall' and keep it fully expanded while editing. Shorter Tall detents, Hug, Capped, numeric, and CSS-length heights are not keyboard-aware.",},{guidance: true,diff --git a/packages/lab/src/BottomSheet/BottomSheet.test.tsx b/packages/lab/src/BottomSheet/BottomSheet.test.tsxindex 023caa30a4..577d8e6523 100644--- a/packages/lab/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/lab/src/BottomSheet/BottomSheet.test.tsx@@ -13,6 +13,7 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {act, render, screen, fireEvent} from '@testing-library/react';import {createRef, useState} from 'react';import {BottomSheet} from './BottomSheet';+import {BottomSheetSwitcher} from './BottomSheetSwitcher';// jsdom doesn't implement <dialog> open/close or pointer capture; stub them.beforeEach(() => {@@ -53,6 +54,7 @@ beforeEach(() => {}),);vi.stubGlobal('cancelAnimationFrame', vi.fn());+ window.scrollTo = vi.fn();});afterEach(() => {@@ -106,6 +108,19 @@ function mockVisualViewport(height: number, offsetTop = 0) {return viewport;}+function mockIOSWebKit() {+ const navigatorMock = Object.create(window.navigator);+ Object.defineProperties(navigatorMock, {+ userAgent: {+ configurable: true,+ value:+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15',+ },+ maxTouchPoints: {configurable: true, value: 5},+ });+ vi.stubGlobal('navigator', navigatorMock);+}+interface ResizeObserverRecord {callback: ResizeObserverCallback;observed: Set<Element>;@@ -178,6 +193,36 @@ function drag(handle: HTMLElement, points: Array<{y: number}>) {fireEvent.pointerUp(handle, {pointerId: 1, clientY: last.y});}+function fireTouchPointer(+ target: Element,+ type: 'pointerdown' | 'pointermove' | 'pointerup',+ {x, y}: {x: number; y: number},+) {+ const event = new Event(type, {bubbles: true, cancelable: true});+ Object.defineProperties(event, {+ clientX: {value: x},+ clientY: {value: y},+ isPrimary: {value: true},+ pointerId: {value: 1},+ pointerType: {value: 'touch'},+ });+ return fireEvent(target, event);+}++function fireTimedPointer(+ target: Element,+ type: 'pointerdown' | 'pointermove' | 'pointerup',+ {time, y}: {time: number; y: number},+) {+ const event = new Event(type, {bubbles: true, cancelable: true});+ Object.defineProperties(event, {+ clientY: {value: y},+ pointerId: {value: 1},+ timeStamp: {value: time},+ });+ return fireEvent(target, event);+}+describe('BottomSheet', () => {it('renders children when open and applies the accessible label', () => {render(@@ -477,91 +522,220 @@ describe('BottomSheet', () => {});describe('mobile keyboard', () => {- it('restores pointer-driven focus scrolling without re-focusing', () => {+ it('prevents native touch focus panning without moving focus early or duplicating events', () => {+ mockIOSWebKit();const onFocus = vi.fn();+ const onBlur = vi.fn();render(- <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">- <input aria-label="Comment" onFocus={onFocus} />+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input+ aria-label="Comment"+ onPointerDown={event => event.stopPropagation()}+ onFocus={onFocus}+ onBlur={onBlur}+ /></BottomSheet>,);- const body = getBody();+ const sheet = getSheet();const input = screen.getByRole('textbox', {name: 'Comment'});const focus = vi.spyOn(input, 'focus');- body.scrollTop = 20;+ sheet.focus();- fireEvent.pointerDown(input, {pointerId: 1, clientY: 200});+ // Pointerdown may still become a scroll gesture, so it must not move+ // focus or open the keyboard early.+ fireTouchPointer(input, 'pointerdown', {x: 20, y: 200});expect(focus).not.toHaveBeenCalled();+ expect(onFocus).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(sheet);- // Emulate the browser panning before it dispatches the focus event.- body.scrollTop = 120;- fireEvent.focus(input, {relatedTarget: null});+ // Pointerup confirms a tap and prevents focus panning. The subsequent+ // native click remains responsible for caret placement.+ fireTouchPointer(input, 'pointerup', {x: 20, y: 200});+ expect(focus).toHaveBeenCalledTimes(1);+ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ expect(document.activeElement).toBe(input);+ expect(onFocus).toHaveBeenCalledTimes(1);+ expect(onBlur).not.toHaveBeenCalled();- expect(body.scrollTop).toBe(20);- expect(focus).not.toHaveBeenCalled();+ // The native click still runs for caret placement and must not produce a+ // second focus transition.+ fireEvent.click(input);expect(onFocus).toHaveBeenCalledTimes(1);+ expect(onBlur).not.toHaveBeenCalled();});- it('restores pointer focus scrolling when a control stops propagation', () => {+ it('does not focus when a touch becomes a scroll gesture', () => {+ mockIOSWebKit();+ const onPreviousBlur = vi.fn();render(- <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <button type="button" onBlur={onPreviousBlur}>+ Previous action+ </button>+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const previous = screen.getByRole('button', {name: 'Previous action'});+ const input = screen.getByRole('textbox', {name: 'Comment'});+ const focus = vi.spyOn(input, 'focus');+ body.scrollTop = 20;+ previous.focus();++ fireTouchPointer(input, 'pointerdown', {x: 20, y: 200});+ fireTouchPointer(input, 'pointermove', {x: 20, y: 240});+ fireTouchPointer(input, 'pointerup', {x: 20, y: 240});++ expect(focus).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(previous);+ expect(onPreviousBlur).not.toHaveBeenCalled();+ });++ it('does not focus when pointer activation is canceled', () => {+ mockIOSWebKit();+ const onFocus = vi.fn();+ const onPreviousBlur = vi.fn();+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <button type="button" onBlur={onPreviousBlur}>+ Previous action+ </button><inputaria-label="Comment"- onPointerDown={event => event.stopPropagation()}+ onPointerDown={event => event.preventDefault()}+ onFocus={onFocus}/></BottomSheet>,);- const body = getBody();+ const previous = screen.getByRole('button', {name: 'Previous action'});const input = screen.getByRole('textbox', {name: 'Comment'});- body.scrollTop = 20;+ const focus = vi.spyOn(input, 'focus');+ previous.focus();- fireEvent.pointerDown(input, {pointerId: 1, clientY: 200});- body.scrollTop = 120;- fireEvent.focus(input, {relatedTarget: null});+ const pointerDownAllowed = fireTouchPointer(input, 'pointerdown', {+ x: 20,+ y: 200,+ });+ fireTouchPointer(input, 'pointerup', {x: 20, y: 200});- expect(body.scrollTop).toBe(20);+ expect(pointerDownAllowed).toBe(false);+ expect(focus).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(previous);+ expect(onFocus).not.toHaveBeenCalled();+ expect(onPreviousBlur).not.toHaveBeenCalled();});- it('restores native focus scrolling without duplicating focus events', () => {+ it('prevents input-to-input focus panning without duplicating focus or blur events', () => {+ mockIOSWebKit();const onTitleBlur = vi.fn();const onCommentFocus = vi.fn();render(- <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall"><input aria-label="Title" onBlur={onTitleBlur} /><input aria-label="Comment" onFocus={onCommentFocus} /></BottomSheet>,);- const body = getBody();const title = screen.getByRole('textbox', {name: 'Title'});const comment = screen.getByRole('textbox', {name: 'Comment'});title.focus();- body.scrollTop = 20;- document.addEventListener(- 'focusout',- () => {- // Emulate the browser scrolling the destination between focusout and- // focus. The hook must restore the position before consumer focus.- body.scrollTop = 120;- },- {once: true},+ const focus = vi.spyOn(comment, 'focus');++ fireTouchPointer(comment, 'pointerdown', {x: 20, y: 200});+ fireTouchPointer(comment, 'pointerup', {x: 20, y: 200});++ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ expect(document.activeElement).toBe(comment);+ expect(onTitleBlur).toHaveBeenCalledTimes(1);+ expect(onCommentFocus).toHaveBeenCalledTimes(1);++ fireEvent.click(comment);+ expect(onTitleBlur).toHaveBeenCalledTimes(1);+ expect(onCommentFocus).toHaveBeenCalledTimes(1);+ });++ it('does not duplicate callbacks during programmatic input-to-input focus', () => {+ mockIOSWebKit();+ const onTitleBlur = vi.fn();+ const onCommentFocus = vi.fn();+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Title" onBlur={onTitleBlur} />+ <input aria-label="Comment" onFocus={onCommentFocus} />+ </BottomSheet>,);+ const title = screen.getByRole('textbox', {name: 'Title'});+ const comment = screen.getByRole('textbox', {name: 'Comment'});+ title.focus();comment.focus();expect(document.activeElement).toBe(comment);- expect(body.scrollTop).toBe(20);expect(onTitleBlur).toHaveBeenCalledTimes(1);expect(onCommentFocus).toHaveBeenCalledTimes(1);});- it('extends internal scrolling and reveals a focused control above the visual viewport', () => {+ it('does not alter ordinary desktop focus when the viewport is unobstructed', () => {+ mockVisualViewport(800);+ const onFocus = vi.fn();+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" onFocus={onFocus} />+ </BottomSheet>,+ );+ const input = screen.getByRole('textbox', {name: 'Comment'});+ const focus = vi.spyOn(input, 'focus');++ input.focus();++ expect(focus).not.toHaveBeenCalledWith({preventScroll: true});+ expect(onFocus).toHaveBeenCalledTimes(1);+ expect(getBody().style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '0px',+ );+ });++ it('keeps Tall geometry fixed while extending and cleaning up its internal scroll range', () => {const viewport = mockVisualViewport(500);render(- <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall"><input aria-label="Comment" /></BottomSheet>,);+ const sheet = getSheet();+ const positioner = getPositioner();const body = getBody();const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(sheet, 'getBoundingClientRect').mockReturnValue(+ rect({top: 0, bottom: 800}),+ );vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(rect({top: 100, bottom: 800}),);@@ -572,13 +746,16 @@ describe('BottomSheet', () => {}),);- act(() => viewport.dispatchEvent(new Event('resize')));- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '0px',- );+ const initialRect = sheet.getBoundingClientRect();input.focus();+ expect(sheet.getBoundingClientRect()).toEqual(initialRect);+ expect(sheet.style.height).toBe('');+ expect(sheet.style.getPropertyValue('--_sheet-budget')).toBe('92dvh');+ expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(+ '',+ );// 300px keyboard overlap + 48px room for Android suggestion UI.expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe('348px',@@ -591,12 +768,53 @@ describe('BottomSheet', () => {expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe('0px',);+ expect(sheet.getBoundingClientRect()).toEqual(initialRect);+ expect(sheet.style.height).toBe('');+ });++ it('smoothly scrolls a focused Tall control above the keyboard', () => {+ mockVisualViewport(500);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ const scrollBy = vi.fn((options: ScrollToOptions) => {+ body.scrollTop += options.top ?? 0;+ });+ Object.defineProperty(body, 'scrollBy', {+ configurable: true,+ value: scrollBy,+ });+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>+ rect({+ top: 660 - body.scrollTop,+ bottom: 700 - body.scrollTop,+ }),+ );++ input.focus();++ expect(scrollBy).toHaveBeenCalledWith({top: 248, behavior: 'smooth'});});it('does not add clearance or scroll when the viewport is unobstructed', () => {mockVisualViewport(800);render(- <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall"><input aria-label="Comment" /></BottomSheet>,);@@ -617,64 +835,178 @@ describe('BottomSheet', () => {expect(body.scrollTop).toBe(0);});- it('keeps a hug sheet at its intrinsic height while adding keyboard scroll range', () => {- const viewport = mockVisualViewport(500);+ it('does not accommodate the keyboard at a shorter Tall detent', () => {+ mockIOSWebKit();+ const observers = mockResizeObserverInstances();+ const viewport = mockVisualViewport(800);render(<BottomSheetisOpenonOpenChange={() => {}}label="Add a comment"- height="hug">+ height="tall"><input aria-label="Comment" /></BottomSheet>,);const sheet = getSheet();- const positioner = getPositioner();const body = getBody();const input = screen.getByRole('textbox', {name: 'Comment'});- const currentLift = () =>- Number.parseFloat(- positioner.style.getPropertyValue('--_sheet-keyboard-lift'),- ) || 0;- vi.spyOn(sheet, 'getBoundingClientRect').mockImplementation(() =>- rect({top: 400 - currentLift(), bottom: 800 - currentLift()}),- );- vi.spyOn(body, 'getBoundingClientRect').mockImplementation(() =>- rect({top: 450 - currentLift(), bottom: 800 - currentLift()}),- );- vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>- rect({- top: 700 - currentLift() - body.scrollTop,- bottom: 740 - currentLift() - body.scrollTop,- }),+ const sheetObserver = observers.find(instance =>+ instance.observed.has(sheet),);+ expect(sheetObserver).toBeDefined();+ act(() => {+ sheetObserver?.callback(+ [{contentRect: rect({top: 0, bottom: 800})} as ResizeObserverEntry],+ sheetObserver as unknown as ResizeObserver,+ );+ });- input.focus();+ fireTimedPointer(getHandle(), 'pointerdown', {time: 0, y: 0});+ fireTimedPointer(getHandle(), 'pointermove', {time: 1000, y: 240});+ fireTimedPointer(getHandle(), 'pointerup', {time: 2000, y: 240});+ expect(sheet.style.transform).toBe('translateY(400px)');- expect(sheet.style.height).toBe('400px');- // The body initially has only 50px above the keyboard. Lift the stable- // 400px sheet by 38px so a 40px control plus the 48px clearance fits.- expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(- '38px',+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 500, bottom: 1200}),);- expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '310px',+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 700, bottom: 740}),);- expect(body.scrollTop).toBe(250);+ viewport.height = 500;+ const focus = vi.spyOn(input, 'focus');+ fireTouchPointer(input, 'pointerdown', {x: 20, y: 700});+ fireTouchPointer(input, 'pointerup', {x: 20, y: 700});+ expect(focus).not.toHaveBeenCalled();- viewport.height = 800;+ focus.mockRestore();+ input.focus();act(() => viewport.dispatchEvent(new Event('resize')));- expect(sheet.style.height).toBe('');- expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(++ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe('0px',);+ expect(body.scrollTop).toBe(0);+ expect(sheet.style.transform).toBe('translateY(400px)');});- it('re-reveals a focused control when content layout changes', () => {+ it.each([+ ['Hug', 'hug'],+ ['Capped', 'capped'],+ ['numeric', 480],+ ['custom CSS', '70dvh'],+ ] as const)(+ 'does not add keyboard behavior to a %s height',+ (_label, height) => {+ mockIOSWebKit();+ const viewport = mockVisualViewport(500);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height={height}>+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const sheet = getSheet();+ const positioner = getPositioner();+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ const focus = vi.spyOn(input, 'focus');+ const sheetFocus = vi.spyOn(sheet, 'focus');+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 400, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 700, bottom: 740}),+ );+ body.scrollTop = 20;++ fireEvent.touchStart(input);+ fireTouchPointer(input, 'pointerdown', {x: 20, y: 200});+ fireTouchPointer(input, 'pointerup', {x: 20, y: 200});+ fireEvent.pointerDown(input, {pointerId: 1, clientY: 200});+ body.scrollTop = 120;+ fireEvent.focus(input, {relatedTarget: null});+ act(() => viewport.dispatchEvent(new Event('resize')));++ expect(body.scrollTop).toBe(120);+ expect(focus).not.toHaveBeenCalled();+ expect(sheetFocus).not.toHaveBeenCalled();+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe('');+ expect(+ positioner.style.getPropertyValue('--_sheet-keyboard-lift'),+ ).toBe('');+ expect(sheet.style.height).toBe('');+ },+ );++ it.each([+ ['standalone no-scrim', 'standalone', false],+ ['modal switcher', 'switcher', true],+ ['no-scrim switcher', 'switcher', false],+ ] as const)(+ 'supports Tall internal keyboard scrolling in a %s presentation',+ (_label, host, hasScrim) => {+ mockVisualViewport(500);+ const content = <input aria-label="Comment" />;+ const result =+ host === 'standalone'+ ? render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall"+ hasScrim={hasScrim}>+ {content}+ </BottomSheet>,+ )+ : render(+ <BottomSheetSwitcher+ activeSheet="comment"+ onActiveSheetChange={() => {}}+ hasScrim={hasScrim}>+ <BottomSheet+ sheetId="comment"+ label="Add a comment"+ height="tall">+ {content}+ </BottomSheet>+ </BottomSheetSwitcher>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>+ rect({+ top: 660 - body.scrollTop,+ bottom: 700 - body.scrollTop,+ }),+ );++ input.focus();++ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',+ );+ expect(body.scrollTop).toBe(248);+ result.unmount();+ },+ );++ it('re-reveals a focused Tall control when content layout changes', () => {const observers = mockResizeObserverInstances();mockVisualViewport(500);render(- <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall"><input aria-label="Comment" /></BottomSheet>,);@@ -704,9 +1036,8 @@ describe('BottomSheet', () => {expect(body.scrollTop).toBe(448);});- it('re-reveals a focused control when the sheet height changes', () => {- const observers = mockResizeObserverInstances();- mockVisualViewport(500);+ it('retains Tall keyboard scroll space during travel until the viewport recovers', () => {+ const viewport = mockVisualViewport(500);render(<BottomSheetisOpen@@ -720,199 +1051,176 @@ describe('BottomSheet', () => {const positioner = getPositioner();const body = getBody();const input = screen.getByRole('textbox', {name: 'Comment'});- let isShort = false;- const currentLift = () =>- Number.parseFloat(- positioner.style.getPropertyValue('--_sheet-keyboard-lift'),- ) || 0;- vi.spyOn(sheet, 'getBoundingClientRect').mockImplementation(() =>- rect({- top: (isShort ? 400 : 0) - currentLift(),- bottom: 800 - currentLift(),- }),+ vi.spyOn(sheet, 'getBoundingClientRect').mockReturnValue(+ rect({top: 0, bottom: 800}),);- vi.spyOn(body, 'getBoundingClientRect').mockImplementation(() =>+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>rect({- top: (isShort ? 450 : 100) - currentLift(),- bottom: 800 - currentLift(),+ top: 660 - body.scrollTop,+ bottom: 700 - body.scrollTop,}),);- vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() => {- const bodyTop = isShort ? 450 : 100;- return rect({- top: bodyTop + 560 - currentLift() - body.scrollTop,- bottom: bodyTop + 600 - currentLift() - body.scrollTop,- });- });input.focus();expect(body.scrollTop).toBe(248);+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',+ );- isShort = true;- const observer = observers.find(instance => instance.observed.has(body));- expect(observer?.observed.has(sheet)).toBe(true);- act(() => {- observer?.callback([], observer as unknown as ResizeObserver);+ const pointerDownAllowed = fireEvent.pointerDown(getHandle(), {+ pointerId: 1,+ clientY: 0,});+ expect(pointerDownAllowed).toBe(false);+ expect(document.activeElement).toBe(input);++ fireEvent.pointerMove(getHandle(), {pointerId: 1, clientY: 40});+ expect(document.activeElement).toBe(sheet);expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(- '38px',+ '',+ );+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',+ );+ expect(body.scrollTop).toBe(248);++ viewport.height = 800;+ act(() => viewport.dispatchEvent(new Event('resize')));+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '0px',);- expect(body.scrollTop).toBe(560);- expect(input.getBoundingClientRect().bottom).toBe(452);});- it('retains keyboard layout during travel until the viewport recovers', () => {+ it('retains Tall keyboard scroll space after blur until the viewport recovers', () => {const viewport = mockVisualViewport(500);render(<BottomSheetisOpenonOpenChange={() => {}}label="Add a comment"- height="hug">+ height="tall"><input aria-label="Comment" /></BottomSheet>,);- const sheet = getSheet();- const positioner = getPositioner();const body = getBody();const input = screen.getByRole('textbox', {name: 'Comment'});- const currentLift = () =>- Number.parseFloat(- positioner.style.getPropertyValue('--_sheet-keyboard-lift'),- ) || 0;- vi.spyOn(sheet, 'getBoundingClientRect').mockImplementation(() =>- rect({top: 400 - currentLift(), bottom: 800 - currentLift()}),- );- vi.spyOn(body, 'getBoundingClientRect').mockImplementation(() =>- rect({top: 450 - currentLift(), bottom: 800 - currentLift()}),+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),);vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>rect({- top: 700 - currentLift() - body.scrollTop,- bottom: 740 - currentLift() - body.scrollTop,+ top: 660 - body.scrollTop,+ bottom: 700 - body.scrollTop,}),);-input.focus();- expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(- '38px',+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',);- expect(body.scrollTop).toBe(250);- fireEvent.pointerDown(getHandle(), {pointerId: 1, clientY: 0});- fireEvent.pointerMove(getHandle(), {pointerId: 1, clientY: 40});+ input.blur();- expect(document.activeElement).toBe(sheet);- expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(- '38px',- );expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(- '310px',+ '348px',);- expect(body.scrollTop).toBe(250);viewport.height = 800;act(() => viewport.dispatchEvent(new Event('resize')));- expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(- '0px',- );expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe('0px',);});- it('re-reveals after the sheet entrance transform settles', () => {- mockVisualViewport(500);- render(+ it('blurs the focused Tall field and retains its inset until the viewport recovers', () => {+ const viewport = mockVisualViewport(500);+ const onOpenChange = vi.fn();+ const content = (isOpen: boolean) => (<BottomSheet- isOpen- onOpenChange={() => {}}+ isOpen={isOpen}+ onOpenChange={onOpenChange}label="Add a comment"- height="hug">+ height="tall"><input aria-label="Comment" />- </BottomSheet>,+ </BottomSheet>);- const sheet = getSheet();- const positioner = getPositioner();+ const {rerender} = render(content(true));const body = getBody();const input = screen.getByRole('textbox', {name: 'Comment'});- let entranceOffset = 100;- const currentLift = () =>- Number.parseFloat(- positioner.style.getPropertyValue('--_sheet-keyboard-lift'),- ) || 0;- vi.spyOn(sheet, 'getBoundingClientRect').mockImplementation(() =>- rect({- top: 400 + entranceOffset - currentLift(),- bottom: 800 + entranceOffset - currentLift(),- }),- );- vi.spyOn(body, 'getBoundingClientRect').mockImplementation(() =>- rect({- top: 450 + entranceOffset - currentLift(),- bottom: 800 + entranceOffset - currentLift(),- }),+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),);vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>rect({- top: 700 + entranceOffset - currentLift() - body.scrollTop,- bottom: 740 + entranceOffset - currentLift() - body.scrollTop,+ top: 660 - body.scrollTop,+ bottom: 700 - body.scrollTop,}),);-input.focus();- expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(- '138px',+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',);- entranceOffset = 0;- fireEvent.transitionEnd(sheet, {propertyName: 'transform'});+ rerender(content(false));- expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(- '38px',+ expect(document.activeElement).not.toBe(input);+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',);- expect(input.getBoundingClientRect().bottom).toBe(452);- });- it('keeps the keyboard open for a handle tap and blurs after travel starts', () => {- render(- <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">- <input aria-label="Comment" />- </BottomSheet>,+ viewport.height = 800;+ act(() => viewport.dispatchEvent(new Event('resize')));+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '0px',);- const input = screen.getByRole('textbox', {name: 'Comment'});- input.focus();-- const pointerDownAllowed = fireEvent.pointerDown(getHandle(), {- pointerId: 1,- clientY: 0,- });- expect(pointerDownAllowed).toBe(false);- expect(document.activeElement).toBe(input);-- fireEvent.pointerMove(getHandle(), {pointerId: 1, clientY: 40});-- expect(document.activeElement).toBe(getSheet());});- it('blurs the focused field when a non-drag close starts', () => {- const onOpenChange = vi.fn();- const content = (isOpen: boolean) => (- <BottomSheet- isOpen={isOpen}- onOpenChange={onOpenChange}- label="Add a comment">- <input aria-label="Comment" />- </BottomSheet>+ it('retains Tall keyboard scroll space through a switcher handoff until the viewport recovers', () => {+ const viewport = mockVisualViewport(500);+ const content = (activeSheet: string) => (+ <BottomSheetSwitcher+ activeSheet={activeSheet}+ onActiveSheetChange={() => {}}>+ <BottomSheet sheetId="comment" label="Add a comment" height="tall">+ <input aria-label="Comment" />+ </BottomSheet>+ <BottomSheet sheetId="confirmation" label="Confirmation">+ Confirmation+ </BottomSheet>+ </BottomSheetSwitcher>);- const {rerender} = render(content(true));+ const {rerender} = render(content('comment'));+ const body = getBody();const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>+ rect({+ top: 660 - body.scrollTop,+ bottom: 700 - body.scrollTop,+ }),+ );input.focus();+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',+ );- rerender(content(false));+ rerender(content('confirmation'));expect(document.activeElement).not.toBe(input);+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',+ );++ viewport.height = 800;+ act(() => viewport.dispatchEvent(new Event('resize')));+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '0px',+ );});});diff --git a/packages/lab/src/BottomSheet/BottomSheet.tsx b/packages/lab/src/BottomSheet/BottomSheet.tsxindex 738cf821b9..0e2a50ceac 100644--- a/packages/lab/src/BottomSheet/BottomSheet.tsx+++ b/packages/lab/src/BottomSheet/BottomSheet.tsx@@ -102,7 +102,6 @@ const styles = stylex.create({display: 'flex',justifyContent: 'center',pointerEvents: 'none',- transform: 'translateY(calc(0px - var(--_sheet-keyboard-lift, 0px)))',},positionerHidden: {display: 'none',@@ -122,7 +121,7 @@ interface BottomSheetSharedProps extends BaseProps<HTMLDivElement> {/** Sheet content, rendered below the grab handle in a scrollable area. */children: ReactNode;- /** Height budget or custom CSS length. @default 'capped' */+ /** Height budget or custom CSS length. Only fully expanded Tall is keyboard-aware. @default 'capped' */height?: BottomSheetHeight | number | string;}@@ -188,7 +187,6 @@ function StandaloneBottomSheet({...props}: StandaloneBottomSheetProps) {const dialogRef = useRef<HTMLDialogElement | null>(null);- const positionerRef = useRef<HTMLDivElement | null>(null);const panelRef = useRef<HTMLDivElement | null>(null);const triggerRef = useRef<HTMLElement | null>(null);const [isPresented, setIsPresented] = useState(isOpen);@@ -304,7 +302,7 @@ function StandaloneBottomSheet({onCancel={handleCancel}onClick={handleClick}onKeyDown={handleKeyDown}>- <div ref={positionerRef} {...stylex.props(styles.positioner)}>+ <div {...stylex.props(styles.positioner)}><BottomSheetPanel{...props}ref={ref}@@ -313,7 +311,6 @@ function StandaloneBottomSheet({xstyle={xstyle}onDismiss={close}onScrimOpacity={handleScrimOpacity}- positionerRef={positionerRef}onElementChange={handlePanelElementChange}onMotionComplete={handleMotionComplete}>{children}@@ -363,7 +360,6 @@ function SwitcherBottomSheetItem({phase === 'exiting';const isPresented = phase !== 'hidden';const isTopSheet = phase === 'active' || phase === 'entering';- const positionerRef = useRef<HTMLDivElement | null>(null);const panelRef = useRef<HTMLDivElement | null>(null);const previousPhaseRef = useRef(phase);const previousPhase = previousPhaseRef.current;@@ -442,7 +438,6 @@ function SwitcherBottomSheetItem({return (<div- ref={positionerRef}{...stylex.props(styles.positioner,!isPresented && styles.positionerHidden,@@ -459,7 +454,6 @@ function SwitcherBottomSheetItem({xstyle={xstyle}onDismiss={close}onScrimOpacity={handleScrimOpacity}- positionerRef={positionerRef}onElementChange={handlePanelElementChange}onMotionStart={handleMotionStart}onMotionComplete={handleMotionComplete}>diff --git a/packages/lab/src/BottomSheet/BottomSheetPanel.tsx b/packages/lab/src/BottomSheet/BottomSheetPanel.tsxindex c0a8534928..7385d222b2 100644--- a/packages/lab/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/lab/src/BottomSheet/BottomSheetPanel.tsx@@ -25,7 +25,6 @@ import {useImperativeHandle,useLayoutEffect,useRef,- type RefObject,type ReactNode,} from 'react';import * as stylex from '@stylexjs/stylex';@@ -124,9 +123,11 @@ const styles = stylex.create({flexGrow: 1,minHeight: 0,overflowY: 'auto',- scrollPaddingBlockEnd: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,overscrollBehavior: 'none',touchAction: 'pan-y',+ },+ tallKeyboardBody: {+ scrollPaddingBlockEnd: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,'::after': {content: '""',display: 'block',@@ -164,7 +165,6 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {children: ReactNode;onDismiss: () => void;onScrimOpacity: (opacity: number) => void;- positionerRef?: RefObject<HTMLDivElement | null>;onElementChange?: (element: HTMLDivElement | null) => void;onMotionStart?: (motion: BottomSheetPanelMotion) => void;onMotionComplete?: (motion: BottomSheetPanelMotion) => void;@@ -291,7 +291,6 @@ export function BottomSheetPanel({xstyle,onDismiss,onScrimOpacity,- positionerRef,onElementChange,onMotionStart,onMotionComplete,@@ -299,7 +298,6 @@ export function BottomSheetPanel({}: BottomSheetPanelProps) {const elementRef = useRef<HTMLDivElement | null>(null);const bodyElementRef = useRef<HTMLDivElement | null>(null);- const fallbackPositionerRef = useRef<HTMLDivElement | null>(null);const previousStateRef = useRef(state);const reactivatedEntranceRef = useRef(false);const onMotionStartRef = useRef(onMotionStart);@@ -323,6 +321,7 @@ export function BottomSheetPanel({}, [onMotionComplete, onMotionStart, state]);const isInteractive = state.kind === 'open';+ const isPresented = state.kind !== 'hidden';const isRetained = state.kind === 'retained';const isInactive = isRetained || state.kind === 'exiting';const isClosing = state.kind === 'exiting';@@ -362,10 +361,11 @@ export function BottomSheetPanel({useMobileKeyboard({bodyRef: bodyElementRef,bottomClearance: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,+ isEnabled: height === 'tall',+ isFullyExpanded: settledOffset === 0,isSheetTraveling: isDragging && dragOffset !== settledOffset,isOpen: isInteractive,- positionerRef: positionerRef ?? fallbackPositionerRef,- preserveSheetHeight: height === 'hug',+ isPresented,sheetRef: elementRef,});// Keep controller registration attached to one stable host ref. React@@ -462,7 +462,13 @@ export function BottomSheetPanel({aria-hidden="true"><div {...stylex.props(styles.handlePill)} /></div>- <div {...stylex.props(styles.body)} {...bodyProps} ref={setBodyElement}>+ <div+ {...stylex.props(+ styles.body,+ height === 'tall' && styles.tallKeyboardBody,+ )}+ {...bodyProps}+ ref={setBodyElement}>{children}</div></div>diff --git a/packages/lab/src/BottomSheet/useMobileKeyboard.ts b/packages/lab/src/BottomSheet/useMobileKeyboard.tsindex 0774d838d8..4cdec8557f 100644--- a/packages/lab/src/BottomSheet/useMobileKeyboard.ts+++ b/packages/lab/src/BottomSheet/useMobileKeyboard.ts@@ -8,18 +8,16 @@* @output Exports internal useMobileKeyboard hook* @position Internal to BottomSheet; not exported from the lab entry point*- * Keeps focused controls inside the visual viewport without resizing the- * sheet. When the on-screen keyboard covers the stable layout viewport, it- * extends the body's internal scroll range and reveals only the focused- * control. A short sheet lifts just enough to expose a usable focus area while- * retaining its measured height. Starting sheet travel or closing the sheet- * blurs the field and dismisses the keyboard.+ * Gives a fully expanded, explicitly Tall sheet a keyboard-aware internal+ * scroll range while leaving the sheet itself stationary. Shorter detents and+ * other heights opt out entirely. Starting Tall-sheet travel or closing the+ * sheet blurs the field and dismisses the keyboard.*/import {useEffect, useRef, type RefObject} from 'react';const MOBILE_KEYBOARD_INSET_VAR = '--_sheet-keyboard-inset';-const MOBILE_KEYBOARD_LIFT_VAR = '--_sheet-keyboard-lift';+const TOUCH_FOCUS_MOVE_THRESHOLD = 10;const NON_TEXT_INPUT_TYPES = new Set(['button','checkbox',@@ -36,13 +34,18 @@ const NON_TEXT_INPUT_TYPES = new Set([interface UseMobileKeyboardOptions {bodyRef: RefObject<HTMLDivElement | null>;bottomClearance: number;+ isEnabled: boolean;+ isFullyExpanded: boolean;isSheetTraveling: boolean;isOpen: boolean;- positionerRef: RefObject<HTMLDivElement | null>;- preserveSheetHeight: boolean;+ isPresented: boolean;sheetRef: RefObject<HTMLDivElement | null>;}+interface KeyboardGeometry {+ bodyBottom: number;+}+interface FocusScrollSnapshot {target: HTMLElement;elements: Array<{@@ -54,11 +57,12 @@ interface FocusScrollSnapshot {windowY: number;}-interface KeyboardGeometry {- bodyBottom: number;- bodyTop: number;- focusedHeight: number;- sheetTop: number | null;+interface PendingTouchFocus {+ clientX: number;+ clientY: number;+ control: HTMLElement;+ pointerDown: PointerEvent;+ pointerId: number;}function captureFocusScroll(target: HTMLElement): FocusScrollSnapshot {@@ -91,6 +95,14 @@ function getVisualViewportBounds(): {top: number; bottom: number} {};}+function isIOSWebKit(): boolean {+ const userAgent = window.navigator.userAgent;+ return (+ /iPad|iPhone|iPod/.test(userAgent) ||+ (/Macintosh/.test(userAgent) && window.navigator.maxTouchPoints > 1)+ );+}+function isTextEntryControl(element: Element | null): element is HTMLElement {if (element instanceof HTMLTextAreaElement) {return !element.disabled && !element.readOnly;@@ -131,17 +143,22 @@ function findTextEntryControl(export function useMobileKeyboard({bodyRef,bottomClearance,+ isEnabled,+ isFullyExpanded,isSheetTraveling,isOpen,- positionerRef,- preserveSheetHeight,+ isPresented,sheetRef,}: UseMobileKeyboardOptions): void {const hasKeyboardLayoutRef = useRef(false);const retainKeyboardLayoutRef = useRef(false);+ const isActiveRef = useRef(isOpen);+ const isFullyExpandedRef = useRef(isFullyExpanded);+ isActiveRef.current = isOpen;+ isFullyExpandedRef.current = isFullyExpanded;useEffect(() => {- if (!isSheetTraveling) {+ if (!isEnabled || !isSheetTraveling) {return;}const sheet = sheetRef.current;@@ -152,17 +169,17 @@ export function useMobileKeyboard({activeElement !== sheet &&sheet.contains(activeElement)) {- // Keep the current keyboard lift/scroll range while focusing the sheet+ // Keep the current keyboard scroll range while focusing the sheet// dismisses the keyboard. Viewport resize events unwind that layout as- // the visual viewport recovers, so the sheet does not jump away from the- // pointer on the first drag frame.+ // the visual viewport recovers, avoiding a content jump on the first+ // drag frame.retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;sheet.focus({preventScroll: true});}- }, [isSheetTraveling, sheetRef]);+ }, [isEnabled, isSheetTraveling, sheetRef]);useEffect(() => {- if (isOpen) {+ if (!isEnabled || !isPresented || isOpen) {return;}const sheet = sheetRef.current;@@ -173,44 +190,62 @@ export function useMobileKeyboard({activeElement !== sheet &&sheet.contains(activeElement)) {+ retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;activeElement.blur();}- }, [isOpen, sheetRef]);+ }, [isEnabled, isOpen, isPresented, sheetRef]);useEffect(() => {const body = bodyRef.current;- const positioner = positionerRef.current;const sheet = sheetRef.current;- if (!isOpen || !body || !positioner) {+ if (!isEnabled || !isPresented || !body) {return;}- let isSheetHeightFrozen = false;- let keyboardLift = 0;let keyboardGeometry: KeyboardGeometry | null = null;let pendingFocusScroll: FocusScrollSnapshot | null = null;let pendingPointerFocusScroll: FocusScrollSnapshot | null = null;-- const setKeyboardLift = (nextLift: number) => {- if (nextLift === keyboardLift) {- return;- }- keyboardLift = nextLift;- positioner.style.setProperty(MOBILE_KEYBOARD_LIFT_VAR, `${nextLift}px`);- };+ let pendingTouchFocus: PendingTouchFocus | null = null;+ const preventFocusScroll = isIOSWebKit();const clearKeyboardLayout = () => {body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, '0px');- setKeyboardLift(0);- if (isSheetHeightFrozen && sheet) {- sheet.style.removeProperty('height');- isSheetHeightFrozen = false;- }keyboardGeometry = null;hasKeyboardLayoutRef.current = false;retainKeyboardLayoutRef.current = false;};+ const restoreScrollSnapshot = (snapshot: FocusScrollSnapshot) => {+ for (const {element, scrollLeft, scrollTop} of snapshot.elements) {+ if (element.scrollLeft !== scrollLeft) {+ element.scrollLeft = scrollLeft;+ }+ if (element.scrollTop !== scrollTop) {+ element.scrollTop = scrollTop;+ }+ }+ if (+ window.scrollX !== snapshot.windowX ||+ window.scrollY !== snapshot.windowY+ ) {+ window.scrollTo(snapshot.windowX, snapshot.windowY);+ }+ };++ const scrollBodyBy = (distance: number, smoothly: boolean) => {+ if (typeof body.scrollBy !== 'function') {+ body.scrollTop += distance;+ return;+ }+ const reduceMotion =+ typeof window.matchMedia === 'function' &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ body.scrollBy({+ top: distance,+ behavior: smoothly && !reduceMotion ? 'smooth' : 'auto',+ });+ };+const applyKeyboardGeometry = (geometry: KeyboardGeometry) => {const viewport = getVisualViewportBounds();// A collapsed detent can extend the body below the layout viewport even@@ -227,50 +262,93 @@ export function useMobileKeyboard({return;}- const targetBodyTop = Math.max(- viewport.top,- viewport.bottom - bottomClearance - geometry.focusedHeight,- );- const neededLift = Math.max(0, geometry.bodyTop - targetBodyTop);- const maxLift =- geometry.sheetTop == null- ? neededLift- : Math.max(0, geometry.sheetTop - viewport.top);- const nextLift = Math.min(neededLift, maxLift);- setKeyboardLift(nextLift);-- const bodyBottom = geometry.bodyBottom - nextLift;const inset = Math.max(0,- bodyBottom - (viewport.bottom - bottomClearance),+ geometry.bodyBottom - (viewport.bottom - bottomClearance),);body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);};- // Let the browser perform pointer focus normally so caret placement, click- // behavior, and the focus lifecycle stay native. Capture scroll positions- // before its default focus action so they can be restored below.+ // Wait until pointerup confirms a touch was a tap, then focus before the+ // native click so preventScroll suppresses page panning while the click+ // still owns caret placement. Holding the original pointerdown event lets+ // consumer preventDefault calls remain authoritative after capture.const rememberPointerFocusScroll = (event: PointerEvent) => {const control = findTextEntryControl(event.target, body);pendingPointerFocusScroll =- control && control !== document.activeElement+ isFullyExpandedRef.current &&+ control &&+ control !== document.activeElement? captureFocusScroll(control): null;+ pendingTouchFocus =+ isActiveRef.current &&+ isFullyExpandedRef.current &&+ event.pointerType === 'touch' &&+ event.isPrimary !== false &&+ control &&+ control !== document.activeElement+ ? {+ clientX: event.clientX,+ clientY: event.clientY,+ control,+ pointerDown: event,+ pointerId: event.pointerId,+ }+ : null;+ };+ const clearPendingTouchFocus = () => {+ if (pendingPointerFocusScroll?.target === pendingTouchFocus?.control) {+ pendingPointerFocusScroll = null;+ }+ pendingTouchFocus = null;+ };+ const handlePointerMove = (event: PointerEvent) => {+ if (+ pendingTouchFocus?.pointerId === event.pointerId &&+ Math.hypot(+ event.clientX - pendingTouchFocus.clientX,+ event.clientY - pendingTouchFocus.clientY,+ ) > TOUCH_FOCUS_MOVE_THRESHOLD+ ) {+ clearPendingTouchFocus();+ }+ };+ const handlePointerCancel = (event: PointerEvent) => {+ if (pendingTouchFocus?.pointerId === event.pointerId) {+ clearPendingTouchFocus();+ }+ };+ const preventTouchFocusScroll = (event: PointerEvent) => {+ const pending = pendingTouchFocus;+ pendingTouchFocus = null;+ if (+ !pending ||+ !isFullyExpandedRef.current ||+ pending.pointerId !== event.pointerId ||+ pending.pointerDown.defaultPrevented ||+ event.defaultPrevented ||+ findTextEntryControl(event.target, body) !== pending.control ||+ document.activeElement === pending.control+ ) {+ if (pendingPointerFocusScroll?.target === pending?.control) {+ pendingPointerFocusScroll = null;+ }+ return;+ }++ pending.control.focus({preventScroll: true});};- // Keyboard and programmatic focus transitions cannot pass preventScroll to- // the browser. After consumer blur handlers run but before the destination- // scrolls into view, snapshot every scrollable ancestor, then restore those- // positions during the destination's focus event. This prevents native- // panning without re-entering the browser's focus lifecycle or duplicating- // consumer focus/blur callbacks.+ // Keyboard and programmatic focus transitions cannot supply preventScroll.+ // Restore their pre-focus scroll positions without re-entering the focus+ // lifecycle, so consumer focus and blur callbacks remain single events.const rememberFocusScroll = (event: FocusEvent) => {const control = findTextEntryControl(event.relatedTarget, body);- if (!control) {+ if (!isFullyExpandedRef.current || !control) {pendingFocusScroll = null;return;}-pendingFocusScroll = captureFocusScroll(control);};const restoreFocusScroll = (event: FocusEvent) => {@@ -283,29 +361,15 @@ export function useMobileKeyboard({: null;pendingFocusScroll = null;pendingPointerFocusScroll = null;- if (!snapshot || snapshot.target !== control) {- return;- }-- for (const {element, scrollLeft, scrollTop} of snapshot.elements) {- if (element.scrollLeft !== scrollLeft) {- element.scrollLeft = scrollLeft;- }- if (element.scrollTop !== scrollTop) {- element.scrollTop = scrollTop;- }- }- if (- window.scrollX !== snapshot.windowX ||- window.scrollY !== snapshot.windowY- ) {- window.scrollTo(snapshot.windowX, snapshot.windowY);+ if (snapshot?.target === control) {+ restoreScrollSnapshot(snapshot);}};const revealFocusedControl = () => {const activeElement = document.activeElement;if (+ !isFullyExpandedRef.current ||!(activeElement instanceof HTMLElement) ||!body.contains(activeElement) ||!isTextEntryControl(activeElement)@@ -323,81 +387,39 @@ export function useMobileKeyboard({const measuredBodyRect = body.getBoundingClientRect();const measuredFocusedRect = activeElement.getBoundingClientRect();const viewport = getVisualViewportBounds();- // The positioner's transform is included in client rects. Add the- // current lift back before calculating the next one so repeated- // viewport/layout observations converge instead of alternating between- // lifted and unlifted values.- const unliftedBodyTop = measuredBodyRect.top + keyboardLift;- const unliftedBodyBottom = measuredBodyRect.bottom + keyboardLift;- const unliftedFocusedTop = measuredFocusedRect.top + keyboardLift;- const unliftedFocusedBottom = measuredFocusedRect.bottom + keyboardLift;- const overlap = Math.max(0, unliftedBodyBottom - viewport.bottom);+ const overlap = Math.max(0, measuredBodyRect.bottom - viewport.bottom);// The extra clearance leaves room for mobile suggestion UI, but only// while the visual viewport actually overlaps the sheet. With no// obstruction, ordinary desktop and hardware-keyboard focus must not// shift an already visible control.const clearance = overlap > 0 ? bottomClearance : 0;- if (overlap > 0 && preserveSheetHeight && sheet && !isSheetHeightFrozen) {- // A normal-flow spacer would otherwise increase a hug sheet's- // intrinsic height. Lock its current geometry before growing the- // internal scroll range, then release it when the obstruction clears.- sheet.style.height = `${sheet.getBoundingClientRect().height}px`;- isSheetHeightFrozen = true;- }-- let nextLift = 0;- const measuredSheetTop = sheet?.getBoundingClientRect().top;- const unliftedSheetTop =- measuredSheetTop == null ? null : measuredSheetTop + keyboardLift;- if (overlap > 0) {- const focusedHeight = measuredFocusedRect.height;- const targetBodyTop = Math.max(- viewport.top,- viewport.bottom - clearance - focusedHeight,- );- const neededLift = Math.max(0, unliftedBodyTop - targetBodyTop);- const maxLift =- unliftedSheetTop == null- ? neededLift- : Math.max(0, unliftedSheetTop - viewport.top);- nextLift = Math.min(neededLift, maxLift);- }- setKeyboardLift(nextLift);keyboardGeometry =overlap > 0? {- bodyBottom: unliftedBodyBottom,- bodyTop: unliftedBodyTop,- focusedHeight: measuredFocusedRect.height,- sheetTop: unliftedSheetTop,+ bodyBottom: measuredBodyRect.bottom,}: null;hasKeyboardLayoutRef.current = overlap > 0;- const bodyTop = unliftedBodyTop - nextLift;- const bodyBottom = unliftedBodyBottom - nextLift;- const focusedTop = unliftedFocusedTop - nextLift;- const focusedBottom = unliftedFocusedBottom - nextLift;const inset =overlap > 0- ? Math.max(0, bodyBottom - (viewport.bottom - clearance))+ ? Math.max(0, measuredBodyRect.bottom - (viewport.bottom - clearance)): 0;body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);- if (overlap === 0 && isSheetHeightFrozen && sheet) {- sheet.style.removeProperty('height');- isSheetHeightFrozen = false;- }- const safeTop = Math.max(bodyTop, viewport.top);- const safeBottom = Math.min(bodyBottom, viewport.bottom - clearance);+ const safeTop = Math.max(measuredBodyRect.top, viewport.top);+ const safeBottom = Math.min(+ measuredBodyRect.bottom,+ viewport.bottom - clearance,+ );if (safeBottom <= safeTop) {return;}- if (focusedBottom > safeBottom) {- body.scrollTop += focusedBottom - safeBottom;- } else if (focusedTop < safeTop) {- body.scrollTop -= safeTop - focusedTop;+ if (measuredFocusedRect.bottom > safeBottom) {+ scrollBodyBy(measuredFocusedRect.bottom - safeBottom, overlap > 0);+ } else if (measuredFocusedRect.top < safeTop) {+ scrollBodyBy(measuredFocusedRect.top - safeTop, overlap > 0);}};@@ -466,6 +488,12 @@ export function useMobileKeyboard({refreshObservedLayout();scheduleReveal();};+ const handleFocusOut = () => {+ // Keep the added scroll range while the keyboard animates away. A focus+ // transition to another text-entry control cancels this in focusin.+ retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;+ scheduleReveal();+ };const handleSheetTransitionEnd = (event: TransitionEvent) => {if (event.target === sheet && event.propertyName === 'transform') {scheduleReveal();@@ -473,13 +501,20 @@ export function useMobileKeyboard({};const viewport = window.visualViewport;- // Capture before consumer handlers so stopPropagation cannot opt the- // browser back into native focus panning accidentally.- document.addEventListener('pointerdown', rememberPointerFocusScroll, true);- document.addEventListener('focusout', rememberFocusScroll);- body.addEventListener('focus', restoreFocusScroll, true);+ if (preventFocusScroll) {+ document.addEventListener(+ 'pointerdown',+ rememberPointerFocusScroll,+ true,+ );+ document.addEventListener('pointermove', handlePointerMove, true);+ document.addEventListener('pointercancel', handlePointerCancel, true);+ document.addEventListener('pointerup', preventTouchFocusScroll);+ document.addEventListener('focusout', rememberFocusScroll);+ body.addEventListener('focus', restoreFocusScroll, true);+ }body.addEventListener('focusin', handleFocusIn);- body.addEventListener('focusout', scheduleReveal);+ body.addEventListener('focusout', handleFocusOut);sheet?.addEventListener('transitionend', handleSheetTransitionEnd);viewport?.addEventListener('resize', scheduleReveal);viewport?.addEventListener('scroll', scheduleReveal);@@ -497,15 +532,24 @@ export function useMobileKeyboard({return () => {cancelAnimationFrame(animationFrame);- document.removeEventListener(- 'pointerdown',- rememberPointerFocusScroll,- true,- );- document.removeEventListener('focusout', rememberFocusScroll);- body.removeEventListener('focus', restoreFocusScroll, true);+ if (preventFocusScroll) {+ document.removeEventListener(+ 'pointerdown',+ rememberPointerFocusScroll,+ true,+ );+ document.removeEventListener('pointermove', handlePointerMove, true);+ document.removeEventListener(+ 'pointercancel',+ handlePointerCancel,+ true,+ );+ document.removeEventListener('pointerup', preventTouchFocusScroll);+ document.removeEventListener('focusout', rememberFocusScroll);+ body.removeEventListener('focus', restoreFocusScroll, true);+ }body.removeEventListener('focusin', handleFocusIn);- body.removeEventListener('focusout', scheduleReveal);+ body.removeEventListener('focusout', handleFocusOut);sheet?.removeEventListener('transitionend', handleSheetTransitionEnd);viewport?.removeEventListener('resize', scheduleReveal);viewport?.removeEventListener('scroll', scheduleReveal);@@ -513,19 +557,8 @@ export function useMobileKeyboard({resizeObserver?.disconnect();mutationObserver?.disconnect();body.style.removeProperty(MOBILE_KEYBOARD_INSET_VAR);- positioner.style.removeProperty(MOBILE_KEYBOARD_LIFT_VAR);- if (isSheetHeightFrozen && sheet) {- sheet.style.removeProperty('height');- }hasKeyboardLayoutRef.current = false;retainKeyboardLayoutRef.current = false;};- }, [- bodyRef,- bottomClearance,- isOpen,- positionerRef,- preserveSheetHeight,- sheetRef,- ]);+ }, [bodyRef, bottomClearance, isEnabled, isPresented, sheetRef]);}