Skip to content

Commit 13b8981

Browse files
authored
fix(Selector): the selected row stays on the trigger as the list grows (#10062)
* chore(core): the layer runtime's exit copy, for a touch presentation's close placeLayerExitCopy puts a static, inert copy of a closing layer where the layer was drawn, in the top layer, for a touch presentation's close to play on: the browser hides a popover the moment it closes. The copy keeps the layer's box, transform, presented look, overflow and scroll positions; has no ids, anchor names, form names or form owner; is inert and hidden from assistive technology; and its descendants' keyframe animations and transitions do not start again. A refused show during the closing toggle waits, hidden, until the toggle is over. A layer inside other layers gets its copy after the outermost one, with what it inherited there (its color scheme included), so a close that takes the layers around it too still draws the copy. That copy is shown again above the copy the same close then places for a layer around it. A layer has one copy. The layer-runtime record states it, and that the presentation plays its exit on the copy (AST-094 FR7). Core's shared inertCopy now takes every copied native control and form-associated custom element out of any form with form="", as its documentation says, so the swap's copies join no form either. It also sets anchor-name: none on each copied element that has an anchor name, so no live anchor gets a second element. * feat(Layer): one input hold, first used by Dialog, Drawer and MobileNav (spec:AST-094 FR35) Layer/inputHold holds a layer's pointer input while its presentation enters or leaves. holdInput(layer, {until, scope}) raises a shield: 'viewport' over the whole viewport while a modal layer enters; 'surface' over the layer's own box while a non-modal one enters, the page around it live; 'layer' over the viewport, its content inert, while a layer leaves. It decides by each event's pointer (a finger's or a pen's press is held to its end; a mouse passes once it moves with no button down, or from the start when the page last heard a mouse, DEC-16), never cancels a touch's start, and cancels a one-finger move so a pinch still zooms (FR10). It hears input through Core's shared input stream before every other subscriber, and ends the dispatch for a held event, so press feedback and the gesture host never hear it; the stream gains first subscribers and records the type of the latest pointer event it delivers (getLastPointerType). The gesture host asks the hold for each touch (holdsTouch), so the hold imports nothing from gestures/ and a component in the root entry may use it statically (architecture:react-component-runtime INV13). Its first users hold only under a coarse primary pointer, a touch presentation (FR13): Dialog, Drawer and MobileNav hold a finger's tap or drag while they enter (holdEntranceInput, which reads the entrance's own animations; MobileNav's slide-in is capped at 550 ms), a non-modal Drawer only on its panel. Under a fine primary pointer nothing is held and nothing listens (FR24). Where the primary pointer is fine and the screen also takes touch, a finger is not held yet; AST-094's current-state impact and Drawer's record name that gap. AST-094's current-state impact also names the first press of a still mouse after a finger, which lands on an entering presentation's shield. AlertDialog renders Dialog, so its entrance is held too: its record says FR7 ships in part, the leaving alert's inert content waiting for FR6's dismissal. Every browser proof lands its input at an exact point (an entrance held where it is, the page's clock, or an exact step of a drag) and plays once. The WebKit interaction lane's scope includes Layer/inputHold.ts: the gesture host imports it, so the gesture specs' fixture bundles it. MobileNav's record states what the rest of the slide-out after the close does: it is inert, taking no input and hidden from assistive technology (FR5). A browser case proves both against the open drawer. From #8342 and its per-event offer, #8630 (Dialog and Drawer) and #8374 (MobileNav). Co-authored-by: Cindy Zhang <cindyxz@meta.com> * feat(Popover): under a finger, it grows out of its trigger and shrinks back into it Under a coarse primary pointer, Popover grows out of its trigger on the theme's entrance duration and easing and shrinks back into it on the theme's exit duration and easing, on the layer runtime's exit copy. A fine primary pointer keeps the layer's own entrance. * test(Popover): browser proofs of the touch presentation's grow and shrink Real-browser proofs, in Chromium and WebKit, that under a finger Popover grows out of its trigger on the theme's entrance tokens and shrinks back on its exit tokens, keeps advancing through a blocked main thread, does no Layout or Paint per frame, and cross-fades under Reduce Motion, with storyboards of both. * Merge #8342 fbe71df (the shared input hold) into the Popover touch presentation (#9823), as #8223's base * fix(Popover): under a finger, a tap during the presentation is ignored, as on iOS While the popover grows out of its trigger under a coarse primary pointer, the layer runtime's input hold takes every touch. A tap outside neither dismisses it nor reaches what is under it, a pan scrolls nothing, and a pinch still zooms the page. * perf(Popover): the touch presentation starts in the next frame Opening a popover under a finger ran the touch presentation in the opening task. The animator's style writes and the box reads laid the anchored page out more often than a mouse opening does, and on a loaded machine that task could pass the 50 ms long-task line. The opening task now reads and writes nothing while it runs. As it ends, after its own reads, the layer's CSS entrance goes off, a write that costs it no layout. A style read after that task then starts no entrance. The presentation waits for the next animation frame, which runs before it paints. There it puts the element invisible at its full size, reads the boxes, starts the curves and takes the input hold. A close before that frame cancels it and leaves the element as the component styles it, with no compositing layer. A presentation again during a dismissal still starts at once, since it reads nothing. Without animation frames, the presentation runs at once and a close plays the shrink. Popover's record notes, under Current-state impact, that the input hold starts on the first frame after the open, so a touch landing within that frame reaches the page. * chore(core): the layer runtime's exit copy, for a touch presentation's close placeLayerExitCopy puts a static, inert copy of a closing layer where the layer was drawn, in the top layer, for a touch presentation's close to play on: the browser hides a popover the moment it closes. The copy keeps the layer's box, transform, presented look, overflow and scroll positions; has no ids, anchor names, form names or form owner; is inert and hidden from assistive technology; and its descendants' keyframe animations and transitions do not start again. A refused show during the closing toggle waits, hidden, until the toggle is over. A layer inside other layers gets its copy after the outermost one, with what it inherited there (its color scheme included), so a close that takes the layers around it too still draws the copy. That copy is shown again above the copy the same close then places for a layer around it. A layer has one copy. The layer-runtime record states it, and that the presentation plays its exit on the copy (AST-094 FR7). Core's shared inertCopy now takes every copied native control and form-associated custom element out of any form with form="", as its documentation says, so the swap's copies join no form either. It also sets anchor-name: none on each copied element that has an anchor name, so no live anchor gets a second element. * Merge branch 'main' into uikit/c26-layer-exit-copy * feat(Popover): under a finger, it grows out of its trigger and shrinks back into it Under a coarse primary pointer, Popover grows out of its trigger on the theme duration step nearest iOS's growth (`--duration-medium-min`) and the theme's entrance easing, and shrinks back into it on the theme's exit duration and easing, on the layer runtime's exit copy. A fine primary pointer keeps the layer's own entrance. * test(Popover): browser proofs of the touch presentation's grow and shrink Real-browser proofs, in Chromium and WebKit, that under a finger Popover grows out of its trigger on the theme's entrance tokens and shrinks back on its exit tokens, keeps advancing through a blocked main thread, does no Layout or Paint per frame, and cross-fades under Reduce Motion, with storyboards of both. * Merge the updated #9823 into the Popover presentation hold (tree matches the lane's intended resolution) * Merge the updated #8223 into the Popover next-frame presentation (frame scheduling kept, createMotionEngine) * Merge branch 'main' into uikit/c26-layer-exit-copy * Merge the updated lower stack branch into uikit/c26-popover-present (own diff unchanged) * Merge the updated lower stack branch into uikit/c27-popover-present-proofs (own diff unchanged) * Merge the updated lower stack branch into uikit/c26-popover-presentation-hold (own diff unchanged) * Merge the updated lower stack branch into uikit/c26-popover-present-next-frame (own diff unchanged) * Merge #8187's input hold into the Popover touch proofs * feat(Popover): a touch during the growth is ignored While the popover grows, the layer runtime's input hold takes every touch, as UIKit ignores touches while it presents a popover. A tap outside does not dismiss it and reaches nothing under it, and a pinch still zooms the page. This folds in the hold that #8223 carried, so the growth and its hold land together. * test(Popover): browser proofs of the hold while the popover grows A tap outside, a tap on the trigger and a pan while the popover grows do nothing, a pinch still zooms, and a storyboard shows the growth going on under a tap outside. Folded from #8223. * docs(AST-094): Popover's input hold starts on the frame after the open AST-094's current-state line for Popover now states the window its Popover record already states: the input hold starts on the first frame after the open, so a touch that lands within that frame reaches the page. Starting the hold at the open would lay the page out twice in the opening task. Two comments now say that the layer's CSS entrance goes off in a microtask, once the script that opened the popover returns. * fix(core): the exit copy keeps no closed layer The exit copy found the inner layers to raise through a module-level set of every copied layer. A layer React removed on close stayed reachable there until a later close showed a copy. The inner layers are inside the closing layer, so they are now found there, and nothing keeps a layer once it is gone. Chromium 150 and later refuse a show during another popover's toggle, so the copy can open in the next frame. The browser spec's light-dismiss case now reads the copy after a frame, as its nested-close cases do. The cap check's comment now names only the copy cap. * docs(core): the exit copy's JSDoc states the empty-canvas rule once The empty-canvas rule stays in the first paragraph, and the inert-copy paragraph no longer repeats it or `inertCopy`'s own contract. * Merge the updated lower stack branch into uikit/c26-popover-present (own diff unchanged) * Merge the updated lower stack branch into uikit/c27-popover-present-proofs (own diff unchanged) * Merge the folded #9823 into the Popover next-frame presentation (#8223 absorbed into #8187) * test(Popover): time the rendering proof from each motion's start The growth now starts in a frame callback. Where the compositor starts it in that frame, its animation starts at the frame's time, before the animate() call the logger stamped. The presentation's window then ended less than 20 ms before the growth did, and it could reach the one-off work at the growth's end. The logger now records each call and the animation's own start time. A wait still finds its animation by the call, which always follows the key press, and times its window from the start. * test(Popover): the blocked-main-thread proof blocks from the page and asserts the verdict The page now starts the block once the growth has run a frame, and the proof asserts the harness verdict, which fails a judged part under 4 frames. Here the growth runs 600 ms at a constant speed, so each frame moves several pixels and a block that starts late on a loaded machine still lands inside it. * Merge the updated lower stack branch into uikit/c26-popover-present-next-frame (own diff unchanged) * fix(Selector): the overlay clamps in layout, so the keyboard cap and every reader of the layer's box see it The selected-item overlay realized its viewport clamp as a negative margin on the anchored layer, which anchor positioning's fit check swallowed, so a list opened near the viewport's end lay past it. A translate instead hid the clamp from every layout reader: the software keyboard's cap read the layer's untransformed box, and a same-size move painted a stale frame. The overlay's layer now takes no position fallbacks (an internal layer option, off by default) and clamps in layout: `inset-block-start` places the selected row's center on the anchor's center between the viewport's gutters, and `inset-inline-start` starts the layer at its anchor's own start inside the inline gutters, from three private variables the Selector sets (the row's offset in the list, and the layer's block and inline sizes). A move or a scroll re-places the list in the same layout, so no frame paints a stale place; content and selection re-measure on the layer's resettle watcher and commit synchronously. Tests: every overlay case asserts a usable list (at least two rows in full view, or every row), the move case asserts no stale painted frame, the keyboard case asserts two rows above the keyboard line, and a cross-engine spec checks the clamp in Chromium and WebKit in both directions, a list wider than its trigger and a list taller than the room included. A story places a Selector near the viewport's end beside a text input. * refactor(Selector): drop the overlay layer that never flips The owners ruled that every anchored placement can flip, so the overlay layer's internal no-fallback option, its layer-runtime paragraph and the Selector FR2 rewrite go. This restores every file of this change to its base. On main, the layer's end gutter already keeps the list inside the viewport. * Merge main * fix(Selector): the selected row stays on the trigger as options grow The selected-item overlay measured its margin once, when the list opened. An option that grew above the selection while the list was open left the row off the trigger, and a list near the viewport's end grew past it. The browser then flipped the layer above its anchor, where the margin moved the list the wrong way. The overlay now measures again when the open listbox resizes, through the shared resize observer, and commits before the frame paints. On a layer flipped above its anchor, the margin sets the same clamped top from the anchor's top. * fix(Selector): read the overlay's flip safely, skip the first report An engine with the Popover API but no CSS anchor positioning has no positionArea on its computed style, so the overlay threw on every open there. It now reads getPropertyValue('position-area'), which gives an empty string in such an engine. observeResize reports once at registration, inside the commit that opens the list, where React cannot flush and warns. That report is now skipped, since the measuring Effect already runs in that commit. A list at its height cap does not resize when an option grows, so the changeset now claims the fix only for a list shorter than its cap. * test(Selector): drop a stray comment and an unused helper parameter The growth spec carried a doc comment that documented no declaration, and a prepare parameter on openPreSelected that no case passed. Both go, and no proof changes. * docs(Selector): say plainly why the first resize report is skipped The comment on the open list's resize observation ended in the passive "so it is skipped". It now leads with the action and keeps the reason. * Merge main * refactor(Selector): observe the open list with observeResizeAfterLayout The shared resize observer now has observeResizeAfterLayout (#9810). It observes an element without the report observeResize makes when it registers. The open list's observer skipped that report by hand, so it now uses the helper, as useTruncation does. No other shared-observer subscriber watches the list, so the helper's microtask report never runs, and the list behaves as before. * Merge main * fix(Selector): keep a flipped list above the software keyboard The margin for a list the browser flipped above its trigger had no keyboard term. Beside a field near the viewport's end, the list stayed under a software keyboard. The flipped margin now keeps the list's end above the keyboard, and its top on screen. That margin applies only where it would not also fit below the anchor. Where it would, the browser moves the layer back below, and a flipped margin there would squeeze the list. There the overlay keeps main's margin. Two SelectorKeyboardInset cases fix the field 8 px above the viewport's end, with the keyboard up before the open and rising while the list is open. A story sets a field 300 px above the screen's end for a phone check, and a browser spec pins it beside a 291 px keyboard. * fix(Selector): shrink a tall list above the software keyboard A list taller than the room above a software keyboard, beside a field near the viewport's end, stayed under the keyboard. The flipped margin stopped the list's top at 0, with no room for the layer's gutter. So the browser dropped that position, and the runtime caps no layer above its trigger. At the open, the overlay now always takes the margin below the anchor, as main does. That margin fits below the anchor, so the browser opens the layer there, and the runtime caps it above a keyboard. Only a layer that the browser flips while the list is open gets the flipped margin, because the browser keeps that side. Its top stays below the gutter. Two SelectorKeyboardInset cases open the nine-option story at 844x390 beside a 200 px keyboard, up before the open and rising while the list is open. * fix(Selector): read the layer's gutter from the margin it keeps The overlay read the layer's gutter as the larger of its two block margins. A flip swaps them, so that read could take the overlay's own margin: with a keyboard up, 270 px. A flipped list that grew again then stopped at that floor, past the keyboard's line. The gutter is now the margin that the overlay does not set: the block-end margin below the anchor, and the block-start margin above it. The unit case for a flipped layer's gutter now also names the flip in the layer's position area. A SelectorKeyboardInset case flips the list with a grown option, raises a keyboard, and grows another option. * Merge main * test(Selector): raise the keyboard story's trigger above Safari's bars With the keyboard up, an iPhone tap on a trigger just above Safari's bottom bars closed the keyboard and opened nothing, and the keyboard story's trigger sat there. The story now lays out its Selector as Overlay Beside Keyboard does, so its trigger sits at the same height. The browser spec now fixes the field 300 px above the viewport's end itself, so it still pins the same case. * Merge main * Merge main * Merge main * docs(Selector): record the Android landscape evidence gap FR2's verification row now names the case no emulator scene can set up: Android landscape with the keyboard up leaves 67 px visible and 40 px of scroll, at this head and on main alike.
1 parent 86b0733 commit 13b8981

