An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector): align selected option during popover entry (#4802)
Ernest060cc9d89265
diff --git a/.changeset/selector-popover-alignment.md b/.changeset/selector-popover-alignment.mdnew file mode 100644index 0000000000..d6d57568a6--- /dev/null+++ b/.changeset/selector-popover-alignment.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Selector: keep the selected option text aligned with the closed trigger across every menu position by measuring untransformed layout geometry during the popover entry animation.+@ernesttdiff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex fb76216f52..bbc2f174ab 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -3,7 +3,7 @@/*** @file Selector.test.tsx* @input Uses vitest, @testing-library/react, @testing-library/user-event- * @output Unit tests for Selector+ * @output Unit tests for Selector behavior and selected-item geometry* @position Tests; validates Selector behavior** SYNC: When Selector.tsx API changes, update these tests.@@ -98,36 +98,103 @@ function rect({};}-function mockSelectorRects() {+function mockSelectorRects({+ anchor = rect({top: 160, bottom: 190, height: 30}),+ trigger = rect({top: 160, bottom: 190, height: 30}),+ listbox = rect({top: 190, bottom: 310, height: 120}),+ selectedItem = rect({top: 220, bottom: 250, height: 30}),+ listboxLayoutHeight = listbox.height,+ selectedItemLayoutTop = selectedItem.top - listbox.top,+ selectedItemLayoutHeight = selectedItem.height,+ viewportHeight = 200,+}: {+ anchor?: DOMRect;+ trigger?: DOMRect;+ listbox?: DOMRect;+ selectedItem?: DOMRect;+ listboxLayoutHeight?: number;+ selectedItemLayoutTop?: number;+ selectedItemLayoutHeight?: number;+ viewportHeight?: number;+} = {}) {const originalGetBoundingClientRect =HTMLElement.prototype.getBoundingClientRect;const originalInnerHeight = Object.getOwnPropertyDescriptor(window,'innerHeight',);+ const originalOffsetTop = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'offsetTop',+ );+ const originalOffsetHeight = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'offsetHeight',+ );HTMLElement.prototype.getBoundingClientRect = function () {+ if (this.classList.contains('astryx-selector')) {+ return anchor;+ }// The trigger is role="combobox" by default, or a plain button with// aria-haspopup="listbox" in hasSearch mode — match either.if (this.getAttribute('role') === 'combobox' ||this.getAttribute('aria-haspopup') === 'listbox') {- return rect({top: 160, bottom: 190, height: 30});+ return trigger;}if (this.getAttribute('role') === 'listbox') {- return rect({top: 190, bottom: 310, height: 120});+ return listbox;}if (this.id.endsWith('-item-1')) {- return rect({top: 220, bottom: 250, height: 30});+ return selectedItem;}return originalGetBoundingClientRect.call(this);};+ Object.defineProperty(HTMLElement.prototype, 'offsetTop', {+ configurable: true,+ get() {+ if (this.getAttribute('role') === 'listbox') {+ return 0;+ }+ if (this.id.endsWith('-item-1')) {+ return selectedItemLayoutTop;+ }+ return 0;+ },+ });+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {+ configurable: true,+ get() {+ if (this.getAttribute('role') === 'listbox') {+ return listboxLayoutHeight;+ }+ if (this.id.endsWith('-item-1')) {+ return selectedItemLayoutHeight;+ }+ return 0;+ },+ });Object.defineProperty(window, 'innerHeight', {- value: 200,+ value: viewportHeight,configurable: true,});return () => {HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect;+ if (originalOffsetTop) {+ Object.defineProperty(+ HTMLElement.prototype,+ 'offsetTop',+ originalOffsetTop,+ );+ }+ if (originalOffsetHeight) {+ Object.defineProperty(+ HTMLElement.prototype,+ 'offsetHeight',+ originalOffsetHeight,+ );+ }if (originalInnerHeight) {Object.defineProperty(window, 'innerHeight', originalInnerHeight);}@@ -265,6 +332,81 @@ describe('Selector', () => {}});+ it('aligns the selected item using untransformed layout geometry', async () => {+ const restoreRects = mockSelectorRects({+ anchor: rect({top: 160, bottom: 192, height: 32}),+ trigger: rect({top: 166, bottom: 186, height: 20}),+ // Simulate the 0.95 entry scale in visual rects while retaining the+ // untransformed 120px list / 36px item offset used for positioning.+ listbox: rect({top: 190, bottom: 304, height: 114}),+ selectedItem: rect({+ top: 224.2,+ bottom: 254.6,+ height: 30.4,+ }),+ listboxLayoutHeight: 120,+ selectedItemLayoutTop: 36,+ selectedItemLayoutHeight: 32,+ viewportHeight: 900,+ });+ 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]');+ await waitFor(() => {+ // 68px geometric alignment plus the 1px optical correction.+ expect(popover?.getAttribute('style')).toContain(+ 'margin-block-start: -69px',+ );+ });+ } finally {+ restoreRects();+ }+ });++ it('adds the border inset only to input-variant dropdowns', async () => {+ const user = userEvent.setup();+ const {unmount} = render(+ <Selector+ label="Input fruit"+ options={OPTIONS}+ value="Banana"+ onChange={() => {}}+ />,+ );++ await user.click(screen.getByRole('combobox'));+ const inputDropdownClass = screen.getByRole('listbox', h).className;+ unmount();++ render(+ <Selector+ label="Ghost fruit"+ options={OPTIONS}+ value="Banana"+ variant="ghost"+ onChange={() => {}}+ />,+ );+ await user.click(screen.getByRole('combobox'));+ const ghostDropdownClass = screen.getByRole('listbox', h).className;++ // The bordered input gets one extra StyleX rule for its border-width+ // correction; the borderless ghost keeps the base menu inset.+ expect(inputDropdownClass).not.toBe(ghostDropdownClass);+ });+it('does not apply selected-item overlay offset when placement is explicit', async () => {const restoreRects = mockSelectorRects();const user = userEvent.setup();diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex ce73eb54a7..c1d703db2b 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -4,7 +4,8 @@/*** @file Selector.tsx- * @input Uses React, StyleX, usePopover, useTooltip, Icon, InputGroupContext+ * @input Uses React, StyleX, usePopover, useTooltip, Icon, InputGroupContext,+ * and Selector positioning hooks* @output Exports Selector component* @position Core implementation; consumed by index.ts*@@ -238,10 +239,16 @@ const styles = stylex.create({boxSizing: 'border-box',maxHeight: '300px',overflowY: 'auto',- padding: spacingVars['--spacing-1'],+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-1'],opacity: 1,transition: `opacity ${durationVars['--duration-fast']}`,},+ dropdownInput: {+ // The input trigger's text inset includes its border. Mirror that extra+ // pixel in the menu; the borderless ghost variant needs no correction.+ paddingInline: `calc(${spacingVars['--spacing-1']} + ${borderVars['--border-width']})`,+ },dropdownHidden: {opacity: 0,transition: 'none',@@ -703,6 +710,9 @@ export function Selector<T extends SelectorOptionType>(const statusMessageId = useId();const inputLabelId = useId();const searchId = useId();+ // Measure from the same outer control that usePopover anchors to; using the+ // shorter inner button makes every size's selected row land too low.+ const anchorRef = useRef<HTMLDivElement>(null);const triggerRef = useRef<HTMLButtonElement>(null);const searchRef = useRef<HTMLInputElement>(null);const inputGroup = useInputGroup();@@ -840,7 +850,7 @@ export function Selector<T extends SelectorOptionType>(selectedItemIndex,listboxId,listboxRef,- triggerRef,+ anchorRef,});const selectedItemOffset = shouldOverlaySelectedItem ? rawOffset : 0;@@ -1160,6 +1170,7 @@ export function Selector<T extends SelectorOptionType>(<><divref={el => {+ anchorRef.current = el;popover.triggerRef(el);// Anchor + hover/focus listeners for the disabled-message tooltip.// Handlers are gated internally by isEnabled, and anchor names@@ -1319,7 +1330,10 @@ export function Selector<T extends SelectorOptionType>(id={listboxId}role="listbox"aria-labelledby={triggerId}- {...stylex.props(styles.dropdown)}>+ {...stylex.props(+ styles.dropdown,+ variant !== 'ghost' && styles.dropdownInput,+ )}>{renderOptions()}</div></div>@@ -1331,6 +1345,7 @@ export function Selector<T extends SelectorOptionType>(aria-labelledby={triggerId}{...stylex.props(styles.dropdown,+ variant !== 'ghost' && styles.dropdownInput,!isPositioned && styles.dropdownHidden,)}>{renderOptions()}diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.tsindex 247ba8779a..c5aab582fe 100644--- a/packages/core/src/Selector/hooks.ts+++ b/packages/core/src/Selector/hooks.ts@@ -4,6 +4,8 @@/*** @file hooks.ts+ * @input Uses untransformed DOM layout geometry from the Selector's outer+ * anchor, listbox, and selected option* @output Hooks for Selector* @position Internal hooks; used by Selector.tsx*/@@ -13,6 +15,25 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import type {RefObject} from 'react';import type {SelectorOptionData} from './types';+// The selected row renders one optical pixel below the closed trigger label at+// the same mathematical center, so compensate before viewport clamping.+const SELECTED_ITEM_OPTICAL_OFFSET = 1;++/**+ * Return an element's document-relative layout top without CSS transforms.+ * getBoundingClientRect includes the popover's entry scale, which would make+ * the measured error grow with each option's distance from the menu top.+ */+function getLayoutTop(element: HTMLElement): number {+ let top = 0;+ let current: HTMLElement | null = element;+ while (current) {+ top += current.offsetTop;+ current = current.offsetParent as HTMLElement | null;+ }+ return top;+}+// =============================================================================// useSelectedItemOffset - Position dropdown to center selected item over trigger// =============================================================================@@ -22,7 +43,7 @@ interface UseSelectedItemOffsetOptions {selectedItemIndex: number;listboxId: string;listboxRef: RefObject<HTMLDivElement | null>;- triggerRef: RefObject<HTMLButtonElement | null>;+ anchorRef: RefObject<HTMLElement | null>;}interface UseSelectedItemOffsetResult {@@ -32,9 +53,9 @@ interface UseSelectedItemOffsetResult {/*** Calculates the offset needed to position the dropdown so that the selected- * item appears centered over the trigger button (macOS-style selector).+ * item appears centered over the outer selector control (macOS-style selector).*- * The desired dropdown top is calculated directly from the trigger center and+ * The desired dropdown top is calculated directly from the anchor center and* selected-item center, then clamped to the viewport. This preserves the* default "selected item over trigger" behavior while letting the menu slide* upward near the bottom edge or downward near the top edge instead of being@@ -45,7 +66,7 @@ export function useSelectedItemOffset({selectedItemIndex,listboxId,listboxRef,- triggerRef,+ anchorRef,}: UseSelectedItemOffsetOptions): UseSelectedItemOffsetResult {const [offset, setOffset] = useState(0);const [isPositioned, setIsPositioned] = useState(false);@@ -67,7 +88,7 @@ export function useSelectedItemOffset({return;}- if (!listboxRef.current || !triggerRef.current) {+ if (!listboxRef.current || !anchorRef.current) {commitPosition(0, true);return;}@@ -83,34 +104,37 @@ export function useSelectedItemOffset({return;}- // Get positions. JSDOM returns zero rects by default, but browsers provide- // real dimensions before paint via layout effect.- const listboxRect = listboxRef.current.getBoundingClientRect();- const itemRect = targetItem.getBoundingClientRect();- const triggerRect = triggerRef.current.getBoundingClientRect();+ const listbox = listboxRef.current;+ const anchorRect = anchorRef.current.getBoundingClientRect();- const listboxHeight = listboxRect.height;+ // 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's top changes between measurements.+ // popover animates between scale values. scrollTop keeps the calculation+ // correct when a previously scrolled listbox is reopened.const itemCenterInListbox =- itemRect.top - listboxRect.top + itemRect.height / 2;- const triggerCenter = triggerRect.top + triggerRect.height / 2;-- // Desired top aligns the selected item's center with trigger center.- const desiredTop = triggerCenter - 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 trigger. Apply a negative+ // useLayer positions the popover below the outer anchor. Apply a negative// block-start margin to the layer container so the listbox top moves from- // triggerRect.bottom to clampedTop.- const clampedOffset = Math.max(0, triggerRect.bottom - clampedTop);+ // anchorRect.bottom to clampedTop.+ const clampedOffset = Math.max(0, anchorRect.bottom - clampedTop);commitPosition(clampedOffset, true);}, [@@ -118,7 +142,7 @@ export function useSelectedItemOffset({selectedItemIndex,listboxId,listboxRef,- triggerRef,+ anchorRef,commitPosition,]);