An open source design system that's fully customizable and agent ready
TypeScript
fix(core): keep the page still when the mobile keyboard reveals a Bottom Sheet field (#5158)
Xinzi Zhou00bed297569f
diff --git a/.changeset/bottomsheet-keeps-the-page-still-when-the-mobile-xlk2.md b/.changeset/bottomsheet-keeps-the-page-still-when-the-mobile-xlk2.mdnew file mode 100644index 0000000000..d914e3bb00--- /dev/null+++ b/.changeset/bottomsheet-keeps-the-page-still-when-the-mobile-xlk2.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet keeps the page still when the mobile keyboard reveals a field the browser focused itself (#5158)+@imdreamrunnerdiff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjsindex 3ee85e797f..4a2ecd5233 100644--- a/packages/core/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/core/src/BottomSheet/BottomSheet.doc.mjs@@ -99,7 +99,7 @@ export const docs = {name: 'height',type: "'hug' | 'capped' | 'tall' | number | string",description:- "How tall the sheet is. Named budgets: 'hug' fits its content up to 92% of the viewport, 'capped' is a scrolling mid-height panel (~62%), and 'tall' is a pinned near-full panel (~92%) for content that streams in. Or pass a number (px) / CSS length for a custom budget. 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.",+ "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: it stays put and scrolls each focused control above the keyboard. Hug, Capped, numeric and CSS-length heights never do, and a Tall sheet stops doing it the moment the user drags it to a shorter detent — resuming when they drag it back. Outside that state the sheet neither moves nor adds keyboard scroll space, and the browser's own focus reveal is left in place; on iOS that reveal can shift the whole page.",default: "'capped'",},{diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsxindex 435ba34c07..5a3c358b54 100644--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx@@ -219,22 +219,6 @@ function drag(handle: HTMLElement, points: {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',@@ -1056,176 +1040,104 @@ describe('BottomSheet', () => {});describe('mobile keyboard', () => {- it('prevents native touch focus panning without moving focus early or duplicating events', () => {+ it('claims a transition between fields and delivers it with preventScroll', () => {mockIOSWebKit();- const onFocus = vi.fn();- const onBlur = vi.fn();render(<BottomSheetisOpenonOpenChange={() => {}}label="Add a comment"height="tall">- <input- aria-label="Comment"- onPointerDown={event => event.stopPropagation()}- onFocus={onFocus}- onBlur={onBlur}- />+ <input aria-label="Title" />+ <input aria-label="Comment" /></BottomSheet>,);- const sheet = getSheet();- const input = screen.getByRole('textbox', {name: 'Comment'});- const focus = vi.spyOn(input, 'focus');- sheet.focus();+ const title = screen.getByRole('textbox', {name: 'Title'});+ const comment = screen.getByRole('textbox', {name: 'Comment'});+ title.focus();+ const focus = vi.spyOn(comment, 'focus');- // 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);+ // The keyboard's Next, Tab, and a programmatic focus() all arrive as this+ // one transition, named by relatedTarget on the outgoing blur.+ fireEvent.blur(title, {relatedTarget: comment});- // 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);+ // Delivered by us, with the browser's reveal refused.expect(focus).toHaveBeenCalledWith({preventScroll: true});- expect(document.activeElement).toBe(input);- expect(onFocus).toHaveBeenCalledTimes(1);- expect(onBlur).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('does not focus when a touch becomes a scroll gesture', () => {+ it('does not park focus on a sheet that is closing', () => {mockIOSWebKit();- const onPreviousBlur = vi.fn();- render(+ const content = (isOpen: boolean) => (<BottomSheet- isOpen+ isOpen={isOpen}onOpenChange={() => {}}label="Add a comment"height="tall">- <button type="button" onBlur={onPreviousBlur}>- Previous action- </button><input aria-label="Comment" />- </BottomSheet>,+ </BottomSheet>);- const body = getBody();- const previous = screen.getByRole('button', {name: 'Previous action'});+ const {rerender} = render(content(true));+ const sheet = getSheet();const input = screen.getByRole('textbox', {name: 'Comment'});- const focus = vi.spyOn(input, 'focus');- body.scrollTop = 20;- previous.focus();+ input.focus();+ const sheetFocus = vi.spyOn(sheet, 'focus');- fireTouchPointer(input, 'pointerdown', {x: 20, y: 200});- fireTouchPointer(input, 'pointermove', {x: 20, y: 240});- fireTouchPointer(input, 'pointerup', {x: 20, y: 240});+ // Closing blurs the field as well, and that blur names no destination —+ // the same shape as Done. There is no next tap to keep claimable here,+ // and the host is about to hand focus back to whatever opened the sheet.+ void act(() => rerender(content(false)));- expect(focus).not.toHaveBeenCalled();- expect(document.activeElement).toBe(previous);- expect(onPreviousBlur).not.toHaveBeenCalled();+ expect(sheetFocus).not.toHaveBeenCalled();});- it('does not focus when pointer activation is canceled', () => {+ it('autofocuses a field without letting the browser reveal it', () => {mockIOSWebKit();- const onFocus = vi.fn();- const onPreviousBlur = vi.fn();+ const focus = vi.spyOn(HTMLInputElement.prototype, 'focus');render(<BottomSheetisOpenonOpenChange={() => {}}label="Add a comment"height="tall">- <button type="button" onBlur={onPreviousBlur}>- Previous action- </button>- <input- aria-label="Comment"- onPointerDown={event => event.preventDefault()}- onFocus={onFocus}- />+ <input aria-label="Comment" data-autofocus /></BottomSheet>,);- const previous = screen.getByRole('button', {name: 'Previous action'});+ // A prototype spy outlives this test unless it is put back by hand.+ const calls = [...focus.mock.calls];+ focus.mockRestore();const input = screen.getByRole('textbox', {name: 'Comment'});- const focus = vi.spyOn(input, 'focus');- previous.focus();-- const pointerDownAllowed = fireTouchPointer(input, 'pointerdown', {- x: 20,- y: 200,- });- fireTouchPointer(input, 'pointerup', {x: 20, y: 200});-- expect(pointerDownAllowed).toBe(false);- expect(focus).not.toHaveBeenCalled();- expect(document.activeElement).toBe(previous);- expect(onFocus).not.toHaveBeenCalled();- expect(onPreviousBlur).not.toHaveBeenCalled();- });- 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"- 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();- 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);+ // Opening focuses the field itself, so there is no transition to claim —+ // nothing was focused to blur. The presenting call has to refuse the+ // reveal on its own, or the browser scrolls the page to show a field the+ // sheet was about to show anyway.+ expect(document.activeElement).toBe(input);+ expect(calls).toContainEqual([{preventScroll: true}]);});- it('does not duplicate callbacks during programmatic input-to-input focus', () => {+ it('parks focus on the sheet when the keyboard Done button takes it', () => {mockIOSWebKit();- const onTitleBlur = vi.fn();- const onCommentFocus = vi.fn();render(<BottomSheetisOpenonOpenChange={() => {}}label="Add a comment"height="tall">- <input aria-label="Title" onBlur={onTitleBlur} />- <input aria-label="Comment" onFocus={onCommentFocus} />+ <input aria-label="Comment" /></BottomSheet>,);- const title = screen.getByRole('textbox', {name: 'Title'});- const comment = screen.getByRole('textbox', {name: 'Comment'});+ const sheet = getSheet();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ input.focus();+ const sheetFocus = vi.spyOn(sheet, 'focus');- title.focus();- comment.focus();+ // Done dismisses the keyboard and drops focus on the body. Left there,+ // the field is still document.activeElement on the next tap, so no+ // transition fires and the browser reveals it its own way. Parking focus+ // on the sheet keeps the next tap a transition this hook can claim.+ fireEvent.blur(input, {relatedTarget: null});- expect(document.activeElement).toBe(comment);- expect(onTitleBlur).toHaveBeenCalledTimes(1);- expect(onCommentFocus).toHaveBeenCalledTimes(1);+ expect(sheetFocus).toHaveBeenCalledWith({preventScroll: true});});it('does not alter ordinary desktop focus when the viewport is unobstructed', () => {@@ -1416,8 +1328,9 @@ describe('BottomSheet', () => {);viewport.height = 500;const focus = vi.spyOn(input, 'focus');- fireTouchPointer(input, 'pointerdown', {x: 20, y: 700});- fireTouchPointer(input, 'pointerup', {x: 20, y: 700});+ // A transition the browser would drive: at a shorter detent the hook+ // must not claim it, so nothing focuses the field but the caller.+ fireEvent.blur(sheet, {relatedTarget: input});expect(focus).not.toHaveBeenCalled();focus.mockRestore();@@ -1467,8 +1380,8 @@ describe('BottomSheet', () => {body.scrollTop = 20;fireEvent.touchStart(input);- fireTouchPointer(input, 'pointerdown', {x: 20, y: 200});- fireTouchPointer(input, 'pointerup', {x: 20, y: 200});+ // These heights opt out, so a browser-driven transition is left alone.+ fireEvent.blur(sheet, {relatedTarget: input});fireEvent.pointerDown(input, {pointerId: 1, clientY: 200});body.scrollTop = 120;fireEvent.focus(input, {relatedTarget: null});@@ -1767,6 +1680,342 @@ describe('BottomSheet', () => {'0px',);});++ it('puts back a document scroll the browser makes to reveal a field', () => {+ mockVisualViewport(377);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 57, bottom: 714}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 600 - body.scrollTop, bottom: 640 - body.scrollTop}),+ );+ input.focus();+ const scrollTo = vi.mocked(window.scrollTo);+ scrollTo.mockClear();+ const scrolledBy = body.scrollTop;++ // The page numbers an iPhone 17 produces when the browser reveals a+ // focused field in a scroll-locked, fixed sheet: it scrolls the DOCUMENT,+ // and the sheet — fixed — travels with it.+ Object.defineProperty(window, 'scrollY', {+ configurable: true,+ value: 337,+ });+ fireEvent.scroll(window);++ expect(scrollTo).toHaveBeenCalledWith(0, 0);+ // …and the control is still inside the safe area afterwards: the sheet's+ // own scroller holds it there, so putting the document back does not+ // hide what the browser was trying to reveal.+ expect(input.getBoundingClientRect().bottom).toBeLessThanOrEqual(+ 377 - 48,+ );+ expect(body.scrollTop).toBe(scrolledBy);+ Object.defineProperty(window, 'scrollY', {configurable: true, value: 0});+ });++ it('leaves the document alone when no keyboard is measured', () => {+ mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 57, bottom: 700}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(+ rect({top: 600, bottom: 640}),+ );+ input.focus();+ const scrollTo = vi.mocked(window.scrollTo);+ scrollTo.mockClear();++ // An ordinary page scroll with no keyboard up is the user's, not the+ // browser's, and a non-modal sheet leaves the page scrollable.+ Object.defineProperty(window, 'scrollY', {+ configurable: true,+ value: 120,+ });+ fireEvent.scroll(window);++ expect(scrollTo).not.toHaveBeenCalled();+ Object.defineProperty(window, 'scrollY', {configurable: true, value: 0});+ });++ it('delivers a browser-driven transition itself, then reveals the field', () => {+ mockIOSWebKit();+ mockVisualViewport(500);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Title" />+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const title = screen.getByRole('textbox', {name: 'Title'});+ const comment = screen.getByRole('textbox', {name: 'Comment'});+ const scrolls: {+ top: number;+ behavior?: ScrollBehavior;+ focusLanded: boolean;+ }[] = [];+ Object.defineProperty(body, 'scrollBy', {+ configurable: true,+ value: (options: ScrollToOptions) => {+ body.scrollTop += options.top ?? 0;+ scrolls.push({+ top: options.top ?? 0,+ behavior: options.behavior,+ focusLanded: document.activeElement === comment,+ });+ },+ });+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(title, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 150 - body.scrollTop, bottom: 190 - body.scrollTop}),+ );+ vi.spyOn(comment, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 660 - body.scrollTop, bottom: 700 - body.scrollTop}),+ );++ // The first field opens the keyboard and is already inside the safe+ // area, so nothing has to move for it.+ title.focus();+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ '348px',+ );+ expect(scrolls).toEqual([]);++ // A keyboard accessory "Next" or a Tab arrives as a blur naming the+ // destination. We deliver that focus with preventScroll — refusing the+ // browser's reveal — and then reveal the field ourselves, inside the+ // sheet.+ fireEvent.blur(title, {relatedTarget: comment});++ expect(document.activeElement).toBe(comment);+ expect(scrolls).toEqual([+ {top: 248, behavior: 'smooth', focusLanded: true},+ ]);+ expect(body.scrollTop).toBe(248);+ });++ it('does not scroll a browser-driven transition when the viewport is unobstructed', () => {+ mockIOSWebKit();+ mockVisualViewport(800);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Title" />+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const title = screen.getByRole('textbox', {name: 'Title'});+ const comment = screen.getByRole('textbox', {name: 'Comment'});+ const scrolls: number[] = [];+ Object.defineProperty(body, 'scrollBy', {+ configurable: true,+ // Apply the scroll, as the real scroller would: a reveal that has+ // already happened must read as no distance left to travel, otherwise+ // every later reveal looks like a fresh one.+ value: (options: ScrollToOptions) => {+ body.scrollTop += options.top ?? 0;+ scrolls.push(options.top ?? 0);+ },+ });+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: 800}),+ );+ vi.spyOn(title, 'getBoundingClientRect').mockReturnValue(+ rect({top: 150, bottom: 190}),+ );+ // Below the body's visible area, so a reveal has somewhere to travel.+ vi.spyOn(comment, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 860 - body.scrollTop, bottom: 900 - body.scrollTop}),+ );++ title.focus();+ scrolls.length = 0;+ const scrollTo = vi.mocked(window.scrollTo);+ scrollTo.mockClear();+ fireEvent.blur(title, {relatedTarget: comment});++ // With no keyboard there is no clearance to leave and nothing to race,+ // but the control still has to end up visible — brought there once, by+ // the sheet's own scroller, with the page left alone.+ expect(scrolls).toEqual([100]);+ expect(scrollTo).not.toHaveBeenCalled();+ });++ it('leaves the page alone behind a non-modal sheet', () => {+ const layoutBottom = window.innerHeight;+ mockVisualViewport(500);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall"+ hasScrim={false}>+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: layoutBottom}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 600 - body.scrollTop, bottom: 640 - body.scrollTop}),+ );+ input.focus();+ const scrollTo = vi.mocked(window.scrollTo);+ scrollTo.mockClear();++ // Without a scrim the page behind stays scrollable, so a document scroll+ // is the user's. Putting it back would fight them.+ Object.defineProperty(window, 'scrollY', {+ configurable: true,+ value: 200,+ });+ fireEvent.scroll(window);++ expect(scrollTo).not.toHaveBeenCalled();+ Object.defineProperty(window, 'scrollY', {configurable: true, value: 0});+ });++ it('holds the keyboard scroll range through a pan, on the blur path', () => {+ // A fully expanded Tall sheet — the only shape this hook runs in — is+ // pinned to the layout viewport bottom, so the body's bottom IS+ // innerHeight. Giving it a cushion below that would hide every bug in+ // this file: the cushion, not the measurement, would keep the overlap+ // positive under a pan.+ const layoutBottom = window.innerHeight;+ const viewport = mockVisualViewport(500);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const input = screen.getByRole('textbox', {name: 'Comment'});+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: layoutBottom}),+ );+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 660 - body.scrollTop, bottom: 700 - body.scrollTop}),+ );+ input.focus();+ const inset = body.style.getPropertyValue('--_sheet-keyboard-inset');+ expect(inset).toBe(`${layoutBottom - (500 - 48)}px`);++ // The browser pans the page up to reveal a field: the same 500px of+ // visible page, now offset so its bottom edge coincides with the layout+ // viewport bottom — with the keyboard still on screen. Read the bottom+ // and that is indistinguishable from the keyboard closing.+ viewport.offsetTop = window.innerHeight - 500;+ input.blur();++ // The keyboard did not change size, so neither does the scroll range.+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ inset,+ );+ });++ it('keeps defending a pinned sheet after the browser has panned it once', () => {+ // The regression that made the device symptom permanent: one pan read as+ // "no keyboard" cleared the inset AND cleared hasKeyboardLayout, which+ // disarms the head start below — so every subsequent reveal panned, and+ // the sheet never recovered.+ const layoutBottom = window.innerHeight;+ mockIOSWebKit();+ const viewport = mockVisualViewport(500);+ render(+ <BottomSheet+ isOpen+ onOpenChange={() => {}}+ label="Add a comment"+ height="tall">+ <input aria-label="Title" />+ <input aria-label="Comment" />+ </BottomSheet>,+ );+ const body = getBody();+ const title = screen.getByRole('textbox', {name: 'Title'});+ const comment = screen.getByRole('textbox', {name: 'Comment'});+ const scrolls: {top: number; focusLanded: boolean}[] = [];+ Object.defineProperty(body, 'scrollBy', {+ configurable: true,+ value: (options: ScrollToOptions) => {+ body.scrollTop += options.top ?? 0;+ scrolls.push({+ top: options.top ?? 0,+ focusLanded: document.activeElement === comment,+ });+ },+ });+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(+ rect({top: 100, bottom: layoutBottom}),+ );+ vi.spyOn(title, 'getBoundingClientRect').mockReturnValue(+ rect({top: 150, bottom: 190}),+ );+ vi.spyOn(comment, 'getBoundingClientRect').mockImplementation(() =>+ rect({top: 700 - body.scrollTop, bottom: 740 - body.scrollTop}),+ );++ title.focus();+ const inset = body.style.getPropertyValue('--_sheet-keyboard-inset');+ expect(inset).toBe(`${layoutBottom - (500 - 48)}px`);++ viewport.offsetTop = layoutBottom - 500;+ void act(() => viewport.dispatchEvent(new Event('resize')));+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(+ inset,+ );++ // And the next browser-driven transition is still claimed and revealed,+ // by a distance measured against the unshifted keyboard boundary.+ scrolls.length = 0;+ fireEvent.blur(title, {relatedTarget: comment});++ expect(document.activeElement).toBe(comment);+ expect(scrolls[0]).toEqual({+ top: 740 - (500 - 48),+ focusLanded: true,+ });+ });});describe('focus restore', () => {diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex f1e16fb845..45de45f902 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -169,6 +169,10 @@ function panelStateForSwitcherPhase(}}+// preventScroll on both: presenting a sheet must not scroll the page to reveal+// what it just focused. For an autofocused field that reveal is the mobile+// keyboard's, and it moves the document under a fixed sheet; useMobileKeyboard+// brings the field into view within the sheet instead.function focusPanel(panel: HTMLElement | null, isModal: boolean): void {const activeElement = document.activeElement;if (activeElement != null && panel?.contains(activeElement)) {@@ -176,9 +180,9 @@ function focusPanel(panel: HTMLElement | null, isModal: boolean): void {}const autofocus = panel?.querySelector<HTMLElement>('[data-autofocus]');if (autofocus != null) {- autofocus.focus();+ autofocus.focus({preventScroll: true});} else if (isModal) {- panel?.focus();+ panel?.focus({preventScroll: true});}}@@ -330,6 +334,7 @@ function StandaloneBottomSheet({state={panelState}height={height}isSwipeDismissAllowed={purpose === 'info'}+ isPageScrollLocked={shouldPresent && hasScrim}xstyle={xstyle}onDismiss={dismissOnLightInteraction}onScrimOpacity={handleScrimOpacity}@@ -484,6 +489,7 @@ function SwitcherBottomSheetItem({state={panelState}height={height}isSwipeDismissAllowed={purpose === 'info'}+ isPageScrollLocked={hasScrim}xstyle={xstyle}onDismiss={dismissOnSwipe}onScrimOpacity={handleScrimOpacity}diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex 9fe537bf65..3ff380e5f6 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -16,6 +16,7 @@* SYNC: When modified, update these files to stay in sync:* - /packages/core/src/BottomSheet/BottomSheet.tsx* - /packages/core/src/BottomSheet/BottomSheetPanel.test.tsx+ * - /packages/core/src/BottomSheet/useMobileKeyboard.ts* - /packages/core/src/BottomSheet/useSheetGestures.ts*/@@ -171,6 +172,8 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {height: BottomSheetHeight | number | string;children: ReactNode;isSwipeDismissAllowed?: boolean;+ /** Whether the host has locked page scrolling (a modal, scrim-backed sheet). */+ isPageScrollLocked?: boolean;onDismiss: () => void;onScrimOpacity: (opacity: number) => void;onElementChange?: (element: HTMLDivElement | null) => void;@@ -298,6 +301,7 @@ export function BottomSheetPanel({tabIndex,xstyle,isSwipeDismissAllowed = true,+ isPageScrollLocked = false,onDismiss,onScrimOpacity,onElementChange,@@ -372,6 +376,7 @@ export function BottomSheetPanel({bottomClearance: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,isEnabled: height === 'tall',isFullyExpanded: settledOffset === 0,+ isPageScrollLocked,isSheetTraveling: isDragging && dragOffset !== settledOffset,isOpen: isInteractive,isPresented,diff --git a/packages/core/src/BottomSheet/useMobileKeyboard.ts b/packages/core/src/BottomSheet/useMobileKeyboard.tsindex 8eb070bfcb..a6f03cbcbb 100644--- a/packages/core/src/BottomSheet/useMobileKeyboard.ts+++ b/packages/core/src/BottomSheet/useMobileKeyboard.ts@@ -12,12 +12,20 @@* 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.+ *+ * Every route into a field also has to reach it without the browser revealing+ * it for us. On iOS that reveal scrolls the DOCUMENT, and a fixed sheet travels+ * with it, so the whole page lurches. The reveal is attached to the focus+ * operation, which is where it can be refused: take the focus transition over+ * on the capture-phase blur, deliver it with preventScroll, and bring the+ * control into view with the sheet's own scroller afterwards. Every route in —+ * a tap, the keyboard's Next, Tab, a programmatic focus() — passes through that+ * one transition.*/import {useEffect, useRef, type RefObject} from 'react';const MOBILE_KEYBOARD_INSET_VAR = '--_sheet-keyboard-inset';-const TOUCH_FOCUS_MOVE_THRESHOLD = 10;const NON_TEXT_INPUT_TYPES = new Set(['button','checkbox',@@ -36,6 +44,7 @@ interface UseMobileKeyboardOptions {bottomClearance: number;isEnabled: boolean;isFullyExpanded: boolean;+ isPageScrollLocked: boolean;isSheetTraveling: boolean;isOpen: boolean;isPresented: boolean;@@ -46,53 +55,13 @@ interface KeyboardGeometry {bodyBottom: number;}-interface FocusScrollSnapshot {- target: HTMLElement;- elements: {- element: HTMLElement;- scrollLeft: number;- scrollTop: number;- }[];- windowX: number;- windowY: number;-}--interface PendingTouchFocus {- clientX: number;- clientY: number;- control: HTMLElement;- pointerDown: PointerEvent;- pointerId: number;+function getObstructionTop(): number {+ return window.visualViewport?.height ?? window.innerHeight;}-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),- };+// The keyboard is gone once the visible band reaches the layout viewport bottom.+function isVisualViewportRecovered(): boolean {+ return getObstructionTop() >= window.innerHeight - 0.5;}function isIOSWebKit(): boolean {@@ -147,6 +116,7 @@ export function useMobileKeyboard({bottomClearance,isEnabled,isFullyExpanded,+ isPageScrollLocked,isSheetTraveling,isOpen,isPresented,@@ -154,10 +124,10 @@ export function useMobileKeyboard({}: UseMobileKeyboardOptions): void {const hasKeyboardLayoutRef = useRef(false);const retainKeyboardLayoutRef = useRef(false);- const isActiveRef = useRef(isOpen);const isFullyExpandedRef = useRef(isFullyExpanded);- isActiveRef.current = isOpen;+ const isOpenRef = useRef(isOpen);isFullyExpandedRef.current = isFullyExpanded;+ isOpenRef.current = isOpen;useEffect(() => {if (!isEnabled || !isSheetTraveling) {@@ -205,35 +175,17 @@ export function useMobileKeyboard({}let keyboardGeometry: KeyboardGeometry | null = null;- let pendingFocusScroll: FocusScrollSnapshot | null = null;- let pendingPointerFocusScroll: FocusScrollSnapshot | null = null;- let pendingTouchFocus: PendingTouchFocus | null = null;- const preventFocusScroll = isIOSWebKit();+ let documentScrollAtKeyboard: {x: number; y: number} | null = null;+ const ownsFocusTransitions = isIOSWebKit();const clearKeyboardLayout = () => {body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, '0px');keyboardGeometry = null;+ documentScrollAtKeyboard = 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;@@ -244,21 +196,51 @@ export function useMobileKeyboard({window.matchMedia('(prefers-reduced-motion: reduce)').matches;body.scrollBy({top: distance,- behavior: smoothly && !reduceMotion ? 'smooth' : 'auto',+ // Not 'auto': that defers to the element's computed `scroll-behavior`,+ // so a consumer's `scroll-behavior: smooth` would animate a scroll this+ // hook needs to land in the same frame.+ behavior: smoothly && !reduceMotion ? 'smooth' : 'instant',});};+ // Scroll `control` into the part of the body the keyboard leaves visible,+ // reading live geometry each time.+ const scrollControlIntoSafeArea = (+ control: HTMLElement,+ smoothly: boolean,+ ) => {+ const measuredBodyRect = body.getBoundingClientRect();+ const measuredControlRect = control.getBoundingClientRect();+ const obstructionTop = getObstructionTop();+ const overlap = Math.max(0, measuredBodyRect.bottom - obstructionTop);+ const clearance = overlap > 0 ? bottomClearance : 0;+ const safeTop = measuredBodyRect.top;+ const safeBottom = Math.min(+ measuredBodyRect.bottom,+ obstructionTop - clearance,+ );+ if (safeBottom <= safeTop) {+ return;+ }++ if (measuredControlRect.bottom > safeBottom) {+ scrollBodyBy(measuredControlRect.bottom - safeBottom, smoothly);+ } else if (measuredControlRect.top < safeTop) {+ scrollBodyBy(measuredControlRect.top - safeTop, smoothly);+ }+ };+const applyKeyboardGeometry = (geometry: KeyboardGeometry) => {- const viewport = getVisualViewportBounds();+ const obstructionTop = getObstructionTop();// A collapsed detent can extend the body below the layout viewport even// after the keyboard closes, so body overlap alone cannot identify- // recovery. Once the visual viewport reaches the layout viewport bottom,- // release the retained keyboard layout unconditionally.- if (viewport.bottom >= window.innerHeight - 0.5) {+ // recovery. Once the visual viewport is full height again, release the+ // retained keyboard layout unconditionally.+ if (isVisualViewportRecovered()) {clearKeyboardLayout();return;}- const overlap = Math.max(0, geometry.bodyBottom - viewport.bottom);+ const overlap = Math.max(0, geometry.bodyBottom - obstructionTop);if (overlap === 0) {clearKeyboardLayout();return;@@ -266,105 +248,46 @@ export function useMobileKeyboard({const inset = Math.max(0,- geometry.bodyBottom - (viewport.bottom - bottomClearance),+ geometry.bodyBottom - (obstructionTop - bottomClearance),);body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);};- // 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 =- 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();+ // Take the focus transition over before the browser performs it.+ //+ // `blur` is dispatched in the capture phase ahead of the browser's own+ // focus step, and it names the destination in `relatedTarget`. Focusing it+ // here with preventScroll settles the transition: the browser's step finds+ // the element already active, so it dispatches nothing further and has+ // nothing to reveal.+ const claimFocusTransition = (event: FocusEvent) => {+ if (!isFullyExpandedRef.current) {+ return;}- };- const 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;+ const destination = findTextEntryControl(event.relatedTarget, body);+ if (destination) {+ if (destination !== document.activeElement) {+ // Revealing the field is not this handler's job: focusing it raises+ // focusin, and the viewport resize that follows the keyboard raises+ // another — both already schedule the reveal below, which knows the+ // safe area and scrolls only the sheet's own body.+ destination.focus({preventScroll: true});}return;}- pending.control.focus({preventScroll: true});- };-- // 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 (!isFullyExpandedRef.current || !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?.target === control) {- restoreScrollSnapshot(snapshot);+ // Focus left for nothing — the keyboard's Done button parks it on the+ // body. Park it on the sheet instead, so re-tapping the same field is+ // still a transition this handler sees. Left on the body, the field is+ // already `document.activeElement` on the next tap, no blur fires, and+ // the browser reveals it its own way.+ //+ // Only while the sheet is open: closing blurs the field too, and there+ // is no next tap to keep claimable — the host restores focus to whatever+ // opened the sheet.+ const origin = findTextEntryControl(event.target, body);+ if (isOpenRef.current && origin && !event.relatedTarget) {+ sheet?.focus({preventScroll: true});}};@@ -387,9 +310,8 @@ export function useMobileKeyboard({retainKeyboardLayoutRef.current = false;const measuredBodyRect = body.getBoundingClientRect();- const measuredFocusedRect = activeElement.getBoundingClientRect();- const viewport = getVisualViewportBounds();- const overlap = Math.max(0, measuredBodyRect.bottom - viewport.bottom);+ const obstructionTop = getObstructionTop();+ const overlap = Math.max(0, measuredBodyRect.bottom - obstructionTop);// The extra clearance leaves room for mobile suggestion UI, but only// while the visual viewport actually overlaps the sheet. With no// obstruction, ordinary desktop and hardware-keyboard focus must not@@ -401,28 +323,22 @@ export function useMobileKeyboard({bodyBottom: measuredBodyRect.bottom,}: null;+ // Where the document sits with the keyboard up and nothing yet shifted:+ // the position handleDocumentScroll returns to. Captured on the+ // transition only — a reveal that runs after the browser has already+ // scrolled would otherwise record the shifted position as correct.+ if (isPageScrollLocked && overlap > 0 && !hasKeyboardLayoutRef.current) {+ documentScrollAtKeyboard = {x: window.scrollX, y: window.scrollY};+ }hasKeyboardLayoutRef.current = overlap > 0;const inset =overlap > 0- ? Math.max(0, measuredBodyRect.bottom - (viewport.bottom - clearance))+ ? Math.max(0, measuredBodyRect.bottom - (obstructionTop - clearance)): 0;body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);- const safeTop = Math.max(measuredBodyRect.top, viewport.top);- const safeBottom = Math.min(- measuredBodyRect.bottom,- viewport.bottom - clearance,- );- if (safeBottom <= safeTop) {- return;- }-- if (measuredFocusedRect.bottom > safeBottom) {- scrollBodyBy(measuredFocusedRect.bottom - safeBottom, overlap > 0);- } else if (measuredFocusedRect.top < safeTop) {- scrollBodyBy(measuredFocusedRect.top - safeTop, overlap > 0);- }+ scrollControlIntoSafeArea(activeElement, overlap > 0);};let animationFrame = 0;@@ -431,6 +347,33 @@ export function useMobileKeyboard({animationFrame = requestAnimationFrame(revealFocusedControl);};+ // Resuming the app re-reveals the focused field with no focus event to+ // claim, so the reveal above never runs and the document scrolls — taking+ // the fixed sheet with it. Put that scroll back on the event that reports+ // it and re-reveal inside the sheet.+ //+ // Only while the page is locked, which is the only state in which a+ // document scroll cannot be the user's own: behind a non-modal sheet the+ // page stays scrollable, and reverting there would fight them.+ const handleDocumentScroll = () => {+ const expected = documentScrollAtKeyboard;+ if (+ expected == null ||+ (window.scrollX === expected.x && window.scrollY === expected.y)+ ) {+ return;+ }+ window.scrollTo(expected.x, expected.y);+ const activeElement = document.activeElement;+ if (+ activeElement instanceof HTMLElement &&+ body.contains(activeElement) &&+ isTextEntryControl(activeElement)+ ) {+ scrollControlIntoSafeArea(activeElement, false);+ }+ };+const resizeObserver =typeof ResizeObserver === 'undefined'? null@@ -503,23 +446,18 @@ export function useMobileKeyboard({};const viewport = window.visualViewport;- 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);+ if (ownsFocusTransitions) {+ // `blur` does not bubble, so the capture phase is the only place to hear+ // every one of them — and it runs before the browser's own focus step,+ // which is the only window in which the transition can still be claimed.+ document.addEventListener('blur', claimFocusTransition, true);}body.addEventListener('focusin', handleFocusIn);body.addEventListener('focusout', handleFocusOut);sheet?.addEventListener('transitionend', handleSheetTransitionEnd);viewport?.addEventListener('resize', scheduleReveal);viewport?.addEventListener('scroll', scheduleReveal);+ window.addEventListener('scroll', handleDocumentScroll);window.addEventListener('resize', scheduleReveal);mutationObserver?.observe(body, {attributes: true,@@ -534,27 +472,15 @@ export function useMobileKeyboard({return () => {cancelAnimationFrame(animationFrame);- 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);+ if (ownsFocusTransitions) {+ document.removeEventListener('blur', claimFocusTransition, true);}body.removeEventListener('focusin', handleFocusIn);body.removeEventListener('focusout', handleFocusOut);sheet?.removeEventListener('transitionend', handleSheetTransitionEnd);viewport?.removeEventListener('resize', scheduleReveal);viewport?.removeEventListener('scroll', scheduleReveal);+ window.removeEventListener('scroll', handleDocumentScroll);window.removeEventListener('resize', scheduleReveal);resizeObserver?.disconnect();mutationObserver?.disconnect();@@ -562,5 +488,12 @@ export function useMobileKeyboard({hasKeyboardLayoutRef.current = false;retainKeyboardLayoutRef.current = false;};- }, [bodyRef, bottomClearance, isEnabled, isPresented, sheetRef]);+ }, [+ bodyRef,+ bottomClearance,+ isEnabled,+ isPageScrollLocked,+ isPresented,+ sheetRef,+ ]);}