Skip to content

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

TypeScript

fix(Layer, Selector): the overlay slides above the software keyboard and keeps its top (#10169)

Christopher Chedeaua5b485e92507
diff --git a/.changeset/selector-overlay-above-keyboard.md b/.changeset/selector-overlay-above-keyboard.md
new file mode 100644
index 0000000000..0f4aed5037
--- /dev/null
+++ b/.changeset/selector-overlay-above-keyboard.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A Selector's list, opened over its trigger near the bottom of the screen while a software keyboard is up, now slides up and ends above the keyboard with its options in view. Before, it shrank to a sliver or opened under the keyboard. Without a keyboard it opens where it did.
+
+@vjeux
diff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsx
index bc5828f595..ba0fb8d5eb 100644
--- a/apps/storybook/stories/Selector.stories.tsx
+++ b/apps/storybook/stories/Selector.stories.tsx
@@ -6,6 +6,7 @@ import {useState} from 'react';
import {Button} from '@astryxdesign/core/Button';
import {InputGroup, InputGroupText} from '@astryxdesign/core/InputGroup';
import {Selector, SelectorOption} from '@astryxdesign/core/Selector';
+import {TextInput} from '@astryxdesign/core/TextInput';
import {Theme, defineTheme} from '@astryxdesign/core/theme';
import {RadioIndicator} from '@astryxdesign/core/Indicator';
import {
@@ -1103,6 +1104,37 @@ export const PreSelected: Story = {
},
};
+/**
+ * A text field above a Selector. On a phone, focus the field so that its
+ * software keyboard rises, then open the Selector. Its list slides above the
+ * keyboard, with every option in view.
+ */
+export const OverlayBesideKeyboard: Story = {
+ parameters: {layout: 'fullscreen'},
+ render: () => {
+ const [name, setName] = useState('');
+ const [value, setValue] = useState<string | undefined>('Banana');
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 16,
+ padding: '96px 24px 0',
+ }}>
+ <TextInput label="Name" value={name} onChange={setName} />
+ <div style={{height: 64}} />
+ <Selector
+ label="Fruit"
+ options={['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig']}
+ value={value}
+ onChange={v => setValue(v)}
+ />
+ </div>
+ );
+ },
+};
+
// All variations
export const AllVariations: Story = {
render: () => {
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index ff367e0890..6213da25df 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -546,7 +546,9 @@ layers use Layer rendering without joining Escape/platform dismissal.
that reads it scrolls from the frame the cap lands, and its content never
paints past the capped box. A layer the keyboard does not reach, a layer
placed above its trigger, and a layer in custom or fixed mode stay as they
- are.
+ are. A layer that reads the keyboard inset and was placed while a keyboard is
+ reported keeps its top until it closes: when the cap lifts it grows downward
+ in place; when the keyboard rises it moves up above it and then holds.
- **INV12 — The first frame is the settled frame.** No input to a layer's
viewport geometry is measured after paint and then applied, with two
exceptions. The runtime observes anchor visibility for every layer, and,
@@ -805,7 +807,7 @@ this current architecture record.
| INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost |
| INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport; `BaseTypeahead.incremental.test.tsx` and the Typeahead incremental-results stories for the `spec:AST-092` FR6 exception | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor; for an open Typeahead popup, a later list for the same query that flips it to the other side or grows it past the room on its side, or a first list for a query that is capped to the span beside the trigger |
| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |
-| INV11, INV12 | The software keyboard's cap: `useLayerKeyboardClearance.test.tsx` for its rule, its timing, and its read before first paint; `PopoverKeyboard.interaction.browser.spec.ts` and `keyboardCappedLists.interaction.browser.spec.ts` for its rendered geometry in Chromium and WebKit | A layer that runs under the keyboard, or is capped though the keyboard does not reach it; a cap that changes more than once per keyboard movement or under a press; a layer opened with the keyboard up whose first frame is uncapped or paints its content past its box |
+| INV11, INV12 | The software keyboard's cap: `useLayerKeyboardClearance.test.tsx` for its rule, its timing, its read before first paint, and the inset's hold; the `PopoverKeyboard`, `keyboardCappedLists` and `SelectorKeyboardInset` browser specs for its rendered geometry | A layer that runs under the keyboard, or is capped though the keyboard does not reach it; a cap that changes more than once per keyboard movement or under a press; a layer opened with the keyboard up whose first frame is uncapped or paints its content past its box; a layer that reads the inset and moves down when the keyboard report ends |
| INV13 | `layerExitCopy.test.ts` and `layerExitCopy.interaction.browser.spec.ts` | A copy with an id, a form name, a form owner, or pointer reach; a copy off the layer's drawn box; a copy outside the top layer; a second copy for one layer |
| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |
| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |
diff --git a/docs/specs/AST-059-layer-viewport-inset/spec.md b/docs/specs/AST-059-layer-viewport-inset/spec.md
index c8fc09e168..458833c472 100644
--- a/docs/specs/AST-059-layer-viewport-inset/spec.md
+++ b/docs/specs/AST-059-layer-viewport-inset/spec.md
@@ -340,6 +340,15 @@ the app reaches every layer instead of the components that happen to read it.
surface inside it capped by that definition shrink together. Each layer
carries its own cap on its own element: a layer opened inside a capped
layer is capped only for its own box, never by its host's.
+ Once a software keyboard is up, the runtime also writes its block-end inset
+ on each open anchor-mode layer, beside the cap: the keyboard's height plus
+ the 10 px clearance. The inset keeps its largest value until the layer
+ closes. The inset is a private custom property that only the runtime writes,
+ never public API, and the fallback order never reads it. A layer that places
+ itself on its block axis, such as Selector's selected-item overlay, ends
+ above the line the inset marks. It moves in the commit that publishes the
+ inset, before the cap reads its box. A keyboard that goes down then leaves
+ it where it is.
- **FR10 — The keyboard cap changes where the keyboard hides the change.**
A
box's height cannot change on the compositor, so the cap changes once per
@@ -485,7 +494,7 @@ for any row.
| FR6 | Stories "app-declared inset (floating bar)" and "layer portaled out of its JSX position"; `LayerProvider` and `ToastViewport` unit suites | An 80px bar declared as `inset={{blockEnd: 80}}`; a toast under the same provider; a `toast.inset` override; no provider; a layer hosted outside the paragraph it was rendered in | A layer or toast ends under the bar, an unset edge moves anything, a `toast.inset` edge stops overriding, no-provider geometry differs from the default provider's, or a portaled layer loses the inset |
| FR8 | Every story above (first frame compared with settled); stories "inset changes while the layer is open", "layer opens in the frame the inset arrives", "inset measured by the app", "anchor already off-screen when the layer opens" | The provider's inset changes 80→160 with the layer open; a layer mounted open in the provider's first commit; a bar the app measures before paint and declares; an off-screen anchor at open | The first frame's rectangle differs from the settled one, or the first frame after a declaration change is not already at the new geometry |
| FR4, FR8 scroll (DEC-7, DEC-8) | Before-and-after evidence in real Chromium for each of DEC-7's seven rows; a performance trace of a page scroll and a scroll inside a scrolling panel that carry a tooltip's trigger past the scroll edge, counting forced layouts per scroll frame before and after; the runtime's anchor-clear unit suite for when the don't-cover check runs; the tooltip suite's scroll-edge case; a count of forced layouts per scroll with the re-pick after `scrollend`, and with the 150 ms fallback where `scrollend` is unsupported | An open tooltip whose trigger a page scroll carries out of the page and back; the same inside a scrolling panel; the layer's show, a remount, a ResizeObserver report, and a window resize; a top-layer layer whose anchor leaves the page; a wheel scroll that ends with the trigger at the scroll edge | A forced layout or layout read for a layer in a scroll frame other than one in which the anchor's visibility changes; a don't-cover check, `scroll` or `scrollend` read, or forced re-pick during a scroll; an observer of a trigger that moves without resizing; a layer that slides or vanishes instead of holding when its anchor leaves the page; the scroll-edge case fails, a layout read lands during the scroll or in a scroll handler, or the re-pick runs before the first painted frame after the stop |
-| FR9 | `useLayerKeyboardClearance.test.tsx`; Popover's keyboard browser proofs in Chromium and WebKit with a stand-in keyboard; the iOS simulator | A tall Popover below its trigger with a field; a keyboard already up at the open; a short layer; a layer above its trigger | A capped layer ending under the keyboard or more than 10 px above it, an unreached layer that changes, a bottom-held layer that moves, or a layer measuring the keyboard itself |
+| FR9 | `useLayerKeyboardClearance.test.tsx`; Popover's keyboard browser proofs in Chromium and WebKit with a stand-in keyboard; the iOS simulator; Selector's keyboard inset browser proof | A tall Popover below its trigger with a field; a keyboard already up at the open; a short layer; a layer above its trigger; a Selector overlay that slides above the keyboard | A capped layer ending under the keyboard or more than 10 px above it, an unreached layer that changes, a bottom-held layer that moves, or a layer measuring the keyboard itself |
| FR10 | `useLayerKeyboardClearance.test.tsx`; Popover's keyboard browser proofs | A rising keyboard before and after it arrives; a falling keyboard; a keyboard that changes at once; a tap on Save as the keyboard falls | A cap written while the keyboard rises, kept as it falls, or taken off under a press before its click |
| FR1 safe area | A device run: `env(safe-area-inset-*)` is set only by a real device and Chromium emulation does not populate it, so no Storybook story can show it. | Landscape phone with a notch on one side | A layer under the notch |
diff --git a/docs/specs/components/Selector/Selector.spec.md b/docs/specs/components/Selector/Selector.spec.md
index c337dd5a36..663a73d1cc 100644
--- a/docs/specs/components/Selector/Selector.spec.md
+++ b/docs/specs/components/Selector/Selector.spec.md
@@ -153,7 +153,7 @@ These requirements describe shipped behavior on current `main`.
| ID | Shipped invariant | Evidence |
| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| FR1 | Selecting an enabled option updates the one selected value, closes the active presentation, and returns the trigger to its stable closed state. | Consumer docs and selection interaction tests |
-| FR2 | Without explicit placement, a non-search popover aligns the selected row over the trigger and clamps it to the viewport. Search popovers and explicit placement use normal Layer positioning. | Consumer docs, implementation, and geometry tests |
+| FR2 | Without explicit placement, a non-search popover aligns the selected row over the trigger and clamps it to the viewport, above any software keyboard (`spec:AST-059` FR9); a keyboard that goes down while it is open does not move its top. Search popovers and explicit placement use normal Layer positioning. | Consumer docs, implementation, and geometry tests |
| FR3 | An option whose resolved selection indicator draws no content reserves no mark-column space. Visible selected or themed replacement indicators remain in layout at `indicatorPosition`; the resulting state-dependent label position or available width is intentional, and row content keeps its existing overflow behavior. | `itemMarkColumn`, focused indicator tests, and Chromium evidence stories |
| FR4 | `popover` uses an anchored Popover. `bottom-sheet` uses a modal BottomSheet. `adaptive` resolves to the modal bottom sheet on compact coarse-pointer screens and Popover otherwise. | Presentation controller and adaptive-presentation tests |
| FR5 | While `isLoading` is true, the trigger exposes busy state and the listbox suppresses empty and no-results output. | Loading, empty-state, and announcement tests |
@@ -354,7 +354,7 @@ new theming target.
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| FR1, AR2, AR3 | `Selector.test.tsx` selection, focus, and keyboard suites, including "leaves focus on the field a press moved it to" and "returns focus to the trigger when the press lands on nothing focusable" | closed/open, search/non-search, disabled option | Removing selection wiring, focus movement, or keyboard behavior fails the named interaction tests | `audit:Selector/behavior` |
-| FR2 | placement and selected-item geometry tests | default, explicit, RTL, transformed entry | Using the wrong positioning model fails the expected position-area or margin | `audit:Selector/behavior` |
+| FR2 | placement and selected-item geometry tests; `SelectorKeyboardInset.a11y.chromium.spec.ts` | default, explicit, RTL, transformed entry, keyboard up | Using the wrong positioning model fails the expected position-area or margin | `audit:Selector/behavior` |
| FR3, AV1 | Focused `Selector.test.tsx` computed-display checks plus guarded Chromium Storybook matrix and stable visual stories | popover/bottom sheet, narrow/wide, start/end, LTR/RTL, selected/unselected, check/radio | Empty output reserves width, visible output collapses, logical placement flips incorrectly, or row content overflows | `audit:Selector/design-rendered` |
| FR4, AR1, AR2 | presentation tests plus `aria-haspopup` source review | pointer, compact coarse pointer, search/non-search | Wrong Popover/dialog roles or focus destinations fail tests; `aria-haspopup` values require source/a11y review | `audit:Selector/accessibility` |
| AR1, AV2 | `Selector.listbox.a11y.test.tsx` and `Listbox.a11y.chromium.spec.ts` against the shared Listbox contract; `SelectorListboxName.a11y.chromium.spec.ts` and `Selector.test.tsx` "names the listbox with the field label, not the trigger that shows the value" for the listbox name; `Selector.test.tsx` "Selector with hasSearch: the closed trigger names the selection" for the button trigger's name; `SelectorListboxName.a11y.chromium.spec.ts` "the closed searchable trigger is named by the label and the selected value" for the accessibility tree | popover/sheet, flat/grouped, selected/unselected, disabled, search, loading, custom RTL | A new or wider loss of role, listbox/option name, state, or ownership gates | `audit:Selector/accessibility` |
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index fbd4927155..9ef4938b6e 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -68,13 +68,20 @@ const styles = stylex.create({
// layer nested in a capped one does not inherit the outer cap. The surfaces
// inside a layer read it through `layerViewportInset.maxBlockSize`. The cap
// also writes the overflow a capped surface takes. Popover's surface reads
- // it, so it scrolls from the commit that caps it. Both are private runtime
- // state, never set by an app or a theme.
- // SYNC: the properties are LAYER_KEYBOARD_CAP_PROPERTY and
- // LAYER_KEYBOARD_OVERFLOW_PROPERTY (useLayerKeyboardClearance.ts).
- keyboardCap: (cap: string, overflow: 'auto' | 'visible') => ({
+ // it, so it scrolls from the commit that caps it. Beside them, the
+ // keyboard's inset from the viewport's bottom lets a layer that places
+ // itself slide above the keyboard. The inset keeps its largest value until
+ // the layer closes, so that layer stays put as the keyboard goes. Every
+ // layer sets it, `initial` until a keyboard is up, so a nested layer does
+ // not inherit it. All three are private runtime state, never set by an app
+ // or a theme.
+ // SYNC: the properties are LAYER_KEYBOARD_CAP_PROPERTY,
+ // LAYER_KEYBOARD_OVERFLOW_PROPERTY and LAYER_KEYBOARD_INSET_PROPERTY
+ // (useLayerKeyboardClearance.ts).
+ keyboardCap: (cap: string, overflow: 'auto' | 'visible', inset: string) => ({
'--_layer-keyboard-max-block-size': cap,
'--_layer-keyboard-overflow': overflow,
+ '--_layer-keyboard-inset-block-end': inset,
}),
// Base reset for all layers
base: {
@@ -1678,10 +1685,11 @@ function useLayerImplementation(
// An anchored layer that would run under the software keyboard keeps its
// block-start edge and ends clear of the keyboard.
- const {cap: keyboardCap, followLayerElement} = useLayerKeyboardClearance(
- isOpen && mode === 'context',
- popoverRef,
- );
+ const {
+ cap: keyboardCap,
+ inset: keyboardInset,
+ followLayerElement,
+ } = useLayerKeyboardClearance(isOpen && mode === 'context', popoverRef);
const popoverRefCallback = useCallback(
(el: HTMLElement | null) => {
@@ -1924,6 +1932,7 @@ function useLayerImplementation(
styles.keyboardCap(
keyboardCap == null ? '100vh' : `${keyboardCap}px`,
keyboardCap == null ? 'visible' : 'auto',
+ keyboardInset == null ? 'initial' : `${keyboardInset}px`,
),
viewportStyles,
offsetStyle,
@@ -1984,6 +1993,7 @@ function useLayerImplementation(
isAnchorInView,
keepsAnchorClear,
keyboardCap,
+ keyboardInset,
lightDismiss,
mountStore,
popoverRefCallback,
@@ -2015,7 +2025,7 @@ function useLayerImplementation(
overlayPaddingReset.reset,
// A fixed layer is never capped; it still sets its own limit so it is
// not clamped by a capped layer it sits in.
- styles.keyboardCap('100vh', 'visible'),
+ styles.keyboardCap('100vh', 'visible', 'initial'),
styles.fixed,
xstyle,
);
diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx b/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
index 0252115db9..66feeb16dd 100644
--- a/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
+++ b/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
@@ -34,6 +34,7 @@ import {
LAYER_ANCHORED_ATTRIBUTE,
LAYER_KEYBOARD_CAP_PROPERTY,
LAYER_KEYBOARD_CLEARANCE_PX,
+ LAYER_KEYBOARD_INSET_PROPERTY,
useLayerKeyboardClearance,
} from './useLayerKeyboardClearance';
import {useLayer} from './useLayer';
@@ -119,6 +120,7 @@ function Harness({
layerKey = 'a',
entering,
shiftedTop,
+ slidesAboveKeyboard = false,
}: {
isOpen?: boolean;
isAnchored?: boolean;
@@ -137,9 +139,17 @@ function Harness({
* `box` and over its trigger; any shorter, it sits at `box`.
*/
shiftedTop?: number;
+ /**
+ * Places itself by the keyboard inset, as Selector's overlay does: while an
+ * inset is out, the layer ends above it.
+ */
+ slidesAboveKeyboard?: boolean;
}) {
const layerRef = useRef<HTMLDivElement>(null);
- const {cap, followLayerElement} = useLayerKeyboardClearance(isOpen, layerRef);
+ const {cap, inset, followLayerElement} = useLayerKeyboardClearance(
+ isOpen,
+ layerRef,
+ );
// The layer's box: its content height, no taller than the cap the hook
// returned. The runtime applies the cap as the layer's own style, which its
// block-size cap folds in; the harness applies it the same way. Below its
@@ -157,6 +167,9 @@ function Harness({
{...(isAnchored ? {[LAYER_ANCHORED_ATTRIBUTE]: ''} : {})}
style={{
...(cap == null ? {} : {[LAYER_KEYBOARD_CAP_PROPERTY]: `${cap}px`}),
+ ...(inset == null
+ ? {}
+ : {[LAYER_KEYBOARD_INSET_PROPERTY]: `${inset}px`}),
...(entering == null ? {} : {transform: `translateY(${entering}px)`}),
}}
data-testid="layer"
@@ -178,8 +191,15 @@ function Harness({
? entering
: 0;
const natural = box.bottom - box.top;
- const start =
+ const keyboardInset = parseFloat(
+ el.style.getPropertyValue(LAYER_KEYBOARD_INSET_PROPERTY),
+ );
+ const placed =
shiftedTop != null && h >= natural ? shiftedTop : box.top;
+ const start =
+ slidesAboveKeyboard && !Number.isNaN(keyboardInset)
+ ? Math.min(placed, VIEWPORT - keyboardInset - h)
+ : placed;
const top = (heldBottom ? box.bottom - h : start) + shift;
return {
top,
@@ -260,6 +280,11 @@ const capOf = (container: HTMLElement) =>
.querySelector<HTMLElement>('[data-testid="layer"]')!
.style.getPropertyValue(LAYER_KEYBOARD_CAP_PROPERTY);
+const insetOf = (container: HTMLElement) =>
+ container
+ .querySelector<HTMLElement>('[data-testid="layer"]')!
+ .style.getPropertyValue(LAYER_KEYBOARD_INSET_PROPERTY);
+
describe('keyboardClearanceCap', () => {
it('keeps the far edge 10 pt above the keyboard, and leaves a layer clear of it', () => {
expect(LAYER_KEYBOARD_CLEARANCE_PX).toBe(10);
@@ -403,6 +428,60 @@ describe('useLayerKeyboardClearance', () => {
expect(capOf(container)).toBe(`${VIEWPORT - 300 - 10 - BOX.top}px`);
});
+ it('publishes the keyboard\u2019s inset, clearance included, and keeps its largest value until the layer closes', () => {
+ const {container, rerender} = render(<Harness />);
+ expect(insetOf(container)).toBe('');
+ guide.emit({kind: 'change', from: 0, to: 300, animated: false});
+ expect(insetOf(container)).toBe(`${300 + LAYER_KEYBOARD_CLEARANCE_PX}px`);
+ // A taller keyboard raises it. A shorter one, or none, leaves it.
+ guide.emit({kind: 'change', from: 300, to: COVER, animated: false});
+ expect(insetOf(container)).toBe(`${COVER + LAYER_KEYBOARD_CLEARANCE_PX}px`);
+ guide.emit({kind: 'change', from: COVER, to: 300, animated: false});
+ expect(insetOf(container)).toBe(`${COVER + LAYER_KEYBOARD_CLEARANCE_PX}px`);
+ guide.emit({kind: 'hide', from: 300, to: 0});
+ expect(insetOf(container)).toBe(`${COVER + LAYER_KEYBOARD_CLEARANCE_PX}px`);
+ rerender(<Harness isOpen={false} />);
+ expect(insetOf(container)).toBe('');
+ });
+
+ it('publishes the inset in the commit that lifts the cap, so a layer that slides above the keyboard on it is not capped', () => {
+ const {container} = render(<Harness slidesAboveKeyboard />);
+ guide.emit({kind: 'change', from: 0, to: COVER, animated: false});
+ expect(insetOf(container)).toBe(`${COVER + LAYER_KEYBOARD_CLEARANCE_PX}px`);
+ // The box was read after the inset moved it: it ends above the keyboard
+ // whole, so nothing caps it.
+ expect(capOf(container)).toBe('');
+ const layer = screen.getByTestId('layer');
+ expect(layer.getBoundingClientRect().bottom).toBe(
+ VIEWPORT - COVER - LAYER_KEYBOARD_CLEARANCE_PX,
+ );
+ });
+
+ it('takes the cap off a layer that does not read the inset at once as the keyboard goes down, even where that moves it (spec:AST-059 FR10)', () => {
+ // At its full height the viewport fit places this layer over its
+ // trigger; capped, it sits below the trigger.
+ const {container} = render(
+ <Harness box={{top: 300, bottom: 700}} shiftedTop={120} />,
+ );
+ guide.emit({kind: 'change', from: 0, to: COVER, animated: false});
+ expect(capOf(container)).not.toBe('');
+ const layer = screen.getByTestId('layer');
+ expect(layer.getBoundingClientRect().top).toBe(300);
+ guide.emit({kind: 'hide', from: COVER, to: 0});
+ expect(capOf(container)).toBe('');
+ expect(layer.getBoundingClientRect().top).toBe(120);
+ });
+
+ it('leaves a layer that slid above the keyboard where it is when the keyboard goes down', () => {
+ const {container} = render(<Harness slidesAboveKeyboard />);
+ guide.emit({kind: 'change', from: 0, to: COVER, animated: false});
+ const layer = screen.getByTestId('layer');
+ const placed = layer.getBoundingClientRect().top;
+ guide.emit({kind: 'hide', from: COVER, to: 0});
+ expect(capOf(container)).toBe('');
+ expect(layer.getBoundingClientRect().top).toBe(placed);
+ });
+
it('caps in layout px under a pinch zoom, where WebKit reports innerHeight zoomed (spec:AST-059 FR9)', () => {
// WebKit reports innerHeight and innerWidth in the zoomed visual
// viewport's px. Safari on iOS 26.2 reports 536 for a 714 px layout
@@ -494,8 +573,10 @@ describe('useLayerKeyboardClearance', () => {
});
expect(frames).toHaveLength(0);
expect(capOf(container)).toBe(CAPPED);
+ expect(insetOf(container)).toBe(`${COVER + LAYER_KEYBOARD_CLEARANCE_PX}px`);
rerender(<Harness isOpen={false} />);
expect(capOf(container)).toBe('');
+ expect(insetOf(container)).toBe('');
expect(guide.listeners.size).toBe(0);
});
diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.ts b/packages/core/src/Layer/useLayerKeyboardClearance.ts
index d03aff52f7..20c0db252e 100644
--- a/packages/core/src/Layer/useLayerKeyboardClearance.ts
+++ b/packages/core/src/Layer/useLayerKeyboardClearance.ts
@@ -8,8 +8,8 @@
* module: its one height, and its layout guide for timing.
* @output Exports `useLayerKeyboardClearance` and its result type,
* `keyboardClearanceCap`, `LAYER_ANCHORED_ATTRIBUTE`,
- * `LAYER_KEYBOARD_CAP_PROPERTY`, `LAYER_KEYBOARD_OVERFLOW_PROPERTY` and
- * `LAYER_KEYBOARD_CLEARANCE_PX`
+ * `LAYER_KEYBOARD_CAP_PROPERTY`, `LAYER_KEYBOARD_OVERFLOW_PROPERTY`,
+ * `LAYER_KEYBOARD_INSET_PROPERTY` and `LAYER_KEYBOARD_CLEARANCE_PX`
* @position Layer runtime, through the layer's touch module: the software
* keyboard's part of the viewport caps
*
@@ -18,6 +18,7 @@
* - /packages/core/src/Layer/settledBox.ts
* - /packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
* - /packages/core/src/Layer/layerViewportInset.stylex.ts
+ * - /packages/core/src/Selector/hooks.ts
* - /docs/specs/AST-059-layer-viewport-inset/spec.md
*/
@@ -61,6 +62,17 @@ export const LAYER_KEYBOARD_CAP_PROPERTY = '--_layer-keyboard-max-block-size';
*/
export const LAYER_KEYBOARD_OVERFLOW_PROPERTY = '--_layer-keyboard-overflow';
+/**
+ * The custom property each layer's style sets beside the cap. Once a software
+ * keyboard is up, it holds how far above the layout viewport's bottom an
+ * anchored layer must end: the keyboard and `LAYER_KEYBOARD_CLEARANCE_PX`. It
+ * keeps its largest value until the layer closes. Otherwise it holds no value.
+ * A layer that places itself, such as Selector's overlay, slides above the
+ * keyboard with it before the cap measures, and stays there.
+ */
+export const LAYER_KEYBOARD_INSET_PROPERTY =
+ '--_layer-keyboard-inset-block-end';
+
/**
* Scrolls the nearest scroll container between `target` and `layer` the
* least amount that shows `target` inside it.
@@ -93,6 +105,12 @@ function keepInView(layer: HTMLElement, target: Element) {
export interface LayerKeyboardClearance {
/** The block size that keeps the layer clear of the keyboard, or null. */
readonly cap: number | null;
+ /**
+ * Once a software keyboard is up, the layout px between the layout
+ * viewport's bottom and the line an anchored layer ends above. It keeps its
+ * largest value until the layer closes. Otherwise null.
+ */
+ readonly inset: number | null;
/**
* Follows a layer element the runtime swaps in while the layer is open.
* The runtime calls it from its layer ref callback.
@@ -114,8 +132,10 @@ export function useLayerKeyboardClearance(
layerRef: RefObject<HTMLElement | null>,
): LayerKeyboardClearance {
const [cap, setCap] = useState<number | null>(null);
+ const [keyboardInset, setKeyboardInset] = useState<number | null>(null);
// The cap the layer renders with, read by the measurement between commits.
const capRef = useRef<number | null>(null);
+ const keyboardInsetRef = useRef<number | null>(null);
// Set while the layer is open: follows the runtime when it replaces the
// layer element without closing it.
const resyncRef = useRef<(() => void) | null>(null);
@@ -149,19 +169,35 @@ export function useLayerKeyboardClearance(
// Renders the layer with `next` and returns once that commit has laid it
// out, so the measurement after it reads the new box. Runs outside
// React's own work: keyboard reports, timers, frames and native events.
- const commitCap = (next: number | null) => {
- if (isDisposed || capRef.current === next) {
+ const commitCap = (
+ next: number | null,
+ nextInset = keyboardInsetRef.current,
+ ) => {
+ if (
+ isDisposed ||
+ (capRef.current === next && keyboardInsetRef.current === nextInset)
+ ) {
return;
}
capRef.current = next;
+ keyboardInsetRef.current = nextInset;
// eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the box is measured at its new size in the same task, before the frame paints
- flushSync(() => setCap(next));
+ flushSync(() => {
+ setCap(next);
+ setKeyboardInset(nextInset);
+ });
sync();
};
// Measured at the layer's own size, as the fallback order places it:
// returns whether the layer is capped.
const capFor = (inset: number): boolean => {
- commitCap(null);
+ // The inset goes out in the commit that lifts the cap. So a layer that
+ // places itself by the inset has moved before its box is read. While
+ // the layer stays open, the inset only grows. A keyboard that goes down
+ // then leaves a layer placed by it where it is.
+ const reported = inset > 0 ? inset + LAYER_KEYBOARD_CLEARANCE_PX : 0;
+ const held = Math.max(reported, keyboardInsetRef.current ?? 0);
+ commitCap(null, held > 0 ? held : null);
if (inset <= 0) {
return false;
}
@@ -198,7 +234,7 @@ export function useLayerKeyboardClearance(
const avoid = (inset: number) => {
sync();
if (!layer.hasAttribute(LAYER_ANCHORED_ATTRIBUTE)) {
- commitCap(null);
+ commitCap(null, null);
return;
}
if (!capFor(inset)) {
@@ -361,11 +397,19 @@ export function useLayerKeyboardClearance(
capRef.current = null;
setCap(null);
}
+ if (keyboardInsetRef.current != null) {
+ keyboardInsetRef.current = null;
+ setKeyboardInset(null);
+ }
};
}, [isOpen, layerRef]);
const followLayerElement = useCallback(() => {
resyncRef.current?.();
}, []);
- return {cap: isOpen ? cap : null, followLayerElement};
+ return {
+ cap: isOpen ? cap : null,
+ inset: isOpen ? keyboardInset : null,
+ followLayerElement,
+ };
}
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 39db61be01..f8cdfe8ed1 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -628,11 +628,17 @@ describe('Selector', () => {
const popover = screen
.getByRole('listbox', {hidden: true})
.closest('[popover]');
+ // The measured shift, or higher by the software keyboard's term. With
+ // no keyboard inset the term falls back to the room below the anchor,
+ // so it is 0 and the shift stands.
await waitFor(() => {
expect(popover?.getAttribute('style')).toContain(
- 'margin-block-start: -110px',
+ '--_selector-overlay-margin: min(-110px, max(-190px, calc(-110px - var(--_layer-keyboard-inset-block-end, -110px))))',
);
});
+ expect(popover?.getAttribute('style')).toContain(
+ 'margin-block-start: var(--_selector-overlay-margin)',
+ );
} finally {
restoreRects();
}
@@ -673,7 +679,7 @@ describe('Selector', () => {
await waitFor(() => {
// 68px geometric alignment plus the 1px optical correction.
expect(popover?.getAttribute('style')).toContain(
- 'margin-block-start: -69px',
+ '--_selector-overlay-margin: min(-69px,',
);
});
} finally {
@@ -826,7 +832,7 @@ describe('Selector', () => {
.closest('[popover]') as HTMLElement;
await waitFor(() => {
expect(popover.getAttribute('style')).toContain(
- 'margin-block-start: -110px',
+ '--_selector-overlay-margin: min(-110px,',
);
});
expect(popover.style.getPropertyValue('--x-marginBlockStart')).toBe('');
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 2a3deb12f5..c53231f57d 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -73,7 +73,7 @@ import {
import type {SelectorOptionType, SelectorOptionData} from './types';
import {isOptionData, isDivider, isSection, normalizeOption} from './utils';
import {getSelectableOptionEntries} from './selectableOptionEntries';
-import {useCombobox, useSelectedItemOffset} from './hooks';
+import {useCombobox, useSelectedItemOverlayMargin} from './hooks';
import {useMenuPress} from '../hooks/useMenuPress';
import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';
import {useTypeahead} from '../hooks/useTypeahead';
@@ -127,6 +127,9 @@ registerEnglishFallback(english);
*/
const MOST_ROWS_THAT_FIT = 12;
+// Private runtime state. No app or theme sets it.
+const OVERLAY_MARGIN_PROPERTY = '--_selector-overlay-margin';
+
const styles = stylex.create({
// Trigger container — the enhanced click target wrapping the combobox button and clear button as siblings
triggerContainer: {
@@ -1453,8 +1456,8 @@ export function Selector<T extends SelectorOptionType>(
// placement opts out of the selector-specific overlay behavior and uses the
// standard layer positioning API instead.
const shouldOverlaySelectedItem = placement == null && !hasSearch;
- const {offset: rawOffset, isPositioned: rawIsPositioned} =
- useSelectedItemOffset({
+ const {marginBlockStart: rawMarginBlockStart, isPositioned: rawIsPositioned} =
+ useSelectedItemOverlayMargin({
isOpen: popover.isOpen && shouldOverlaySelectedItem,
selectedItemIndex,
listboxId,
@@ -1462,13 +1465,21 @@ export function Selector<T extends SelectorOptionType>(
anchorRef,
});
- const selectedItemOffset = shouldOverlaySelectedItem ? rawOffset : 0;
const isPositioned = shouldOverlaySelectedItem ? rawIsPositioned : true;
const popoverPlacement = placement ?? 'below';
+ const overlayMargin =
+ shouldOverlaySelectedItem && rawMarginBlockStart != null
+ ? rawMarginBlockStart
+ : null;
+ const overlayMarginProperty: Record<string, string> =
+ overlayMargin == null ? {} : {[OVERLAY_MARGIN_PROPERTY]: overlayMargin};
const popoverOffsetStyle: React.CSSProperties | undefined =
- selectedItemOffset > 0
- ? {marginBlockStart: `-${selectedItemOffset}px`}
- : undefined;
+ overlayMargin == null
+ ? undefined
+ : {
+ ...overlayMarginProperty,
+ marginBlockStart: `var(${OVERLAY_MARGIN_PROPERTY})`,
+ };
// Clear the current value. Shared by the clear button and the keyboard
// Delete/Backspace path so clearing is reachable without a mouse.
diff --git a/packages/core/src/Selector/__tests__/SelectorKeyboardInset.a11y.chromium.spec.ts b/packages/core/src/Selector/__tests__/SelectorKeyboardInset.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..a0eb2af35b
--- /dev/null
+++ b/packages/core/src/Selector/__tests__/SelectorKeyboardInset.a11y.chromium.spec.ts
@@ -0,0 +1,284 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^(packages/core/src/(Selector|Layer)/|apps/storybook/stories/Selector\.stories)
+
+/**
+ * @file SelectorKeyboardInset.a11y.chromium.spec.ts
+ * @input The Pre Selected story at a phone viewport, its trigger moved low. A
+ * stand-in `window.visualViewport` shrinks from the bottom as a software
+ * keyboard does.
+ * @output Browser proof that the selected-item overlay slides above the
+ * software keyboard. The list ends clear of the keyboard with its rows in
+ * view, whether the keyboard was up before the list opened or rose after.
+ * When the keyboard's report ends, the open list keeps its top: a list the
+ * cap held grows downward in place. A list that slid above a late keyboard
+ * holds against a shorter one.
+ * @position Chromium contract for the Selector overlay beside the keyboard
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+import {LAYER_KEYBOARD_CLEARANCE_PX} from '../../Layer/layerKeyboardClearance';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+const VIEWPORT = {width: 390, height: 844};
+// The keyboard and its bars cover the lower 300 px of the layout viewport.
+const COVER = 300;
+const LIMIT = VIEWPORT.height - COVER - LAYER_KEYBOARD_CLEARANCE_PX;
+
+/**
+ * Replaces `window.visualViewport` before the page loads with one the test
+ * drives: `__keyboard(cover)` shrinks it from the bottom and fires one
+ * `resize`, as Mobile Safari does.
+ */
+async function installKeyboard(page: Page) {
+ await page.addInitScript(() => {
+ Reflect.deleteProperty(Navigator.prototype, 'virtualKeyboard');
+ const viewport = Object.assign(new EventTarget(), {
+ height: window.innerHeight,
+ width: window.innerWidth,
+ offsetTop: 0,
+ offsetLeft: 0,
+ pageTop: 0,
+ pageLeft: 0,
+ scale: 1,
+ });
+ Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ get: () => viewport,
+ });
+ (window as unknown as {__keyboard: (cover: number) => void}).__keyboard =
+ cover => {
+ viewport.height = window.innerHeight - cover;
+ viewport.dispatchEvent(new Event('resize'));
+ };
+ });
+}
+
+const raiseKeyboard = async (page: Page, cover = COVER) =>
+ page.evaluate(
+ value =>
+ (window as unknown as {__keyboard: (cover: number) => void}).__keyboard(
+ value,
+ ),
+ cover,
+ );
+
+/**
+ * Sets the keyboard's cover (0 ends its report) and returns the open list's
+ * top in each of the next 30 frames, read in the page.
+ */
+async function coverAndTrackTop(page: Page, cover = 0): Promise<number[]> {
+ return page.getByRole('listbox').evaluate(async (list, value) => {
+ (window as unknown as {__keyboard: (cover: number) => void}).__keyboard(
+ value,
+ );
+ const tops: number[] = [];
+ for (let frame = 0; frame < 30; frame++) {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ tops.push(list.getBoundingClientRect().top);
+ }
+ return tops;
+ }, cover);
+}
+
+function expectTopHeld(tops: number[], top: number, detail: string) {
+ expect(tops.length, detail).toBeGreaterThan(0);
+ for (const each of tops) {
+ expect(Math.abs(each - top), detail).toBeLessThanOrEqual(0.5);
+ }
+}
+
+/**
+ * Opens the story with its trigger moved down by `drop` px. The centered story
+ * root grows with its content, so it adds twice that height above it.
+ */
+async function openStory(page: Page, drop: number) {
+ await installKeyboard(page);
+ await page.setViewportSize(VIEWPORT);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-selector--pre-selected&viewMode=story`,
+ {waitUntil: 'load'},
+ );
+ const trigger = page.getByRole('combobox').first();
+ await expect(trigger).toBeVisible();
+ await page.evaluate(height => {
+ const block = document.createElement('div');
+ block.style.height = `${height}px`;
+ document.getElementById('storybook-root')?.prepend(block);
+ }, drop * 2);
+ return trigger;
+}
+
+interface ListFacts {
+ top: number;
+ bottom: number;
+ rows: number;
+ rowsWithBox: number;
+ rowsAboveKeyboard: number;
+}
+
+/** Where the open list is, and how many of its rows show above the keyboard. */
+async function listFacts(page: Page): Promise<ListFacts> {
+ return page.getByRole('listbox').evaluate((list, limit) => {
+ const box = list.getBoundingClientRect();
+ const rows = [...list.querySelectorAll('[role="option"]')].map(row =>
+ row.getBoundingClientRect(),
+ );
+ return {
+ top: box.top,
+ bottom: box.bottom,
+ rows: rows.length,
+ rowsWithBox: rows.filter(row => row.height > 0).length,
+ rowsAboveKeyboard: rows.filter(
+ row =>
+ row.height > 0 &&
+ row.top >= Math.max(0, box.top) - 0.5 &&
+ row.bottom <= Math.min(box.bottom, limit) + 0.5,
+ ).length,
+ };
+ }, LIMIT);
+}
+
+// The Pre Selected story's options.
+const OPTIONS = 4;
+
+function expectClearOfKeyboard(facts: ListFacts) {
+ const detail = JSON.stringify({...facts, limit: LIMIT});
+ // The list and each of its options are there, with a box.
+ expect(facts.rows, detail).toBe(OPTIONS);
+ expect(facts.bottom - facts.top, detail).toBeGreaterThan(0);
+ expect(facts.rowsWithBox, detail).toBe(OPTIONS);
+ expect(facts.top, detail).toBeGreaterThanOrEqual(0);
+ expect(facts.bottom, detail).toBeLessThanOrEqual(LIMIT + 0.5);
+ expect(facts.rowsAboveKeyboard, detail).toBe(facts.rows);
+}
+
+// Trigger 496–516 px: the cap alone leaves two rows above the keyboard.
+// Trigger 566–586 px: under the keyboard's line, the list's top just above it.
+// Trigger 606–626 px: the whole list would open under the keyboard.
+for (const drop of [80, 150, 190]) {
+ test(`a list opened with the keyboard up ends above it, trigger ${drop} px lower`, async ({
+ page,
+ }) => {
+ const trigger = await openStory(page, drop);
+ await raiseKeyboard(page);
+ await trigger.click();
+ await expect(page.getByRole('listbox')).toBeVisible();
+ await expect(async () => {
+ expectClearOfKeyboard(await listFacts(page));
+ }).toPass({timeout: 3_000});
+ });
+
+ test(`a list opened with the keyboard up stays where it is when the keyboard's report ends, trigger ${drop} px lower`, async ({
+ page,
+ }) => {
+ const trigger = await openStory(page, drop);
+ await raiseKeyboard(page);
+ await trigger.click();
+ await expect(page.getByRole('listbox')).toBeVisible();
+ await expect(async () => {
+ expectClearOfKeyboard(await listFacts(page));
+ }).toPass({timeout: 3_000});
+ const placed = await listFacts(page);
+ const tops = await coverAndTrackTop(page);
+ const detail = JSON.stringify({placed, tops});
+ expectTopHeld(tops, placed.top, detail);
+ const after = await listFacts(page);
+ expect(after.rows, detail).toBe(OPTIONS);
+ expect(after.rowsWithBox, detail).toBe(OPTIONS);
+ });
+
+ test(`an open list moves above a keyboard that rises, trigger ${drop} px lower`, async ({
+ page,
+ }) => {
+ const trigger = await openStory(page, drop);
+ await trigger.click();
+ await expect(page.getByRole('listbox')).toBeVisible();
+ // Without the keyboard the list overlays the trigger, under the line.
+ const before = await listFacts(page);
+ expect(before.bottom, JSON.stringify(before)).toBeGreaterThan(LIMIT);
+ await raiseKeyboard(page);
+ await expect(async () => {
+ expectClearOfKeyboard(await listFacts(page));
+ }).toPass({timeout: 3_000});
+ });
+
+ test(`a list that slid above a late keyboard holds against a shorter one, trigger ${drop} px lower`, async ({
+ page,
+ }) => {
+ const trigger = await openStory(page, drop);
+ await trigger.click();
+ await expect(page.getByRole('listbox')).toBeVisible();
+ await raiseKeyboard(page);
+ await expect(async () => {
+ expectClearOfKeyboard(await listFacts(page));
+ }).toPass({timeout: 3_000});
+ const placed = await listFacts(page);
+ const tops = await coverAndTrackTop(page, COVER - 100);
+ expectTopHeld(tops, placed.top, JSON.stringify({placed, tops}));
+ });
+}
+
+test('a list the cap holds above the keyboard grows downward in place when the report ends', async ({
+ page,
+}) => {
+ // A 300 px list in a 600 px viewport. The keyboard leaves 210 px above
+ // its line, so the cap holds the list there and it scrolls.
+ const cover = 380;
+ const line = 600 - cover - LAYER_KEYBOARD_CLEARANCE_PX;
+ await installKeyboard(page);
+ await page.setViewportSize({width: 390, height: 600});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-selector--long-list&viewMode=story`,
+ {waitUntil: 'load'},
+ );
+ const trigger = page.getByRole('combobox').first();
+ await expect(trigger).toBeVisible();
+ await raiseKeyboard(page, cover);
+ await trigger.click();
+ const listbox = page.getByRole('listbox');
+ await expect(listbox).toBeVisible();
+ const read = async () =>
+ listbox.evaluate(list => {
+ const box = list.getBoundingClientRect();
+ const finger = [...list.querySelectorAll('[role="option"]')]
+ .map(row => row.getBoundingClientRect())
+ .filter(row => row.height > 0 && row.top >= box.top)[2];
+ return {
+ top: box.top,
+ bottom: box.bottom,
+ fingerTop: finger?.top ?? Number.NaN,
+ };
+ });
+ let held = await read();
+ await expect(async () => {
+ held = await read();
+ expect(held.bottom - held.top, JSON.stringify(held)).toBeGreaterThan(100);
+ expect(held.bottom, JSON.stringify(held)).toBeLessThanOrEqual(line + 0.5);
+ expect(held.fingerTop, JSON.stringify(held)).toBeGreaterThan(held.top);
+ }).toPass({timeout: 3_000});
+ const tops = await coverAndTrackTop(page);
+ const after = await read();
+ const detail = JSON.stringify({held, after, tops});
+ expectTopHeld(tops, held.top, detail);
+ expect(
+ Math.abs(after.fingerTop - held.fingerTop),
+ detail,
+ ).toBeLessThanOrEqual(0.5);
+ expect(after.bottom, detail).toBeGreaterThan(held.bottom + 40);
+});
diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.ts
index 6f7ed9733e..17f465c7cd 100644
--- a/packages/core/src/Selector/hooks.ts
+++ b/packages/core/src/Selector/hooks.ts
@@ -5,10 +5,12 @@
/**
* @file hooks.ts
* @input Uses untransformed DOM layout geometry from the Selector's outer
- * anchor, listbox, and selected option
- * @output Hooks for Selector: useSelectedItemOffset, and useCombobox (public,
- * exported from the Selector entry point; also used by CommandPalette, and
- * by products for a combobox over a text field they render, spec:AST-075)
+ * anchor, listbox, and selected option, and the layer runtime's keyboard
+ * inset
+ * @output Hooks for Selector. useSelectedItemOffset and useCombobox are
+ * public, exported from the Selector entry point. CommandPalette also uses
+ * useCombobox, and so do products with a combobox over their own text field
+ * (spec:AST-075). useSelectedItemOverlayMargin is Selector's own.
* @position Selector hooks; used by Selector.tsx and CommandPalette
*
* SYNC: When useCombobox's options or return change, update:
@@ -18,7 +20,9 @@
import {useCallback, useState} from 'react';
import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {LAYER_KEYBOARD_INSET_PROPERTY} from '../Layer/useLayerKeyboardClearance';
import {isImeKeyEvent} from '../utils/ime';
+import {layoutViewportHeight} from '../utils/layoutViewport';
import type {RefObject} from 'react';
import type {SelectorOptionData} from './types';
@@ -58,6 +62,77 @@ interface UseSelectedItemOffsetResult {
isPositioned: boolean;
}
+interface SelectedItemPlacement {
+ /** The block-start shift, px, from the anchor's bottom to the clamped top. */
+ offset: number;
+ /** The anchor's bottom edge, viewport px. */
+ anchorBottom: number;
+ /** The listbox's layout height, px. */
+ listboxHeight: number;
+}
+
+/**
+ * Measures where the open list goes so that its selected item sits over the
+ * anchor, clamped to the viewport. Returns null when there is nothing to
+ * measure.
+ */
+function measureSelectedItem(
+ listbox: HTMLElement | null,
+ anchor: HTMLElement | null,
+ listboxId: string,
+ selectedItemIndex: number,
+): SelectedItemPlacement | null {
+ if (listbox == null || anchor == null) {
+ return null;
+ }
+
+ // Find the target item: selected item or first item
+ const targetIndex = selectedItemIndex >= 0 ? selectedItemIndex : 0;
+ const targetItemId = `${listboxId}-item-${targetIndex}`;
+ // Use getElementById - works with special characters without escaping
+ const targetItem = document.getElementById(targetItemId);
+
+ if (!targetItem) {
+ return null;
+ }
+
+ const anchorRect = anchor.getBoundingClientRect();
+
+ // offset* metrics intentionally exclude the popover's entry transform.
+ const listboxHeight = listbox.offsetHeight;
+ if (listboxHeight <= 0) {
+ return null;
+ }
+
+ // Item center relative to listbox top. This remains stable even as the
+ // popover animates between scale values. scrollTop keeps the calculation
+ // correct when a previously scrolled listbox is reopened.
+ const itemCenterInListbox =
+ getLayoutTop(targetItem) -
+ getLayoutTop(listbox) -
+ listbox.scrollTop +
+ targetItem.offsetHeight / 2;
+ const anchorCenter = anchorRect.top + anchorRect.height / 2;
+
+ // Desired top aligns the selected item's center with the anchor center.
+ const desiredTop =
+ anchorCenter - itemCenterInListbox - SELECTED_ITEM_OPTICAL_OFFSET;
+ const viewportHeight = window.innerHeight;
+ const maxTop = Math.max(0, viewportHeight - listboxHeight);
+ const clampedTop = Math.min(Math.max(desiredTop, 0), maxTop);
+
+ // useLayer positions the popover below the outer anchor. Apply a negative
+ // block-start margin to the layer container so the listbox top moves from
+ // anchorRect.bottom to clampedTop.
+ const clampedOffset = Math.max(0, anchorRect.bottom - clampedTop);
+
+ return {
+ offset: clampedOffset,
+ anchorBottom: anchorRect.bottom,
+ listboxHeight,
+ };
+}
+
/**
* Calculates the offset needed to position the dropdown so that the selected
* item appears centered over the outer selector control (macOS-style selector).
@@ -94,56 +169,13 @@ export function useSelectedItemOffset({
commitPosition(0, false);
return;
}
-
- if (!listboxRef.current || !anchorRef.current) {
- commitPosition(0, true);
- return;
- }
-
- // Find the target item: selected item or first item
- const targetIndex = selectedItemIndex >= 0 ? selectedItemIndex : 0;
- const targetItemId = `${listboxId}-item-${targetIndex}`;
- // Use getElementById - works with special characters without escaping
- const targetItem = document.getElementById(targetItemId);
-
- if (!targetItem) {
- commitPosition(0, true);
- return;
- }
-
- const listbox = listboxRef.current;
- const anchorRect = anchorRef.current.getBoundingClientRect();
-
- // offset* metrics intentionally exclude the popover's entry transform.
- const listboxHeight = listbox.offsetHeight;
- if (listboxHeight <= 0) {
- commitPosition(0, true);
- return;
- }
-
- // Item center relative to listbox top. This remains stable even as the
- // popover animates between scale values. scrollTop keeps the calculation
- // correct when a previously scrolled listbox is reopened.
- const itemCenterInListbox =
- getLayoutTop(targetItem) -
- getLayoutTop(listbox) -
- listbox.scrollTop +
- targetItem.offsetHeight / 2;
- const anchorCenter = anchorRect.top + anchorRect.height / 2;
-
- // Desired top aligns the selected item's center with the anchor center.
- const desiredTop =
- anchorCenter - itemCenterInListbox - SELECTED_ITEM_OPTICAL_OFFSET;
- const viewportHeight = window.innerHeight;
- const maxTop = Math.max(0, viewportHeight - listboxHeight);
- const clampedTop = Math.min(Math.max(desiredTop, 0), maxTop);
-
- // useLayer positions the popover below the outer anchor. Apply a negative
- // block-start margin to the layer container so the listbox top moves from
- // anchorRect.bottom to clampedTop.
- const clampedOffset = Math.max(0, anchorRect.bottom - clampedTop);
-
- commitPosition(clampedOffset, true);
+ const placement = measureSelectedItem(
+ listboxRef.current,
+ anchorRef.current,
+ listboxId,
+ selectedItemIndex,
+ );
+ commitPosition(placement?.offset ?? 0, true);
}, [
isOpen,
selectedItemIndex,
@@ -156,6 +188,56 @@ export function useSelectedItemOffset({
return {offset, isPositioned};
}
+interface SelectedItemOverlayMargin {
+ marginBlockStart: string | undefined;
+ isPositioned: boolean;
+}
+
+/**
+ * Selector's own overlay margin: `useSelectedItemOffset`'s shift, or more
+ * while a software keyboard is up. The keyboard's part is CSS. The layer
+ * runtime's keyboard inset lifts the list above the keyboard. It does so in
+ * the commit that publishes the inset, before the runtime's cap reads the box.
+ */
+export function useSelectedItemOverlayMargin({
+ isOpen,
+ selectedItemIndex,
+ listboxId,
+ listboxRef,
+ anchorRef,
+}: UseSelectedItemOffsetOptions): SelectedItemOverlayMargin {
+ const [marginBlockStart, setMarginBlockStart] = useState<string>();
+ const [isPositioned, setIsPositioned] = useState(false);
+
+ // Syncs the overlay's margin with the open list's layout: its selected
+ // item, its anchor and the viewport.
+ useIsomorphicLayoutEffect(() => {
+ const placement = isOpen
+ ? measureSelectedItem(
+ listboxRef.current,
+ anchorRef.current,
+ listboxId,
+ selectedItemIndex,
+ )
+ : null;
+ let margin: string | undefined;
+ if (placement != null) {
+ const {offset, anchorBottom, listboxHeight} = placement;
+ // The room below the anchor for the list, in the keyboard inset's
+ // layout px. With no keyboard the inset falls back to the room itself.
+ // The keyboard term is then 0, and the measured shift stands.
+ const room = layoutViewportHeight(window) - listboxHeight - anchorBottom;
+ margin = `min(${-offset}px, max(${-anchorBottom}px, calc(${room}px - var(${LAYER_KEYBOARD_INSET_PROPERTY}, ${room}px))))`;
+ }
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- selector popover position is derived from DOM layout
+ setMarginBlockStart(margin);
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- selector popover position is derived from DOM layout
+ setIsPositioned(isOpen);
+ }, [isOpen, selectedItemIndex, listboxId, listboxRef, anchorRef]);
+
+ return {marginBlockStart, isPositioned};
+}
+
// =============================================================================
// useCombobox - Keyboard navigation and selection
// =============================================================================
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index 790e3d70c7..57bda7a7c5 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -134,6 +134,9 @@ const STRUCTURAL_VARS = new Set([
// Written beside it: `auto` while the keyboard caps the layer, so the
// surface scrolls from that commit. Runtime state, never authored by a theme.
'--_layer-keyboard-overflow',
+ // Also beside it: how far above the viewport's bottom a layer ends while the
+ // keyboard is up. Runtime geometry, never authored by a theme.
+ '--_layer-keyboard-inset-block-end',
]);
/**