Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(lab): support mobile keyboards in BottomSheet (#5043)

Xinzi Zhou9e8a72a9fb74
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsx
index e83fbe17be..adaee1e59e 100644
--- a/apps/storybook/stories/BottomSheet.stories.tsx
+++ b/apps/storybook/stories/BottomSheet.stories.tsx
@@ -41,6 +41,127 @@ const meta: Meta<typeof BottomSheet> = {
export default meta;
type Story = StoryObj<typeof BottomSheet>;
+interface CommentFormValues {
+ title: string;
+ author: string;
+ email: string;
+ team: string;
+ project: string;
+ relatedTask: string;
+ summary: string;
+ context: string;
+ changes: string;
+ followUp: string;
+ comment: string;
+}
+
+function MobileKeyboardCommentForm({onPost}: {onPost: () => void}) {
+ const [values, setValues] = useState<CommentFormValues>({
+ title: '',
+ author: '',
+ email: '',
+ team: '',
+ project: '',
+ relatedTask: '',
+ summary: '',
+ context: '',
+ changes: '',
+ followUp: '',
+ comment: '',
+ });
+ const update =
+ (field: keyof CommentFormValues) =>
+ (value: string): void =>
+ setValues(current => ({...current, [field]: value}));
+
+ return (
+ <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.
+ </Text>
+ <Divider />
+ <TextInput
+ label="Title"
+ value={values.title}
+ onChange={update('title')}
+ />
+ <TextInput
+ label="Author"
+ value={values.author}
+ onChange={update('author')}
+ />
+ <TextInput
+ label="Email"
+ type="email"
+ value={values.email}
+ onChange={update('email')}
+ />
+ <TextInput label="Team" value={values.team} onChange={update('team')} />
+ <TextInput
+ label="Project"
+ value={values.project}
+ onChange={update('project')}
+ />
+ <TextInput
+ label="Related task"
+ value={values.relatedTask}
+ onChange={update('relatedTask')}
+ />
+ <TextArea
+ label="Summary"
+ rows={4}
+ value={values.summary}
+ onChange={update('summary')}
+ />
+ <TextArea
+ label="Context"
+ rows={6}
+ value={values.context}
+ onChange={update('context')}
+ />
+ <TextArea
+ label="What changed?"
+ rows={4}
+ value={values.changes}
+ onChange={update('changes')}
+ />
+ <TextArea
+ label="Suggested follow-up"
+ rows={4}
+ value={values.followUp}
+ onChange={update('followUp')}
+ />
+ <TextArea
+ label="Comment"
+ rows={8}
+ value={values.comment}
+ onChange={update('comment')}
+ />
+ <Button label="Post comment" onClick={onPost} />
+ </VStack>
+ );
+}
+
+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);
@@ -157,22 +278,23 @@ export const HugHeight: Story = {
const [isOpen, setIsOpen] = useState(false);
return (
<>
- <Button label="Add a comment" onClick={() => setIsOpen(true)} />
+ <Button label="Share page" onClick={() => setIsOpen(true)} />
<BottomSheet
isOpen={isOpen}
onOpenChange={setIsOpen}
- label="Add a comment"
+ label="Share page"
height="hug">
<Section padding={4}>
<VStack gap={4}>
- <Heading level={3}>Add a comment</Heading>
+ <Heading level={3}>Share page</Heading>
<Text type="supporting" color="secondary">
The sheet fits its content, up to 92% of the viewport.
</Text>
<Divider />
- <TextInput label="Title" value="" />
- <TextArea label="Comment" rows={4} value="" />
- <Button label="Post" onClick={() => setIsOpen(false)} />
+ <Button label="Copy link" />
+ <Button label="Send in Messenger" />
+ <Button label="Save for later" />
+ <Button label="Done" onClick={() => setIsOpen(false)} />
</VStack>
</Section>
</BottomSheet>
@@ -180,3 +302,45 @@ export const HugHeight: 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',
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <Button label="Add a comment" onClick={() => setIsOpen(true)} />
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ label="Add a comment"
+ height="tall">
+ <Section padding={4}>
+ <MobileKeyboardCommentForm onPost={() => setIsOpen(false)} />
+ </Section>
+ </BottomSheet>
+ </>
+ );
+ },
+};
diff --git a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs b/packages/lab/src/BottomSheet/BottomSheet.doc.mjs
index e4c96fcb1e..7b3dd99f73 100644
--- a/packages/lab/src/BottomSheet/BottomSheet.doc.mjs
+++ b/packages/lab/src/BottomSheet/BottomSheet.doc.mjs
@@ -18,6 +18,9 @@ export const docs = {
'dialog',
'overlay',
'modal',
+ 'form',
+ 'mobile keyboard',
+ 'visual viewport',
],
theming: {
targets: [{className: 'astryx-bottom-sheet', visualProps: []}],
@@ -50,7 +53,7 @@ export const docs = {
name: 'children',
type: 'ReactNode',
description:
- 'Sheet content, rendered below the grab handle in a scrollable area.',
+ 'Sheet content, rendered below the grab handle in a scrollable, mobile-keyboard-aware area.',
required: true,
},
{
@@ -70,7 +73,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. 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. 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).',
bestPractices: [
{
guidance: true,
@@ -87,6 +90,11 @@ export const docs = {
description:
"Pick the starting height that fits the content: 'hug' for short bounded content, 'capped' for lists, 'tall' for streaming/resizing content; the user can then drag between snap points.",
},
+ {
+ 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.",
+ },
{
guidance: true,
description:
@@ -130,6 +138,28 @@ export const docs = {
label="Share"
height="hug">
<ShareActions />
+</BottomSheet>`,
+ },
+ {
+ label: 'Mobile keyboard (a long form)',
+ code: `const [isOpen, setIsOpen] = useState(false);
+<BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ 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>`,
},
{
@@ -149,10 +179,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, 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, visual-viewport mobile-keyboard handling, named height scale, modal (default) or non-modal (hasScrim={false}) presentation',
usage: {
description:
- 'Mobile surface for filters, actions, 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. 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. 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.',
bestPractices: [
{
guidance: true,
@@ -168,6 +198,11 @@ export const docsDense = {
description:
"Pick a height that fits: 'hug' for short content, 'capped' for lists, 'tall' for streaming content.",
},
+ {
+ guidance: true,
+ description:
+ "Use 'tall' for long forms. 'hug' supports short forms by lifting temporarily when the keyboard leaves too little usable space.",
+ },
{
guidance: true,
description:
diff --git a/packages/lab/src/BottomSheet/BottomSheet.test.tsx b/packages/lab/src/BottomSheet/BottomSheet.test.tsx
index 5f808107d4..9082a73604 100644
--- a/packages/lab/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/lab/src/BottomSheet/BottomSheet.test.tsx
@@ -45,6 +45,14 @@ beforeEach(() => {
dispatchEvent: vi.fn(),
}),
);
+ vi.stubGlobal(
+ 'requestAnimationFrame',
+ vi.fn((callback: FrameRequestCallback) => {
+ callback(0);
+ return 1;
+ }),
+ );
+ vi.stubGlobal('cancelAnimationFrame', vi.fn());
});
afterEach(() => {
@@ -59,6 +67,77 @@ function getSheet(): HTMLElement {
return sheet;
}
+function getBody(): HTMLElement {
+ const body = getSheet().lastElementChild;
+ if (!(body instanceof HTMLElement)) {
+ throw new Error('sheet scroll body not found');
+ }
+ return body;
+}
+
+function getPositioner(): HTMLElement {
+ const positioner = getSheet().parentElement;
+ if (!(positioner instanceof HTMLElement)) {
+ throw new Error('sheet positioner not found');
+ }
+ return positioner;
+}
+
+function rect({top, bottom}: {top: number; bottom: number}): DOMRect {
+ return {
+ x: 0,
+ y: top,
+ top,
+ right: 400,
+ bottom,
+ left: 0,
+ width: 400,
+ height: bottom - top,
+ toJSON: () => ({}),
+ };
+}
+
+function mockVisualViewport(height: number, offsetTop = 0) {
+ const viewport = Object.assign(new EventTarget(), {
+ height,
+ offsetTop,
+ });
+ vi.stubGlobal('visualViewport', viewport);
+ return viewport;
+}
+
+interface ResizeObserverRecord {
+ callback: ResizeObserverCallback;
+ observed: Set<Element>;
+}
+
+function mockResizeObserverInstances(): ResizeObserverRecord[] {
+ const observers: ResizeObserverRecord[] = [];
+ class ResizeObserverMock {
+ callback: ResizeObserverCallback;
+ observed = new Set<Element>();
+
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback;
+ observers.push(this);
+ }
+
+ observe(target: Element) {
+ this.observed.add(target);
+ }
+
+ unobserve(target: Element) {
+ this.observed.delete(target);
+ }
+
+ disconnect() {
+ this.observed.clear();
+ }
+ }
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock);
+ return observers;
+}
+
function finishSheetExit() {
fireEvent.transitionEnd(getSheet(), {propertyName: 'transform'});
}
@@ -112,6 +191,20 @@ describe('BottomSheet', () => {
expect(screen.getByText('Sheet content')).toBeInTheDocument();
});
+ it('keeps consumer content as the last scroll-body child', () => {
+ render(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Filters">
+ <div data-testid="consumer-content">Sheet content</div>
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const consumer = screen.getByTestId('consumer-content');
+
+ expect(body.children).toHaveLength(1);
+ expect(body.lastElementChild).toBe(consumer);
+ expect(consumer.matches(':last-child')).toBe(true);
+ });
+
it('does not show when isOpen is false', () => {
render(
<BottomSheet isOpen={false} onOpenChange={() => {}} label="Filters">
@@ -354,6 +447,446 @@ describe('BottomSheet', () => {
});
});
+ describe('mobile keyboard', () => {
+ it('restores pointer-driven focus scrolling without re-focusing', () => {
+ const onFocus = vi.fn();
+ render(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">
+ <input aria-label="Comment" onFocus={onFocus} />
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const input = screen.getByRole('textbox', {name: 'Comment'});
+ const focus = vi.spyOn(input, 'focus');
+ body.scrollTop = 20;
+
+ fireEvent.pointerDown(input, {pointerId: 1, clientY: 200});
+ expect(focus).not.toHaveBeenCalled();
+
+ // Emulate the browser panning before it dispatches the focus event.
+ body.scrollTop = 120;
+ fireEvent.focus(input, {relatedTarget: null});
+
+ expect(body.scrollTop).toBe(20);
+ expect(focus).not.toHaveBeenCalled();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ });
+
+ it('restores pointer focus scrolling when a control stops propagation', () => {
+ render(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">
+ <input
+ aria-label="Comment"
+ onPointerDown={event => event.stopPropagation()}
+ />
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const input = screen.getByRole('textbox', {name: 'Comment'});
+ body.scrollTop = 20;
+
+ fireEvent.pointerDown(input, {pointerId: 1, clientY: 200});
+ body.scrollTop = 120;
+ fireEvent.focus(input, {relatedTarget: null});
+
+ expect(body.scrollTop).toBe(20);
+ });
+
+ it('restores native focus scrolling without duplicating focus events', () => {
+ const onTitleBlur = vi.fn();
+ const onCommentFocus = vi.fn();
+ render(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">
+ <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},
+ );
+
+ 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', () => {
+ const viewport = mockVisualViewport(500);
+ render(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">
+ <input aria-label="Comment" />
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const input = screen.getByRole('textbox', {name: 'Comment'});
+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(
+ rect({top: 100, bottom: 800}),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>
+ rect({
+ top: 660 - body.scrollTop,
+ bottom: 700 - body.scrollTop,
+ }),
+ );
+
+ act(() => viewport.dispatchEvent(new Event('resize')));
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '0px',
+ );
+
+ input.focus();
+
+ // 300px keyboard overlap + 48px room for Android suggestion UI.
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '348px',
+ );
+ // Visible bottom is 500px; preserve the same 48px focus gap.
+ expect(body.scrollTop).toBe(248);
+
+ viewport.height = 800;
+ act(() => viewport.dispatchEvent(new Event('resize')));
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '0px',
+ );
+ });
+
+ it('does not add clearance or scroll when the viewport is unobstructed', () => {
+ mockVisualViewport(800);
+ render(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">
+ <input aria-label="Comment" />
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const input = screen.getByRole('textbox', {name: 'Comment'});
+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(
+ rect({top: 100, bottom: 800}),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(
+ rect({top: 760, bottom: 790}),
+ );
+
+ input.focus();
+
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '0px',
+ );
+ expect(body.scrollTop).toBe(0);
+ });
+
+ it('keeps a hug sheet at its intrinsic height while adding keyboard scroll range', () => {
+ const viewport = mockVisualViewport(500);
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Add a comment"
+ height="hug">
+ <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,
+ }),
+ );
+
+ input.focus();
+
+ 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',
+ );
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '310px',
+ );
+ expect(body.scrollTop).toBe(250);
+
+ viewport.height = 800;
+ act(() => viewport.dispatchEvent(new Event('resize')));
+ expect(sheet.style.height).toBe('');
+ expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(
+ '0px',
+ );
+ });
+
+ it('re-reveals a focused control when content layout changes', () => {
+ const observers = mockResizeObserverInstances();
+ mockVisualViewport(500);
+ render(
+ <BottomSheet isOpen onOpenChange={() => {}} label="Add a comment">
+ <input aria-label="Comment" />
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const input = screen.getByRole('textbox', {name: 'Comment'});
+ let layoutShift = 0;
+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(
+ rect({top: 100, bottom: 800}),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>
+ rect({
+ top: 660 + layoutShift - body.scrollTop,
+ bottom: 700 + layoutShift - body.scrollTop,
+ }),
+ );
+
+ input.focus();
+ expect(body.scrollTop).toBe(248);
+
+ layoutShift = 200;
+ const observer = observers.find(instance => instance.observed.has(input));
+ expect(observer).toBeDefined();
+ act(() => {
+ observer?.callback([], observer as unknown as ResizeObserver);
+ });
+
+ expect(body.scrollTop).toBe(448);
+ });
+
+ it('re-reveals a focused control when the sheet height changes', () => {
+ const observers = mockResizeObserverInstances();
+ mockVisualViewport(500);
+ render(
+ <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'});
+ 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(body, 'getBoundingClientRect').mockImplementation(() =>
+ rect({
+ top: (isShort ? 450 : 100) - currentLift(),
+ bottom: 800 - currentLift(),
+ }),
+ );
+ 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);
+
+ 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);
+ });
+
+ expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(
+ '38px',
+ );
+ expect(body.scrollTop).toBe(560);
+ expect(input.getBoundingClientRect().bottom).toBe(452);
+ });
+
+ it('retains keyboard layout during travel until the viewport recovers', () => {
+ const viewport = mockVisualViewport(500);
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Add a comment"
+ height="hug">
+ <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,
+ }),
+ );
+
+ input.focus();
+ expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(
+ '38px',
+ );
+ expect(body.scrollTop).toBe(250);
+
+ fireEvent.pointerDown(getHandle(), {pointerId: 1, clientY: 0});
+ 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(
+ '310px',
+ );
+ 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(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Add a comment"
+ height="hug">
+ <input aria-label="Comment" />
+ </BottomSheet>,
+ );
+ const sheet = getSheet();
+ const positioner = getPositioner();
+ 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(input, 'getBoundingClientRect').mockImplementation(() =>
+ rect({
+ top: 700 + entranceOffset - currentLift() - body.scrollTop,
+ bottom: 740 + entranceOffset - currentLift() - body.scrollTop,
+ }),
+ );
+
+ input.focus();
+ expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(
+ '138px',
+ );
+
+ entranceOffset = 0;
+ fireEvent.transitionEnd(sheet, {propertyName: 'transform'});
+
+ expect(positioner.style.getPropertyValue('--_sheet-keyboard-lift')).toBe(
+ '38px',
+ );
+ 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>,
+ );
+ 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>
+ );
+ const {rerender} = render(content(true));
+ const input = screen.getByRole('textbox', {name: 'Comment'});
+ input.focus();
+
+ rerender(content(false));
+
+ expect(document.activeElement).not.toBe(input);
+ });
+ });
+
describe('focus restore', () => {
function Harness() {
const [isOpen, setIsOpen] = useState(false);
diff --git a/packages/lab/src/BottomSheet/BottomSheet.tsx b/packages/lab/src/BottomSheet/BottomSheet.tsx
index 0c99f1ab28..ded849e47a 100644
--- a/packages/lab/src/BottomSheet/BottomSheet.tsx
+++ b/packages/lab/src/BottomSheet/BottomSheet.tsx
@@ -4,7 +4,7 @@
/**
* @file BottomSheet.tsx
- * @input Uses React, StyleX, theme tokens, core hooks (useScrollLock), utils, useSheetGestures
+ * @input Uses React, StyleX, theme tokens, core hooks (useScrollLock), utils, useMobileKeyboard, useSheetGestures
* @output Exports BottomSheet component and BottomSheetProps
* @position Lab implementation; consumed by index.ts, tested by BottomSheet.test.tsx, demonstrated in Storybook
*
@@ -17,6 +17,12 @@
* That shell is what lets the sheet translate freely (including a little past
* fully-open) without clipping against a fixed dialog edge.
*
+ * Form controls stay usable above mobile on-screen keyboards: the outer sheet
+ * keeps its measured height while visual-viewport overlap extends the internal
+ * scroll range and focused controls scroll into view. Short sheets lift only
+ * far enough to expose a usable focus area. Starting sheet travel or closing
+ * the sheet blurs the field to dismiss the keyboard.
+ *
* `hasScrim` picks the presentation: `true` (default) uses `showModal()` (top
* layer, focus trap, scrim, scroll lock, background inert); `false` uses
* `show()` for a non-modal sheet with no scrim, leaving the page behind
@@ -35,7 +41,14 @@
* - /apps/storybook/stories/BottomSheet.stories.tsx (examples and visual coverage)
*/
-import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
import {
@@ -49,6 +62,7 @@ import {
} from '@astryxdesign/core/theme/tokens.stylex';
import {useDevWarning, useScrollLock} from '@astryxdesign/core/hooks';
import {mergeProps, mergeRefs, themeProps} from '@astryxdesign/core/utils';
+import {useMobileKeyboard} from './useMobileKeyboard';
import {useSheetGestures} from './useSheetGestures';
// A non-modal sheet (hasScrim={false}) uses show() instead of showModal(), so
@@ -84,6 +98,11 @@ export type BottomSheetHeight = keyof typeof HEIGHT_BUDGETS;
// SYNC: must match OVERSCROLL_MAX in useSheetGestures.ts (the drag cap).
const OVERSCROLL_PADDING = 48;
+// Chrome Android needs trailing room after the final input when its suggestion
+// UI appears. This single value controls both the CSS scroll padding and the
+// hook's viewport calculations.
+const MOBILE_KEYBOARD_BOTTOM_CLEARANCE = 48;
+
/**
* Default snap detents in px, resolved against the *visual* viewport (like iOS
* detents), so a mid rest point is ~half the screen regardless of the sheet's
@@ -174,6 +193,10 @@ const styles = stylex.create({
display: 'flex',
justifyContent: 'center',
pointerEvents: 'none',
+ // SYNC: custom property is set by useMobileKeyboard.ts. Applying the
+ // keyboard-only lift outside the measured sheet keeps hug height and drag
+ // detents stable.
+ transform: 'translateY(calc(0px - var(--_sheet-keyboard-lift, 0px)))',
},
sheet: {
pointerEvents: 'auto',
@@ -237,6 +260,10 @@ const styles = stylex.create({
flexGrow: 1,
minHeight: 0,
overflowY: 'auto',
+ // Set from visualViewport while the on-screen keyboard/browser chrome
+ // covers the stable sheet. The generated tail below extends the internal
+ // scroll range; the outer sheet and this flex item's box stay unchanged.
+ scrollPaddingBlockEnd: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,
// No overscroll bounce inside the sheet — a pull-down at the top edge is
// handed off to the sheet drag (see useSheetGestures' touch handling)
// rather than rubber-banding the content.
@@ -245,6 +272,16 @@ const styles = stylex.create({
// intercepted via a non-passive touchmove listener, not by blocking
// touch-action (which would suppress scrolling entirely).
touchAction: 'pan-y',
+ // Extend the scroll range without inserting an element after public
+ // children. Direct children must retain their :last-child semantics for
+ // Astryx container edge compensation and consumer-authored selectors.
+ '::after': {
+ content: '""',
+ display: 'block',
+ // SYNC: custom property is set by useMobileKeyboard.ts.
+ blockSize: 'var(--_sheet-keyboard-inset, 0px)',
+ pointerEvents: 'none',
+ },
},
// Both budgets add the overdrag padding back to the height so the visible
// height (minus the off-screen padding) matches the intended budget.
@@ -277,7 +314,10 @@ export interface BottomSheetProps extends BaseProps<HTMLDialogElement> {
*/
label: string;
- /** Sheet content, rendered below the grab handle in a scrollable area. */
+ /**
+ * Sheet content, rendered below the grab handle in a scrollable,
+ * mobile-keyboard-aware area.
+ */
children: ReactNode;
/**
@@ -326,6 +366,10 @@ export interface BottomSheetProps extends BaseProps<HTMLDialogElement> {
* With `hasScrim={false}` it opens non-modally (`show()`, no scrim), leaving
* the page behind interactive and scrollable.
*
+ * Focused form controls scroll above the mobile on-screen keyboard without
+ * resizing the sheet. A short sheet temporarily lifts when it has no usable
+ * area above the keyboard. Moving the sheet dismisses the keyboard.
+ *
* @example
* ```
* const [isOpen, setIsOpen] = useState(false);
@@ -352,7 +396,9 @@ export function BottomSheet({
const isExiting = !isOpen && isPresented;
const dialogRef = useRef<HTMLDialogElement | null>(null);
const triggerRef = useRef<HTMLElement | null>(null);
+ const positionerNodeRef = useRef<HTMLDivElement | null>(null);
const sheetNodeRef = useRef<HTMLDivElement | null>(null);
+ const bodyNodeRef = useRef<HTMLDivElement | null>(null);
const close = useCallback(() => onOpenChange(false), [onOpenChange]);
// Set imperatively (not via state) so a 60fps drag doesn't re-render. The
@@ -364,12 +410,34 @@ export function BottomSheet({
);
}, []);
- const {contentProps, handleProps, bodyProps, sheetRef} = useSheetGestures({
+ const {
+ contentProps,
+ handleProps,
+ bodyProps,
+ sheetRef,
+ dragOffset,
+ settledOffset,
+ isDragging,
+ } = useSheetGestures({
isOpen,
onDismiss: close,
snapHeights: defaultSnapHeights,
onScrimOpacity: handleScrimOpacity,
});
+ const isSheetTraveling = isDragging && dragOffset !== settledOffset;
+ const mergedBodyRef = useMemo(
+ () => mergeRefs(bodyProps.ref, bodyNodeRef),
+ [bodyProps.ref],
+ );
+ useMobileKeyboard({
+ bodyRef: bodyNodeRef,
+ bottomClearance: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,
+ isSheetTraveling,
+ isOpen,
+ positionerRef: positionerNodeRef,
+ preserveSheetHeight: height === 'hug',
+ sheetRef: sheetNodeRef,
+ });
// Modal: showModal() enters the top layer with a focus trap + ::backdrop and
// we restore focus to the opener on close. Standard: show() is non-modal, so
@@ -396,9 +464,9 @@ export function BottomSheet({
// otherwise only honor a descendant data-autofocus.
const autofocus = dialog.querySelector<HTMLElement>('[data-autofocus]');
if (autofocus) {
- autofocus.focus();
+ autofocus.focus({preventScroll: true});
} else if (hasScrim) {
- sheetNodeRef.current?.focus();
+ sheetNodeRef.current?.focus({preventScroll: true});
}
}
} else if (dialog.open) {
@@ -511,7 +579,7 @@ export function BottomSheet({
onClick={handleClick}
onKeyDown={handleKeyDown}
{...props}>
- <div {...stylex.props(styles.positioner)}>
+ <div ref={positionerNodeRef} {...stylex.props(styles.positioner)}>
<div
ref={mergeRefs(sheetRef, sheetNodeRef)}
tabIndex={-1}
@@ -536,7 +604,10 @@ export function BottomSheet({
aria-hidden="true">
<div {...stylex.props(styles.handlePill)} />
</div>
- <div {...stylex.props(styles.body)} {...bodyProps}>
+ <div
+ {...stylex.props(styles.body)}
+ {...bodyProps}
+ ref={mergedBodyRef}>
{children}
</div>
</div>
diff --git a/packages/lab/src/BottomSheet/useMobileKeyboard.ts b/packages/lab/src/BottomSheet/useMobileKeyboard.ts
new file mode 100644
index 0000000000..0774d838d8
--- /dev/null
+++ b/packages/lab/src/BottomSheet/useMobileKeyboard.ts
@@ -0,0 +1,531 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useMobileKeyboard.ts
+ * @input Uses React effects and refs supplied by BottomSheet
+ * @output Exports internal useMobileKeyboard hook
+ * @position Internal to BottomSheet; not exported from the 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.
+ */
+
+import {useEffect, useRef, type RefObject} from 'react';
+
+const MOBILE_KEYBOARD_INSET_VAR = '--_sheet-keyboard-inset';
+const MOBILE_KEYBOARD_LIFT_VAR = '--_sheet-keyboard-lift';
+const NON_TEXT_INPUT_TYPES = new Set([
+ 'button',
+ 'checkbox',
+ 'color',
+ 'file',
+ 'hidden',
+ 'image',
+ 'radio',
+ 'range',
+ 'reset',
+ 'submit',
+]);
+
+interface UseMobileKeyboardOptions {
+ bodyRef: RefObject<HTMLDivElement | null>;
+ bottomClearance: number;
+ isSheetTraveling: boolean;
+ isOpen: boolean;
+ positionerRef: RefObject<HTMLDivElement | null>;
+ preserveSheetHeight: boolean;
+ sheetRef: RefObject<HTMLDivElement | null>;
+}
+
+interface FocusScrollSnapshot {
+ target: HTMLElement;
+ elements: Array<{
+ element: HTMLElement;
+ scrollLeft: number;
+ scrollTop: number;
+ }>;
+ windowX: number;
+ windowY: number;
+}
+
+interface KeyboardGeometry {
+ bodyBottom: number;
+ bodyTop: number;
+ focusedHeight: number;
+ sheetTop: number | null;
+}
+
+function captureFocusScroll(target: HTMLElement): FocusScrollSnapshot {
+ const elements: FocusScrollSnapshot['elements'] = [];
+ for (
+ let element = target.parentElement;
+ element;
+ element = element.parentElement
+ ) {
+ elements.push({
+ element,
+ scrollLeft: element.scrollLeft,
+ scrollTop: element.scrollTop,
+ });
+ }
+ return {
+ target,
+ elements,
+ windowX: window.scrollX,
+ windowY: window.scrollY,
+ };
+}
+
+function getVisualViewportBounds(): {top: number; bottom: number} {
+ const viewport = window.visualViewport;
+ const top = viewport?.offsetTop ?? 0;
+ return {
+ top,
+ bottom: top + (viewport?.height ?? window.innerHeight),
+ };
+}
+
+function isTextEntryControl(element: Element | null): element is HTMLElement {
+ if (element instanceof HTMLTextAreaElement) {
+ return !element.disabled && !element.readOnly;
+ }
+ if (element instanceof HTMLInputElement) {
+ return (
+ !element.disabled &&
+ !element.readOnly &&
+ !NON_TEXT_INPUT_TYPES.has(element.type)
+ );
+ }
+ return (
+ element instanceof HTMLElement &&
+ element.matches('[contenteditable]:not([contenteditable="false"])')
+ );
+}
+
+function findTextEntryControl(
+ target: EventTarget | null,
+ body: HTMLElement,
+): HTMLElement | null {
+ if (!(target instanceof Element)) {
+ return null;
+ }
+
+ const direct = target.closest(
+ 'input, textarea, [contenteditable]:not([contenteditable="false"])',
+ );
+ if (body.contains(direct) && isTextEntryControl(direct)) {
+ return direct;
+ }
+
+ const label = target.closest('label');
+ const control = label instanceof HTMLLabelElement ? label.control : null;
+ return body.contains(control) && isTextEntryControl(control) ? control : null;
+}
+
+export function useMobileKeyboard({
+ bodyRef,
+ bottomClearance,
+ isSheetTraveling,
+ isOpen,
+ positionerRef,
+ preserveSheetHeight,
+ sheetRef,
+}: UseMobileKeyboardOptions): void {
+ const hasKeyboardLayoutRef = useRef(false);
+ const retainKeyboardLayoutRef = useRef(false);
+
+ useEffect(() => {
+ if (!isSheetTraveling) {
+ return;
+ }
+ const sheet = sheetRef.current;
+ const activeElement = document.activeElement;
+ if (
+ sheet &&
+ activeElement instanceof HTMLElement &&
+ activeElement !== sheet &&
+ sheet.contains(activeElement)
+ ) {
+ // Keep the current keyboard lift/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.
+ retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;
+ sheet.focus({preventScroll: true});
+ }
+ }, [isSheetTraveling, sheetRef]);
+
+ useEffect(() => {
+ if (isOpen) {
+ return;
+ }
+ const sheet = sheetRef.current;
+ const activeElement = document.activeElement;
+ if (
+ sheet &&
+ activeElement instanceof HTMLElement &&
+ activeElement !== sheet &&
+ sheet.contains(activeElement)
+ ) {
+ activeElement.blur();
+ }
+ }, [isOpen, sheetRef]);
+
+ useEffect(() => {
+ const body = bodyRef.current;
+ const positioner = positionerRef.current;
+ const sheet = sheetRef.current;
+ if (!isOpen || !body || !positioner) {
+ 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`);
+ };
+
+ 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 applyKeyboardGeometry = (geometry: KeyboardGeometry) => {
+ const viewport = getVisualViewportBounds();
+ // A collapsed detent can extend the body below the layout viewport even
+ // after the keyboard closes, so body overlap alone cannot identify
+ // recovery. Once the visual viewport reaches the layout viewport bottom,
+ // release the retained keyboard layout unconditionally.
+ if (viewport.bottom >= window.innerHeight - 0.5) {
+ clearKeyboardLayout();
+ return;
+ }
+ const overlap = Math.max(0, geometry.bodyBottom - viewport.bottom);
+ if (overlap === 0) {
+ clearKeyboardLayout();
+ 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),
+ );
+ 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.
+ const rememberPointerFocusScroll = (event: PointerEvent) => {
+ const control = findTextEntryControl(event.target, body);
+ pendingPointerFocusScroll =
+ control && control !== document.activeElement
+ ? captureFocusScroll(control)
+ : null;
+ };
+
+ // 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.
+ const rememberFocusScroll = (event: FocusEvent) => {
+ const control = findTextEntryControl(event.relatedTarget, body);
+ if (!control) {
+ pendingFocusScroll = null;
+ return;
+ }
+
+ pendingFocusScroll = captureFocusScroll(control);
+ };
+ const restoreFocusScroll = (event: FocusEvent) => {
+ const control = findTextEntryControl(event.target, body);
+ const snapshot =
+ pendingFocusScroll?.target === control
+ ? pendingFocusScroll
+ : pendingPointerFocusScroll?.target === control
+ ? pendingPointerFocusScroll
+ : 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);
+ }
+ };
+
+ const revealFocusedControl = () => {
+ const activeElement = document.activeElement;
+ if (
+ !(activeElement instanceof HTMLElement) ||
+ !body.contains(activeElement) ||
+ !isTextEntryControl(activeElement)
+ ) {
+ if (retainKeyboardLayoutRef.current && keyboardGeometry) {
+ applyKeyboardGeometry(keyboardGeometry);
+ return;
+ }
+ clearKeyboardLayout();
+ return;
+ }
+
+ retainKeyboardLayoutRef.current = false;
+
+ 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);
+ // 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,
+ }
+ : 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))
+ : 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);
+ if (safeBottom <= safeTop) {
+ return;
+ }
+
+ if (focusedBottom > safeBottom) {
+ body.scrollTop += focusedBottom - safeBottom;
+ } else if (focusedTop < safeTop) {
+ body.scrollTop -= safeTop - focusedTop;
+ }
+ };
+
+ let animationFrame = 0;
+ const scheduleReveal = () => {
+ cancelAnimationFrame(animationFrame);
+ animationFrame = requestAnimationFrame(revealFocusedControl);
+ };
+
+ const resizeObserver =
+ typeof ResizeObserver === 'undefined'
+ ? null
+ : new ResizeObserver(scheduleReveal);
+ const refreshObservedLayout = () => {
+ if (!resizeObserver) {
+ return;
+ }
+ resizeObserver.disconnect();
+
+ // Body/sheet box changes include public height and xstyle updates. The
+ // generated inset pseudo-element changes only scroll overflow, so these
+ // observations do not feed the keyboard inset back into sheet geometry.
+ const targets = new Set<Element>([body]);
+ if (sheet) {
+ targets.add(sheet);
+ }
+ for (const child of body.children) {
+ targets.add(child);
+ }
+ const activeElement = document.activeElement;
+ if (
+ activeElement instanceof HTMLElement &&
+ body.contains(activeElement)
+ ) {
+ for (
+ let element: HTMLElement | null = activeElement;
+ element && element !== body;
+ element = element.parentElement
+ ) {
+ targets.add(element);
+ }
+ }
+ for (const target of targets) {
+ resizeObserver.observe(target);
+ }
+ };
+ const mutationObserver =
+ typeof MutationObserver === 'undefined'
+ ? null
+ : new MutationObserver(records => {
+ // Ignore the internal inset written on the body. Consumer DOM,
+ // text, class, style, or visibility changes can all move the
+ // focused control without a viewport event.
+ if (
+ records.every(
+ record =>
+ record.type === 'attributes' && record.target === body,
+ )
+ ) {
+ return;
+ }
+ refreshObservedLayout();
+ scheduleReveal();
+ });
+ const handleFocusIn = () => {
+ refreshObservedLayout();
+ scheduleReveal();
+ };
+ const handleSheetTransitionEnd = (event: TransitionEvent) => {
+ if (event.target === sheet && event.propertyName === 'transform') {
+ scheduleReveal();
+ }
+ };
+
+ 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);
+ body.addEventListener('focusin', handleFocusIn);
+ body.addEventListener('focusout', scheduleReveal);
+ sheet?.addEventListener('transitionend', handleSheetTransitionEnd);
+ viewport?.addEventListener('resize', scheduleReveal);
+ viewport?.addEventListener('scroll', scheduleReveal);
+ window.addEventListener('resize', scheduleReveal);
+ mutationObserver?.observe(body, {
+ attributes: true,
+ characterData: true,
+ childList: true,
+ subtree: true,
+ });
+ refreshObservedLayout();
+ // The dialog enters the top layer in a later effect. Wait until the next
+ // frame so flex geometry is final before measuring the body.
+ scheduleReveal();
+
+ return () => {
+ cancelAnimationFrame(animationFrame);
+ document.removeEventListener(
+ 'pointerdown',
+ rememberPointerFocusScroll,
+ true,
+ );
+ document.removeEventListener('focusout', rememberFocusScroll);
+ body.removeEventListener('focus', restoreFocusScroll, true);
+ body.removeEventListener('focusin', handleFocusIn);
+ body.removeEventListener('focusout', scheduleReveal);
+ sheet?.removeEventListener('transitionend', handleSheetTransitionEnd);
+ viewport?.removeEventListener('resize', scheduleReveal);
+ viewport?.removeEventListener('scroll', scheduleReveal);
+ window.removeEventListener('resize', scheduleReveal);
+ 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,
+ ]);
+}
diff --git a/packages/lab/src/BottomSheet/useSheetGestures.test.ts b/packages/lab/src/BottomSheet/useSheetGestures.test.ts
index c25787ddce..e77ab6e950 100644
--- a/packages/lab/src/BottomSheet/useSheetGestures.test.ts
+++ b/packages/lab/src/BottomSheet/useSheetGestures.test.ts
@@ -19,7 +19,8 @@ import {
const SHEET_HEIGHT = 400;
// A fake pointer event object good enough for the handlers, which only read
-// pointerId, clientY, timeStamp, and currentTarget's capture + measure APIs.
+// pointerId, clientY, timeStamp, preventDefault, and currentTarget's capture +
+// measure APIs.
function pointerEvent(
clientY: number,
timeStamp: number,
@@ -31,6 +32,7 @@ function pointerEvent(
clientY,
timeStamp,
currentTarget: target,
+ preventDefault: vi.fn(),
} as unknown as React.PointerEvent;
}
diff --git a/packages/lab/src/BottomSheet/useSheetGestures.ts b/packages/lab/src/BottomSheet/useSheetGestures.ts
index 365c3c95e4..67c1cfc9c8 100644
--- a/packages/lab/src/BottomSheet/useSheetGestures.ts
+++ b/packages/lab/src/BottomSheet/useSheetGestures.ts
@@ -361,6 +361,10 @@ export function useSheetGestures({
const handlePointerDown = useCallback(
(event: ReactPointerEvent) => {
+ // The handle has no native focus action. Prevent pointer-down from
+ // moving focus off a form control on a tap; once the pointer actually
+ // moves, BottomSheet dismisses the keyboard as sheet travel begins.
+ event.preventDefault();
beginDrag(event, measureHeight());
},
[beginDrag, measureHeight],