An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector): keep the selected-item overlay on screen at the bottom edge (#10697)
Cindy Zhang27378eb5750c
diff --git a/.changeset/selector-overlay-bottom-edge.md b/.changeset/selector-overlay-bottom-edge.mdnew file mode 100644index 0000000000..abd9199e9e--- /dev/null+++ b/.changeset/selector-overlay-bottom-edge.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A Selector whose trigger sits near the bottom of the screen now opens its list on screen. The selected-item overlay's clamp did not count the layer's viewport gutter, so near the bottom edge the browser flipped the list below the viewport and its last options could not be reached.++@cixzhangdiff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex a746e0bd62..f9f383f75c 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -644,6 +644,56 @@ describe('Selector', () => {}});+ it.each([+ ['below its anchor', 'marginBlockEnd'],+ ['already flipped above its anchor', 'marginBlockStart'],+ ])(+ "keeps the overlay out of the layer's viewport gutter, the layer %s",+ async (_, gutterMargin) => {+ const restoreRects = mockSelectorRects();+ // The layer keeps a 16 px gutter from the viewport's block end.+ const realGetComputedStyle = window.getComputedStyle.bind(window);+ const styleSpy = vi+ .spyOn(window, 'getComputedStyle')+ .mockImplementation((element, pseudo) => {+ const style = realGetComputedStyle(element, pseudo);+ if (+ element instanceof HTMLElement &&+ element.hasAttribute('popover')+ ) {+ Object.defineProperty(style, gutterMargin, {value: '16px'});+ }+ return style;+ });+ const user = userEvent.setup();+ try {+ render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ value="Banana"+ onChange={() => {}}+ />,+ );++ await user.click(screen.getByRole('combobox'));+ const popover = screen+ .getByRole('listbox', {hidden: true})+ .closest('[popover]');+ // 16 px higher than without the gutter (110 px), so the list ends at+ // the gutter in the 200 px viewport.+ await waitFor(() => {+ expect(popover?.getAttribute('style')).toContain(+ '--_selector-overlay-margin: min(-126px,',+ );+ });+ } finally {+ styleSpy.mockRestore();+ restoreRects();+ }+ },+ );+it('aligns the selected item using untransformed layout geometry', async () => {const restoreRects = mockSelectorRects({anchor: rect({top: 160, bottom: 192, height: 32}),diff --git a/packages/core/src/Selector/__tests__/SelectorBottomEdge.a11y.chromium.spec.ts b/packages/core/src/Selector/__tests__/SelectorBottomEdge.a11y.chromium.spec.tsnew file mode 100644index 0000000000..7c77cab88b--- /dev/null+++ b/packages/core/src/Selector/__tests__/SelectorBottomEdge.a11y.chromium.spec.ts@@ -0,0 +1,82 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^(packages/core/src/(Selector|Layer|Popover)/|apps/storybook/stories/Selector\.stories)++/**+ * @file SelectorBottomEdge.a11y.chromium.spec.ts+ * @input The Long List story at a 390x844 phone viewport, its trigger moved to+ * the bottom of the screen+ * @output Browser proof that the selected-item overlay stays in the viewport+ * when its clamp engages at the bottom edge: the whole layer, its+ * viewport gutter counted, is on screen and the last option can be reached+ * @position Chromium contract for Selector FR2's viewport clamp+ */++import {expect, test} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => storybook?.close());++const VIEWPORT = {width: 390, height: 844};++for (const triggerTop of [742, 800]) {+ test(`the overlay stays on screen with its trigger at ${triggerTop} px`, async ({+ page,+ }) => {+ await page.setViewportSize(VIEWPORT);+ 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 trigger.evaluate((element, top) => {+ const block = document.createElement('div');+ document.getElementById('storybook-root')?.prepend(block);+ // The story's layout moves the trigger by an uneven part of the+ // spacer's height, so bisect on the height until the trigger is placed.+ let low = 0;+ let high = 4000;+ for (let i = 0; i < 40; i++) {+ const height = (low + high) / 2;+ block.style.height = `${height}px`;+ const current = element.getBoundingClientRect().top;+ if (Math.abs(current - top) < 0.5) {+ break;+ }+ if (current < top) {+ low = height;+ } else {+ high = height;+ }+ }+ }, triggerTop);+ const placed = await trigger.evaluate(+ element => element.getBoundingClientRect().top,+ );+ expect(Math.abs(placed - triggerTop)).toBeLessThan(1);+ await trigger.click();+ const listbox = page.getByRole('listbox');+ await expect(listbox).toBeVisible();+ const layer = await listbox.evaluate(list => {+ const box = (list.closest('[popover]') ?? list).getBoundingClientRect();+ return {top: box.top, bottom: box.bottom};+ });+ const detail = JSON.stringify(layer);+ expect(layer.top, detail).toBeGreaterThanOrEqual(-0.5);+ expect(layer.bottom, detail).toBeLessThanOrEqual(VIEWPORT.height + 0.5);+ // The last option scrolls into view inside the screen.+ const last = listbox.getByRole('option').last();+ await last.scrollIntoViewIfNeeded();+ await expect(last).toBeInViewport();+ });+}diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.tsindex 82798755ac..4e54eb7235 100644--- a/packages/core/src/Selector/hooks.ts+++ b/packages/core/src/Selector/hooks.ts@@ -81,6 +81,7 @@ function measureSelectedItem(anchor: HTMLElement | null,listboxId: string,selectedItemIndex: number,+ {countsLayerGutter = false}: {countsLayerGutter?: boolean} = {},): SelectedItemPlacement | null {if (listbox == null || anchor == null) {return null;@@ -117,8 +118,27 @@ function measureSelectedItem(// Desired top aligns the selected item's center with the anchor center.const desiredTop =anchorCenter - itemCenterInListbox - SELECTED_ITEM_OPTICAL_OFFSET;+ // The layer keeps a gutter from the viewport's block end. A list that+ // reaches into it overflows the layer's room, and the browser then takes a+ // position fallback, which can flip the list off screen. The gutter is the+ // layer's far-edge margin. The browser can flip the layer above its anchor+ // before the overlay margin applies. The flip moves the gutter to the+ // block-start margin. So read the larger of the two margins. A software+ // keyboard's own inset replaces the gutter.+ const layer = countsLayerGutter+ ? listbox.closest<HTMLElement>('[popover]')+ : null;+ let blockEndGutter = 0;+ if (layer != null) {+ const layerStyle = getComputedStyle(layer);+ blockEndGutter = Math.max(+ 0,+ parseFloat(layerStyle.marginBlockStart) || 0,+ parseFloat(layerStyle.marginBlockEnd) || 0,+ );+ }const viewportHeight = window.innerHeight;- const maxTop = Math.max(0, viewportHeight - listboxHeight);+ const maxTop = Math.max(0, viewportHeight - listboxHeight - blockEndGutter);const clampedTop = Math.min(Math.max(desiredTop, 0), maxTop);// useLayer positions the popover below the outer anchor. Apply a negative@@ -218,6 +238,7 @@ export function useSelectedItemOverlayMargin({anchorRef.current,listboxId,selectedItemIndex,+ {countsLayerGutter: true},): null;let margin: string | undefined;