8 files changed

Lines changed: 826 additions & 20 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[fix] When an option grows while a `Selector`'s list is open, and the list is shorter than its height cap, the selected row stays on the trigger. The selected-item overlay measured its place only when the list opened, so a row that grew above the selection left it off the trigger, and a list near the viewport's end grew past it. The overlay now measures again when the open list resizes, before that frame paints. No API changes.
6+
7+
@vjeux

‎apps/storybook/stories/Selector.stories.tsx‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1137,6 +1137,50 @@ export const OverlayBesideKeyboard: Story = {
11371137
},
11381138
};
11391139

1140+
/**
1141+
* Overlay Beside Keyboard with nine options, so the open list must rise to
1142+
* end above a software keyboard. On a phone, focus the field so that its
1143+
* keyboard rises, then open the Selector. The list ends above the keyboard.
1144+
* The trigger sits where Overlay Beside Keyboard's does. On an iPhone with the
1145+
* keyboard up, a tap on a trigger just above Safari's bottom bars closed the
1146+
* keyboard and opened nothing.
1147+
*/
1148+
export const FlippedOverlayBesideKeyboard: Story = {
1149+
parameters: {layout: 'fullscreen'},
1150+
render: () => {
1151+
const [name, setName] = useState('');
1152+
const [value, setValue] = useState<string | undefined>('Banana');
1153+
return (
1154+
<div
1155+
style={{
1156+
display: 'flex',
1157+
flexDirection: 'column',
1158+
gap: 16,
1159+
padding: '96px 24px 0',
1160+
}}>
1161+
<TextInput label="Name" value={name} onChange={setName} />
1162+
<div style={{height: 64}} />
1163+
<Selector
1164+
label="Fruit"
1165+
options={[
1166+
'Apple',
1167+
'Banana',
1168+
'Cherry',
1169+
'Date',
1170+
'Elderberry',
1171+
'Fig',
1172+
'Grape',
1173+
'Honeydew',
1174+
'Kiwi',
1175+
]}
1176+
value={value}
1177+
onChange={v => setValue(v)}
1178+
/>
1179+
</div>
1180+
);
1181+
},
1182+
};
1183+
11401184
// All variations
11411185
export const AllVariations: Story = {
11421186
render: () => {

‎docs/specs/components/Selector/Selector.spec.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ new theming target.
358358
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
359359
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
360360
| 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` |
361-
| 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` |
361+
| FR2 | placement and selected-item geometry tests; `SelectorKeyboardInset.a11y.chromium.spec.ts`; Android landscape with the keyboard up not evidenced: the emulator scene leaves 67 px visible and 40 px of scroll, so the case can't be set up; the same at main | default, explicit, RTL, transformed entry, keyboard up | Using the wrong positioning model fails the expected position-area or margin | `audit:Selector/behavior` |
362362
| 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` |
363363
| 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` |
364364
| 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` |

‎packages/core/src/Selector/Selector.test.tsx‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -646,13 +646,19 @@ describe('Selector', () => {
646646
});
647647

648648
it.each([
649-
['below its anchor', 'marginBlockEnd'],
650-
['already flipped above its anchor', 'marginBlockStart'],
649+
['below its anchor', 'marginBlockEnd', null],
650+
[
651+
'already flipped above its anchor',
652+
'marginBlockStart',
653+
'self-block-start span-self-inline-end',
654+
],
651655
])(
652656
"keeps the overlay out of the layer's viewport gutter, the layer %s",
653-
async (_, gutterMargin) => {
657+
async (_, gutterMargin, flippedArea) => {
654658
const restoreRects = mockSelectorRects();
655-
// The layer keeps a 16 px gutter from the viewport's block end.
659+
// The layer keeps a 16 px gutter from the viewport's block end. A flip
660+
// moves it to the block-start margin and names the block-start side in
661+
// the layer's position area.
656662
const realGetComputedStyle = window.getComputedStyle.bind(window);
657663
const styleSpy = vi
658664
.spyOn(window, 'getComputedStyle')
@@ -663,6 +669,13 @@ describe('Selector', () => {
663669
element.hasAttribute('popover')
664670
) {
665671
Object.defineProperty(style, gutterMargin, {value: '16px'});
672+
if (flippedArea != null) {
673+
const read = style.getPropertyValue.bind(style);
674+
Object.defineProperty(style, 'getPropertyValue', {
675+
value: (name: string) =>
676+
name === 'position-area' ? flippedArea : read(name),
677+
});
678+
}
666679
}
667680
return style;
668681
});
@@ -864,6 +877,29 @@ describe('Selector', () => {
864877
});
865878
});
866879

880+
it('opens the selected-item overlay without a flush inside its commit', async () => {
881+
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
882+
try {
883+
const user = userEvent.setup();
884+
render(
885+
<Selector
886+
label="Fruit"
887+
options={OPTIONS}
888+
value="Banana"
889+
onChange={() => {}}
890+
/>,
891+
);
892+
893+
await user.click(screen.getByRole('combobox'));
894+
await screen.findByRole('listbox', {hidden: true});
895+
// The list's resize report at registration runs inside the open's
896+
// commit, where React cannot flush and warns.
897+
expect(error.mock.calls.flat().join(' ')).not.toContain('flushSync');
898+
} finally {
899+
error.mockRestore();
900+
}
901+
});
902+
867903
it('stays flush in the default selected-item overlay', async () => {
868904
const restoreRects = mockSelectorRects();
869905
const user = userEvent.setup();
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
// @pr-a11y scope ^(packages/core/src/(Selector|Layer)/|apps/storybook/stories/Selector\.stories)
3+
4+
/**
5+
* @file SelectorFlippedOverlayKeyboard.a11y.browser.spec.ts
6+
* @input The Flipped Overlay Beside Keyboard story at a phone viewport, its
7+
* Selector's field fixed 300 px above the viewport's end. A stand-in
8+
* `window.visualViewport` shrinks from the bottom as a 291 px software
9+
* keyboard does.
10+
* @output Browser proof that the list opens above the keyboard at its height
11+
* without one, on either side of its field.
12+
* @position Chromium and WebKit contract for the Selector overlay beside the
13+
* keyboard, on the story a phone check uses
14+
*/
15+
16+
import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
17+
import {
18+
DEFAULT_STORYBOOK_DIR,
19+
serveStorybook,
20+
type StaticServer,
21+
} from '@astryxdesign/a11y-spec/storybook';
22+
import {LAYER_KEYBOARD_CLEARANCE_PX} from '../../Layer/layerKeyboardClearance';
23+
24+
let storybook: StaticServer;
25+
26+
test.beforeAll(async () => {
27+
storybook = await serveStorybook(
28+
process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
29+
);
30+
});
31+
32+
test.afterAll(async () => {
33+
await storybook?.close();
34+
});
35+
36+
const VIEWPORT = {width: 390, height: 844};
37+
// An iPhone's software keyboard with its predictive bar off.
38+
const COVER = 291;
39+
const LIMIT = VIEWPORT.height - COVER - LAYER_KEYBOARD_CLEARANCE_PX;
40+
41+
/**
42+
* Replaces `window.visualViewport` before the page loads with one the test
43+
* drives: `__keyboard(cover)` shrinks it from the bottom and fires one
44+
* `resize`, as Mobile Safari does.
45+
*/
46+
async function installKeyboard(page: Page) {
47+
await page.addInitScript(() => {
48+
Reflect.deleteProperty(Navigator.prototype, 'virtualKeyboard');
49+
const viewport = Object.assign(new EventTarget(), {
50+
height: window.innerHeight,
51+
width: window.innerWidth,
52+
offsetTop: 0,
53+
offsetLeft: 0,
54+
pageTop: 0,
55+
pageLeft: 0,
56+
scale: 1,
57+
});
58+
Object.defineProperty(window, 'visualViewport', {
59+
configurable: true,
60+
get: () => viewport,
61+
});
62+
(window as unknown as {__keyboard: (cover: number) => void}).__keyboard =
63+
cover => {
64+
viewport.height = window.innerHeight - cover;
65+
viewport.dispatchEvent(new Event('resize'));
66+
};
67+
});
68+
}
69+
70+
/** The open list's box, and its layout height, which no transform scales. */
71+
async function listBox(page: Page) {
72+
return page.getByRole('listbox').evaluate(list => {
73+
const box = list.getBoundingClientRect();
74+
return {
75+
top: box.top,
76+
bottom: box.bottom,
77+
height: (list as HTMLElement).offsetHeight,
78+
};
79+
});
80+
}
81+
82+
test('a list beside a field 300 px above the end opens above a 291 px keyboard at its full height', async ({
83+
page,
84+
}) => {
85+
await installKeyboard(page);
86+
await page.setViewportSize(VIEWPORT);
87+
await page.goto(
88+
`${storybook.origin}/iframe.html?id=core-selector--flipped-overlay-beside-keyboard&viewMode=story`,
89+
{waitUntil: 'load'},
90+
);
91+
const trigger = page.getByRole('combobox');
92+
// The field, fixed 300 px above the viewport's end. The list is taller than
93+
// the room below the field, so the browser can flip it above.
94+
const field = await trigger.evaluate(combobox => {
95+
const box = combobox.closest<HTMLElement>('.astryx-selector');
96+
if (box == null) {
97+
throw new Error('the Selector field must be in the document');
98+
}
99+
box.style.position = 'fixed';
100+
box.style.insetInline = '24px';
101+
box.style.insetBlockStart = 'auto';
102+
box.style.insetBlockEnd = '300px';
103+
return box.getBoundingClientRect().bottom;
104+
});
105+
expect(VIEWPORT.height - field).toBeCloseTo(300, 0);
106+
// Without the keyboard, the list's height.
107+
await trigger.click();
108+
await expect(page.getByRole('listbox')).toBeVisible();
109+
const full = (await listBox(page)).height;
110+
await page.keyboard.press('Escape');
111+
await expect(page.getByRole('listbox')).toBeHidden();
112+
// The keyboard rises, then the list opens.
113+
await page.evaluate(
114+
cover =>
115+
(window as unknown as {__keyboard: (cover: number) => void}).__keyboard(
116+
cover,
117+
),
118+
COVER,
119+
);
120+
await trigger.click();
121+
await expect(page.getByRole('listbox')).toBeVisible();
122+
await expect(async () => {
123+
const box = await listBox(page);
124+
const detail = JSON.stringify({...box, full, limit: LIMIT});
125+
expect(box.top, detail).toBeGreaterThanOrEqual(0);
126+
expect(box.bottom, detail).toBeLessThanOrEqual(LIMIT + 0.5);
127+
expect(box.height, detail).toBe(full);
128+
}).toPass({timeout: 3_000});
129+
});

0 commit comments

Comments
 (0)