Skip to content

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

TypeScript

[Component Audit] ComplexSelector: the trigger is a combobox field on both paths (#6991)

Cindy Zhange52ef25f28bb
diff --git a/.changeset/complex-selector-combobox-trigger.md b/.changeset/complex-selector-combobox-trigger.md
new file mode 100644
index 0000000000..cb04c13945
--- /dev/null
+++ b/.changeset/complex-selector-combobox-trigger.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] ComplexSelector: the trigger is now a combobox whose popup is a dialog, so a screen reader hears when the field is required (`aria-required` was ignored on the old button role). With `renderTrigger`, the caller's control receives the same `role`, `aria-required`, and `aria-disabled`, is named by `label` unless the selector is given `aria-label` or `aria-labelledby`, and a disabled control keeps its tab stop but does not open. Button keeps a caller-supplied `aria-disabled` and `aria-busy`, so a Button used as that control carries the selector's state. Tests that find the trigger with `getByRole('button')` should use `getByRole('combobox')`.
+
+@cixzhang
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 83538e8373..33da6f1b06 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -3402,6 +3402,37 @@ jobs:
retention-days: 30
if-no-files-found: error
+ # ComplexSelector's whole-component audit grades the rendered state matrix,
+ # caller-rendered trigger anchor/focus behavior, RTL, and 320px reflow from
+ # exact-head Chromium receipts. Keep this with the existing pr-a11y owner.
+ - name: Run ComplexSelector audit browser evidence
+ if: ${{ !cancelled() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ComplexSelector:') }}
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ status=0
+ node .github/scripts/accessibility-audit.js \
+ --storybook-dir apps/storybook/dist \
+ --output complex-selector-a11y-report.json \
+ --components ComplexSelector \
+ --baseline .github/a11y-baseline.json \
+ --fail-on-new || status=1
+ pnpm exec playwright test \
+ packages/core/src/ComplexSelector/__tests__/ComplexSelector.a11y.chromium.spec.ts \
+ --project chromium || status=1
+ exit "$status"
+
+ - name: Upload ComplexSelector audit evidence
+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ComplexSelector:')
+ uses: actions/upload-artifact@v7
+ with:
+ name: complex-selector-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: |
+ complex-selector-a11y-report.json
+ test-results/complex-selector-audit-evidence/
+ retention-days: 30
+ if-no-files-found: error
+
# ContextMenuItem opens from a pointer gesture after the trigger renders.
# The focused selector wait binds axe to the open menu rather than letting
# the trigger's first frame satisfy generic Storybook readiness.
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index fad0dee4de..80230ac139 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -469,6 +469,18 @@
"overlayRoot": "[role=\"combobox\"]"
}
},
+ {
+ "component": "ComplexSelector",
+ "storyId": "core-complexselector--controlled-toolbar-trigger",
+ "dims": ["D4"],
+ "setup": {
+ "click": "button[aria-haspopup=\"dialog\"]"
+ },
+ "selectors": {
+ "overlay": ".astryx-complex-selector-popup",
+ "overlayRoot": "button[aria-haspopup=\"dialog\"]"
+ }
+ },
{
"component": "SideNav",
"storyId": "core-sidenav--default",
diff --git a/apps/storybook/stories/ComplexSelector.stories.tsx b/apps/storybook/stories/ComplexSelector.stories.tsx
index dfb8d7c696..ebd43779e3 100644
--- a/apps/storybook/stories/ComplexSelector.stories.tsx
+++ b/apps/storybook/stories/ComplexSelector.stories.tsx
@@ -409,6 +409,12 @@ const styles = stylex.create({
width: 280,
padding: spacingVars['--spacing-3'],
},
+ auditMatrix: {
+ width: 'min(720px, calc(100vw - 32px))',
+ },
+ auditPopupContent: {
+ width: 220,
+ },
});
function formatFruitValue(value: FruitValue) {
@@ -832,7 +838,7 @@ export const SecondaryVariant: Story = {
const widthBefore = root.getBoundingClientRect().width;
expect(widthBefore).toBeCloseTo(190, 0);
- const trigger = canvas.getByRole('button', {name: 'View density'});
+ const trigger = canvas.getByRole('combobox', {name: 'View density'});
await userEvent.click(trigger);
const dialog = within(document.body).getByRole('dialog', {
name: 'View density',
@@ -924,3 +930,99 @@ export const ControlledToolbarTrigger: Story = {
},
},
};
+
+export const AuditMatrix: Story = {
+ name: 'Audit matrix',
+ tags: ['no-visual'],
+ render: () => {
+ const content = () => <Button label="Apply selection" size="sm" />;
+
+ return (
+ <VStack gap={4} xstyle={styles.auditMatrix} data-testid="audit-matrix">
+ <ComplexSelector label="Empty small" value="" size="sm">
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Selected medium"
+ value="Design systems"
+ triggerLabel="Design systems"
+ data-testid="rtl-trigger">
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Long large"
+ value="A long selected destination"
+ triggerLabel="A long selected destination that must truncate without widening the field"
+ size="lg">
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Ghost trigger"
+ value="Compact"
+ triggerLabel="Compact"
+ variant="ghost"
+ startIcon="viewColumns">
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Loading value"
+ value="Saving"
+ triggerLabel="Saving destination"
+ isLoading>
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Disabled value"
+ value="Unavailable"
+ triggerLabel="Unavailable"
+ isDisabled>
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Invalid required value"
+ value="Needs attention"
+ triggerLabel="Needs attention"
+ isRequired
+ status={{type: 'error', message: 'Choose an available destination.'}}>
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Warning value"
+ value="Draft destination"
+ triggerLabel="Draft destination"
+ status={{type: 'warning', message: 'This destination is archived.'}}>
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Successful value"
+ value="Ready"
+ triggerLabel="Ready"
+ status={{type: 'success', message: 'Destination is available.'}}>
+ {content}
+ </ComplexSelector>
+ <ComplexSelector
+ label="Custom trigger selector"
+ value="Custom"
+ contentXstyle={styles.auditPopupContent}
+ renderTrigger={props => (
+ <Button
+ data-testid="rtl-custom-trigger"
+ label="Custom trigger"
+ variant="secondary"
+ {...props}
+ />
+ )}>
+ {content}
+ </ComplexSelector>
+ </VStack>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A bounded audit fixture for the built-in sizes, variants, busy, disabled, validation, overflow, and caller-rendered trigger paths. Browser evidence drives this one fixture through light, dark, RTL, interaction, and 320px states.',
+ },
+ },
+ },
+};
diff --git a/packages/core/src/Button/Button.test.tsx b/packages/core/src/Button/Button.test.tsx
index 964d185ac4..7013e4ee3e 100644
--- a/packages/core/src/Button/Button.test.tsx
+++ b/packages/core/src/Button/Button.test.tsx
@@ -149,6 +149,13 @@ describe('Button', () => {
expect(button.className).toContain('styles.disabled');
});
+ it('keeps a caller-supplied aria-disabled and aria-busy', () => {
+ render(<Button label="Assign" aria-disabled="true" aria-busy={true} />);
+ const button = screen.getByRole('button', {name: 'Assign'});
+ expect(button).toHaveAttribute('aria-disabled', 'true');
+ expect(button).toHaveAttribute('aria-busy', 'true');
+ });
+
it('sets aria-busy synchronously while clickAction is pending', async () => {
// The spinner reveal is visually delayed (CSS animation-delay), but the
// loading DOM state — aria-busy and aria-disabled — must not be delayed.
diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx
index 7b7ab1ab2f..301bec0d98 100644
--- a/packages/core/src/Button/Button.tsx
+++ b/packages/core/src/Button/Button.tsx
@@ -838,8 +838,10 @@ export function Button({
{...ariaLabelProp}
{...describedByProp}
{...edgeCompAttr}
- aria-busy={isLoadingState || undefined}
- aria-disabled={useAriaDisabled || undefined}
+ // A caller's own busy or disabled state is kept, so a component that
+ // hands these props to a Button (a caller-rendered trigger) is heard.
+ aria-busy={isLoadingState || props['aria-busy'] || undefined}
+ aria-disabled={useAriaDisabled || props['aria-disabled'] || undefined}
onClick={handleClick}
{...(handleKeyDown ? {onKeyDown: handleKeyDown} : null)}>
{buttonContent}
@@ -857,8 +859,10 @@ export function Button({
{...ariaLabelProp}
{...describedByProp}
{...edgeCompAttr}
- aria-busy={isLoadingState || undefined}
- aria-disabled={useAriaDisabled || undefined}
+ // A caller's own busy or disabled state is kept, so a component that
+ // hands these props to a Button (a caller-rendered trigger) is heard.
+ aria-busy={isLoadingState || props['aria-busy'] || undefined}
+ aria-disabled={useAriaDisabled || props['aria-disabled'] || undefined}
onClick={handleClick}
{...(handleKeyDown ? {onKeyDown: handleKeyDown} : null)}>
{buttonContent}
diff --git a/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs b/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs
index 39ebf344ea..9f3c050b00 100644
--- a/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs
+++ b/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs
@@ -189,7 +189,7 @@ export const docs = {
name: 'renderTrigger',
type: '(props: ComplexSelectorRenderTriggerProps) => ReactNode',
description:
- "Render the control the popup hangs off — a glyph in a list row, a chip, an icon button — instead of the selector's own field and button. Spread the given props ({ref, id, onClick, onKeyDown, aria-haspopup, aria-expanded, aria-controls, aria-busy}) onto it; the popup is anchored to that control and still labelled by `label`. The field chrome is not rendered. Pair with handleRef to open from a keystroke elsewhere.",
+ "Render the control the popup hangs off — a glyph in a list row, a chip, an icon button — instead of the selector's own field and button. Spread the given props ({ref, id, onClick, onKeyDown, role, aria-haspopup, aria-expanded, aria-controls, aria-busy, aria-required, aria-disabled}) onto it: the control becomes the selector's combobox field, the popup is anchored to it and still labelled by `label`, and a disabled control keeps its tab stop but does not open. The field chrome is not rendered. Pair with handleRef to open from a keystroke elsewhere.",
},
{
name: 'handleRef',
diff --git a/packages/core/src/ComplexSelector/ComplexSelector.focusableDisabled.test.tsx b/packages/core/src/ComplexSelector/ComplexSelector.focusableDisabled.test.tsx
index 8ac2ec8171..c518b5daa9 100644
--- a/packages/core/src/ComplexSelector/ComplexSelector.focusableDisabled.test.tsx
+++ b/packages/core/src/ComplexSelector/ComplexSelector.focusableDisabled.test.tsx
@@ -28,7 +28,7 @@ function Harness(props: {
);
}
-const trigger = () => screen.getByRole('button', {name: 'View options'});
+const trigger = () => screen.getByRole('combobox', {name: 'View options'});
describe('ComplexSelector disabled (spec:AST-085)', () => {
it('FR1: renders no native disabled and keeps its tab stop', async () => {
diff --git a/packages/core/src/ComplexSelector/ComplexSelector.fr10.test.tsx b/packages/core/src/ComplexSelector/ComplexSelector.fr10.test.tsx
index 15520133fe..3d543eb7f4 100644
--- a/packages/core/src/ComplexSelector/ComplexSelector.fr10.test.tsx
+++ b/packages/core/src/ComplexSelector/ComplexSelector.fr10.test.tsx
@@ -45,7 +45,7 @@ describeFieldInputParts('ComplexSelector', {
{content}
</ComplexSelector>
),
- getControl: () => screen.getByRole('button', {name: 'Fruit'}),
+ getControl: () => screen.getByRole('combobox', {name: 'Fruit'}),
// No shipped InputGroup support (family:input-fields adoption table).
inGroup: false,
});
@@ -64,7 +64,7 @@ describe('ComplexSelector FR10 targets', () => {
);
const ids = (
screen
- .getByRole('button', {name: 'Fruit'})
+ .getByRole('combobox', {name: 'Fruit'})
.getAttribute('aria-describedby') ?? ''
).split(' ');
expect(ids).toContain('caller-help');
@@ -84,7 +84,7 @@ describe('ComplexSelector FR10 targets', () => {
{content}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'Fruit'});
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
const controlBox = document.querySelector('.fr10-control') as HTMLElement;
expect(controlBox).toHaveClass('astryx-complex-selector');
expect(controlBox).toContainElement(trigger);
@@ -114,7 +114,7 @@ describe('ComplexSelector FR10 targets', () => {
{content}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'Fruit'});
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
fireEvent.click(trigger);
expect(targets).toEqual([trigger]);
expect(trigger).toHaveAttribute('aria-expanded', 'false');
@@ -135,7 +135,7 @@ describe('ComplexSelector FR10 targets', () => {
{content}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'Fruit'});
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
fireEvent.click(trigger);
expect(onClick).toHaveBeenCalledTimes(1);
expect(trigger).toHaveAttribute('aria-expanded', 'true');
@@ -153,7 +153,7 @@ describe('ComplexSelector FR10 targets', () => {
);
const controlBox = container.querySelector('.fr10-control') as HTMLElement;
fireEvent.click(controlBox);
- expect(screen.getByRole('button', {name: 'Fruit'})).toHaveAttribute(
+ expect(screen.getByRole('combobox', {name: 'Fruit'})).toHaveAttribute(
'aria-expanded',
'true',
);
@@ -174,7 +174,7 @@ describe('ComplexSelector FR10 targets', () => {
{content}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'Fruit'});
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
fireEvent.keyDown(trigger, {key: 'ArrowDown'});
expect(trigger).toHaveAttribute('aria-expanded', 'true');
// The caller still sees the ArrowDown the trigger used to open the popup.
@@ -199,7 +199,7 @@ describe('ComplexSelector FR10 renderTrigger', () => {
{content}
</ComplexSelector>,
);
- const opener = screen.getByRole('button', {name: 'Open'});
+ const opener = screen.getByRole('combobox', {name: 'Fruit'});
fireEvent.click(opener);
expect(opener).toHaveAttribute('aria-expanded', 'true');
});
@@ -224,7 +224,7 @@ describe('ComplexSelector FR10 renderTrigger', () => {
{content}
</ComplexSelector>,
);
- const opener = screen.getByRole('button', {name: 'Open'});
+ const opener = screen.getByRole('combobox', {name: 'Fruit'});
expect(opener).toHaveAttribute('data-testid', 'opener');
expect(opener).toHaveAttribute('aria-details', 'details-id');
expect(ref.current).toBe(opener);
diff --git a/packages/core/src/ComplexSelector/ComplexSelector.spec.md b/packages/core/src/ComplexSelector/ComplexSelector.spec.md
index 547adc643d..8954e1a863 100644
--- a/packages/core/src/ComplexSelector/ComplexSelector.spec.md
+++ b/packages/core/src/ComplexSelector/ComplexSelector.spec.md
@@ -1,6 +1,6 @@
---
schema_version: 3
-template_version: 3
+template_version: 7
kind: component
id: component:ComplexSelector
authority: draft
@@ -9,10 +9,13 @@ superseded_by: null
approved_by: null
approved_at: null
owners: [cixzhang]
-review_triggers: [theming]
+review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/core/src/ComplexSelector/ComplexSelector.test.tsx,
+ packages/core/src/ComplexSelector/__tests__/ComplexSelector.a11y.chromium.spec.ts,
+ apps/storybook/stories/ComplexSelector.stories.tsx,
+ apps/storybook/rtl-audit/targets.json,
packages/core/src/Field/Field.test.tsx,
packages/core/src/Icon/Icon.test.tsx,
scripts/check-knowledge.mjs,
@@ -21,29 +24,46 @@ modules: []
families: [family:input-fields, family:overlay-dismissal]
design_specs: []
architecture:
- [architecture:component-theming-surface, architecture:layer-runtime]
+ [
+ architecture:public-component-api,
+ architecture:component-theming-surface,
+ architecture:layer-runtime,
+ ]
contributing: []
-system_specs: [spec:AST-079/DEC-1]
+system_specs: [spec:AST-055, spec:AST-079/DEC-1, spec:AST-085]
---
# ComplexSelector component contract
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | The trigger plays the combobox role on both paths (DEC-1), and `ComplexSelectorRenderTriggerProps` carries `role`, `aria-label`, `aria-required`, and `aria-disabled` beside its existing ref, id, handlers, and popup props. Current source exports one controlled rich-selector shell, its public props and supporting types, an imperative handle, a content render function, an optional `renderTrigger` seam governed by `spec:AST-055`, and named `container*`/`control*` styling targets in place of root styling props. |
+| Behavior | The built-in path composes Field, one combobox trigger whose popup is a dialog, an indicator, and a mounted dialog popup. The caller-rendered path replaces the Field and built-in trigger chrome with one unwrapped caller control that carries the same combobox role and state, while ComplexSelector keeps anchoring, open state, popup wiring, focus return, and the popup. |
+| End-user impact | People selecting through rich custom content receive one named combobox trigger that announces required, busy, and disabled state (and invalid state on the built-in trigger), keyboard and pointer opening, focus restoration, and a popup that remains reachable across logical placement and viewport direction. |
+| Builder impact | Builders provide controlled value plus custom dialog content. They may use the built-in field trigger, call the imperative handle, or spread one exported trigger-props object onto a caller-rendered control, which then becomes the selector's combobox field. Test code that finds the trigger with `getByRole('button')` uses `getByRole('combobox')`. |
+| Compatibility/readiness | The built-in Field composition is preserved when `renderTrigger` is absent, and the trigger plays the combobox role on both paths (DEC-1). Caller-rendered mode is additive and implemented under current `spec:AST-055`. This record stays a draft until an owner approves it. |
+| Review checks | Reject a second or wrapped interactive trigger, a trigger role other than combobox, ARIA the combobox role does not support, missing popup or disabled state, lost focus return, a popup anchored to a different box or outside the inline viewport, suppressed BaseProps, physical-direction placement, or a status that loses its semantic message. |
+| Governing rules | `spec:AST-055/FR1–FR7, AR1–AR4`; `architecture:public-component-api/INV1, INV3, INV5–INV9`; `family:input-fields/FR1–FR8, FR10`; `spec:AST-085/FR1, FR2, FR4`; `spec:AST-079/DEC-1`; `family:overlay-dismissal`; `architecture:component-theming-surface`; `architecture:layer-runtime`. |
+
+This table is a review projection; the body below is authoritative.
+
## Intent
-ComplexSelector renders a field-owned shell, an owned trigger, and a dialog
-popup for caller-provided rich selection content. This draft records current
-consumer anatomy and theming ownership without changing runtime behavior,
-styling, targets, or public API.
+ComplexSelector is a controlled selector shell for choices whose accessible
+interaction structure is richer than a single list of options. It owns the
+field trigger or caller-rendered anchor, dialog popup, open and close lifecycle,
+focus return, optimistic value handoff, and shared field semantics. The caller
+owns the accessible structure and selection interaction rendered inside the
+popup.
## Compatibility and migration
-- Released default preserved: `yes`
-- Compatibility class: additive. `renderTrigger` is absent by default; when omitted,
- runtime, DOM, styling, targets, and public API remain unchanged. With
- `renderTrigger`, the caller-rendered control replaces the Field shell, Trigger, and
- Indicator icon by the caller's choice.
-- Controlled/uncontrolled behavior: unchanged
-- Migration decision: none
+- Released default preserved: `no`; the trigger's role is combobox
+- Compatibility class: accessibility correction; omitting `renderTrigger` preserves the built-in Field, DOM structure, targets, and interaction
+- Controlled/uncontrolled behavior: controlled only; the caller owns `value`, while ComplexSelector supplies the committing helper
+- Migration decision: test code that finds the trigger with `getByRole('button')` uses `getByRole('combobox')`; no runtime migration
Consumer migration instructions belong in consumer docs and release notes.
@@ -51,93 +71,124 @@ Consumer migration instructions belong in consumer docs and release notes.
**Owns**
-- The trigger and its current `complex-selector` target.
-- The trailing indicator icon and its current
- `complex-selector-indicator-icon` target.
-- The painted popup surface and its current `complex-selector-popup` target.
+- The built-in Field composition, one combobox trigger, loading and disclosure end controls, and the current `complex-selector` target.
+- Popup visibility, the anchor relationship, logical placement and alignment, focus return, and `onOpenChange` notification.
+- The optimistic value and busy state exposed to caller-provided content while `changeAction` is pending.
+- The `renderTrigger` integration local to ComplexSelector: dialog naming, click and ArrowDown opening, focus return, and the current handed-back props object.
+- The trailing indicator and popup surfaces exposed by the current `complex-selector-indicator-icon` and `complex-selector-popup` targets.
**Does not own / non-goals**
-- Field-shell presentation — rendered by Field and themed through Field's
- current `field` target.
-- General Icon presentation — rendered by Icon for semantic icon names and icon
- component types and themed through Icon's current `icon` target.
-- Arbitrary ReactNode content supplied through `startIcon` — rendered directly
- and owned by the product callsite.
-- The selector-specific structure supplied through `children` — owned by the
- product callsite.
-- Shared layer lifecycle, positioning, and dismissal behavior.
+- The accessible role, keyboard model, and selection behavior inside `children` — owned by the product callsite and the primitives it composes.
+- Shared Field label, description, requirement, validation, and status rendering — owned by `component:Field` and `family:input-fields`.
+- General Icon rendering for semantic names and icon component types — owned by `component:Icon`.
+- Arbitrary ReactNode content supplied through `startIcon` — owned by the product callsite.
+- Shared layer hosting, positioning, native light dismissal, and Escape ordering — owned by `architecture:layer-runtime` and `family:overlay-dismissal`.
+- The cross-component caller-rendered-trigger API grammar — owned by `spec:AST-055`.
## Public concepts
-One additive concept: anchored mode, selected by the `renderTrigger` render prop
-(absent by default). The prop's name, shape, and open-state documentation are
-governed by [`spec:AST-055`](../../../../docs/specs/AST-055-caller-rendered-trigger/spec.md);
-this record covers only what is local to `ComplexSelector`. The caller renders the control the popup hangs off and
-spreads the given props (`ref`, `id`, `onClick`, `onKeyDown`, `aria-haspopup`,
-`aria-expanded`, `aria-controls`, `aria-busy`) onto it. Consumer props and usage
-remain documented in `ComplexSelector.doc.mjs`.
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ----------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------- |
+| controlled selection | caller value; optimistic candidate value | Current value passed to `children`; commits call `onChange` and optional `changeAction` | all paths | caller's `value` | `component:ComplexSelector` | stable | no uncontrolled fallback |
+| content render state | open/closed; idle/busy; trigger id; content id | Lets caller content observe shell state without owning visibility | all paths | closed and idle | `component:ComplexSelector` | stable | current shell state is supplied on every render |
+| trigger ownership | built-in; caller-rendered | Chooses whether ComplexSelector renders Field/combobox chrome or renders one caller control unwrapped | caller-rendered when `renderTrigger` is present | built-in | `spec:AST-055` | stable | caller-rendered path wins; built-in chrome is absent |
+| built-in variant | `input`; `secondary`; `ghost` | Bordered field, secondary-button, or ghost-button trigger representation | built-in path only | `input` | `component:ComplexSelector` | stable | unsupported values are rejected by TypeScript |
+| built-in size | `sm`; `md`; `lg` | Resolves trigger height through shared element-size tokens | built-in path only | `md` | `component:ComplexSelector` | stable | unsupported values are rejected by TypeScript |
+| start content | absent; semantic icon name; icon component type; arbitrary ReactNode | Optional leading trigger content | built-in path only | absent | `component:ComplexSelector` | stable | icon-capable values delegate to Icon; arbitrary content renders directly |
+| field metadata | visible/hidden label; description absent/present; optional/required/neither; tooltip | Supplies built-in Field naming and supporting information | built-in path; required state also reaches a caller-rendered control | visible label; neither required | `family:input-fields` | stable | `isRequired` and `isOptional` resolve to one required state on the combobox |
+| availability | enabled; disabled | Disabled blocks click, ArrowDown, and imperative opening | `aria-disabled` with a kept tab stop on both paths | enabled | `component:ComplexSelector` | stable | disabled guards every opening route and press on both paths |
+| busy | idle; external loading; pending Action | Exposes `aria-busy`, a built-in Spinner, and `isBusy` to content | Spinner only on built-in path; state remains available to content | idle | `family:input-fields` | stable | external and transition busy resolve to one state |
+| validation | absent; warning; error; success | Supplies Field status; error also exposes invalid state on the built-in trigger | built-in path only | absent | `family:input-fields` | stable | unsupported values are rejected by TypeScript |
+| status placement | `attached`; `detached`; `tooltip` | Chooses Field status presentation | built-in path only; secondary and ghost map attached to detached | `attached` for input; `detached` for secondary and ghost | `family:input-fields` | stable | a secondary or ghost attached request resolves to detached |
+| popup placement | `above`; `below`; `start`; `end` | Logical side where the popup is requested | all paths; layer runtime may choose a fallback | `below` | `architecture:layer-runtime` | stable | unsupported values are rejected by TypeScript |
+| popup alignment | `start`; `center`; `end` | Logical alignment along the placement axis | all paths | `start` | `architecture:layer-runtime` | stable | unsupported values are rejected by TypeScript |
+| visibility control | trigger actions; content `close`; imperative `open`/`close`/`toggle`; observation callback | Keeps one component-owned visibility state and reports every transition | all paths | closed | `component:ComplexSelector` | stable | disabled guards opening; closing an already closed popup is a no-op |
+| caller DOM/style inputs | inherited BaseProps supplied or omitted; `container*` and `control*` part styles | DOM, data, ARIA, and event inputs accepted by ComplexSelector, plus named part styling | BaseProps reach the primary semantic control on both paths; part styles apply on the built-in path | omitted | `family:input-fields` | stable | root `xstyle`/`className`/`style` are a type error; part styles under `renderTrigger` have no effect and warn in development |
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | -------------------------------------------------- |
-| FR1 | The current render contains a Field, Trigger, Indicator icon, and mounted Popup; one optional start slot may contain either an Icon-rendered start icon or caller-rendered start content. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | Trigger, Indicator icon, and Popup carry `complex-selector`, `complex-selector-indicator-icon`, and `complex-selector-popup`, respectively. | Current source, docs, and tests | Verified current behavior; no target change |
-| FR3 | Field delegates to Field's `field` target, and a semantic name or icon component in the start slot delegates to Icon's `icon` target. | Current source and owner tests | Verified current behavior; no target change |
-| FR4 | Arbitrary ReactNode start content renders directly and carries no ComplexSelector-owned target. | Current source | Verified current behavior; no target change |
-| FR5 | With `renderTrigger`, the caller-rendered control is the popup's anchor and focus-return target, carries `aria-haspopup="dialog"`, `aria-expanded`, and `aria-controls` for the Popup, and opens it on click or ArrowDown; no Field, Trigger, or Indicator icon renders. `handleRef` and `onOpenChange` behave as without a trigger. | DEC-1, docs, and tests | Proposed; awaiting owner approval |
+Draft requirements identify their basis so observed code is not mistaken for an
+intentional decision. A `current` contract contains no unresolved rows.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
+| FR1 | ComplexSelector MUST remain controlled: `children` receives the current or optimistic value, a committing helper, a closing helper, and live shell state; the committing helper calls `onChange` before an optional `changeAction`. | Current source, tests, `family:input-fields/FR6` | Verified current behavior |
+| FR2 | The built-in path MUST render Field, one combobox trigger whose popup is a dialog, an optional start slot, a disclosure/loading end area, and one mounted popup. The popup is hidden while closed and shown while open. | Current source, docs, tests, `architecture:layer-runtime` | Verified current behavior |
+| FR3 | The built-in trigger MUST resolve `sm`, `md`, and `lg` from shared element-size tokens. Input, secondary, and ghost variants MUST preserve the same open, close, value, busy, and popup behavior. | Current source, docs, tests, `family:input-fields` | Verified current behavior |
+| FR4 | Built-in Field metadata MUST name and describe the combobox trigger and preserve description, status, validation, and requirement semantics; required state reaches the trigger as `aria-required`, which the combobox role supports. | Current source, Field contract, DEC-1, WCAG 2.2 4.1.2 | Verified current behavior |
+| FR5 | Explicit disabled MUST expose `aria-disabled` on the trigger, built-in or caller-rendered, while it keeps its tab stop, and MUST make click, ArrowDown, imperative `open`, and imperative `toggle` no-ops; a press on a disabled trigger reaches no handler. | Current source, tests, `spec:AST-085/FR1, FR2, FR4` | Verified current behavior |
+| FR6 | External `isLoading` or a pending `changeAction` MUST resolve to one busy state. The built-in path renders one decorative Spinner, exposes `aria-busy`, and announces the busy start once; caller content receives `isBusy`; caller-rendered mode receives current `aria-busy`. | Current source, docs, tests, `family:input-fields/FR5–FR6` | Verified current behavior |
+| FR7 | Warning, error, and success MUST delegate to Field status. Error MUST expose `aria-invalid` on the built-in trigger. Secondary and ghost with requested attached status MUST resolve to detached status. | Current source, tests, `family:input-fields/FR8` | Verified current behavior |
+| FR8 | Trigger click toggles the popup; ArrowDown opens a closed popup; content and the imperative handle can close it; every open/close route reports through `onOpenChange`; closing returns focus to the current trigger. | Current source, tests, `family:overlay-dismissal` | Verified current behavior |
+| FR9 | Placement and alignment MUST remain logical. The popup MUST anchor to the current trigger and keep content reachable through the current layer-runtime fallback and scroll behavior. | Current source, RTL target, browser test, layer architecture, WCAG 2.2 1.4.10 | Verification requires passing logical RTL placement and exact-head 320px browser receipts |
+| FR10 | With `renderTrigger`, the caller control MUST render unwrapped as the only opener, replace Field and built-in chrome, and carry the exported ref, handlers, combobox role, popup props (`aria-haspopup="dialog"`, `aria-expanded`, `aria-controls`), name, busy, required, and disabled state, plus the caller's inherited BaseProps. It anchors the popup, receives focus return, and preserves the same content, handle, and open-change behavior. | `spec:AST-055/FR1–FR7, AR1–AR4`, DEC-1, current source and tests | Verified current behavior |
+| FR11 | The trigger MUST play the combobox role on both paths so every emitted ARIA state is supported, and accepted BaseProps plus component availability state MUST NOT disappear silently when trigger ownership changes. | DEC-1, `architecture:public-component-api/INV3, INV5–INV7`, WCAG 2.2 4.1.2 | Verified current behavior |
+| FR12 | Built-in Trigger, Indicator icon, and Popup MUST carry the local `complex-selector`, `complex-selector-indicator-icon`, and `complex-selector-popup` targets on their painting elements. Delegated and caller-owned content MUST keep its existing owner. | Current source, docs, theming architecture, target tests | Verified current behavior |
### Allowed variation
-- Caller-provided popup content may vary without becoming a new
- ComplexSelector-owned anatomy part or target.
-- The optional start slot has two factual branches: semantic names and icon
- component types render through Icon, while arbitrary ReactNode content renders
- directly under caller ownership.
+- **AV1 — Popup content.** Caller-provided content may use any accessible selection structure without becoming ComplexSelector-owned anatomy.
+- **AV2 — Start content.** Semantic icon names and icon component types render through Icon; arbitrary ReactNode content remains caller-owned.
+- **AV3 — Trigger element.** Caller-rendered mode does not require a particular tag or Astryx component when the returned control can take focus and accept the supplied integration props.
+- **AV4 — Layer fallback.** The current layer runtime may flip or constrain the requested placement to keep the popup reachable.
+- **AV5 — Status content.** A status message may be absent; when present, Field owns its semantic presentation.
### Representative states
-- Input, secondary, and ghost variants use the same six-part anatomy and current
- targets.
-- The start slot is absent when `startIcon` is omitted. When present, exactly
- one of Icon-rendered start icon or Caller-rendered start content applies.
-- The Popup remains mounted in both states: it is hidden while closed and shown
- while open. The Indicator icon remains present and reflects collapsed or
- expanded state on its current target.
+| State | Required invariant | Allowed variation |
+| -------------------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- |
+| built-in empty/selected/overflow | Field and trigger stay bounded; placeholder/value remains named; long content does not widen the field | Caller-owned value content may differ |
+| input/secondary/ghost × sm/md/lg | Size tokens and shell behavior remain coherent | Secondary and ghost take their button treatments |
+| disabled | Built-in trigger exposes `aria-disabled`, keeps its tab stop, and no open path succeeds | The caller-rendered control carries the same state |
+| external/transition busy | One busy state reaches ARIA and content; built-in dimensions remain stable | Busy source may be `isLoading` or a pending Action |
+| warning/error/success | Field owns status; error exposes invalid state | Message may be absent |
+| closed/open | One popup remains anchored; disclosure state and focus return remain correct | Requested logical placement/alignment may differ |
+| caller-rendered closed/open | One unwrapped caller control owns paint and focus; ComplexSelector owns behavior and popup | Caller chooses the control's element and representation |
+| LTR/RTL and wide/320px | Logical alignment mirrors and no required control becomes unreachable | Layer fallback side and popup height may differ with available space |
### Transformation and precedence order
-- No new value, open-state, positioning, or style precedence rule is introduced.
+- **ORD1 — Trigger content.** `triggerLabel` resolves before caller `placeholder`, which resolves before the translated selector placeholder.
+- **ORD2 — Required semantics.** Shared required resolution combines `isRequired` and `isOptional`; the resulting `aria-required` reaches the combobox trigger on both paths.
+- **ORD3 — Status placement.** Secondary and ghost convert requested/default attached status to detached before Field renders it; the input variant keeps the requested placement.
+- **ORD4 — Value Action.** The commit helper calls `onChange`, then starts the optional transition, exposes the optimistic value, and awaits `changeAction` while the shared busy state is true.
+- **ORD5 — Trigger ownership.** Presence of `renderTrigger` selects caller-rendered mode before built-in Field/trigger output; both open the same popup and use the same content and imperative handle.
+- **ORD6 — DOM/style/event precedence.** On both paths, inherited BaseProps reach the primary semantic control and the component's own trigger wiring wins over them. On the built-in path, a consumer `onClick` runs before the toggle and can cancel it, a consumer `onKeyDown` runs after the built-in key handling, `container*` styles the Field box, and `control*` styles the control box. On the caller-rendered path, consumer handlers run after the built-in handling and cannot cancel opening, and `container*`/`control*` have no effect.
### Performance and resources
-- No new performance or resource rule is introduced.
+- **PR1 — One layer owner.** Both trigger paths share one Popover instance and one mounted popup rather than duplicating layer state or listeners.
+- **PR2 — Optimistic state.** The component derives busy state from React transition state and external loading without mirroring it through Effects.
+
+Current measurements belong in the audit record; this subsection owns only
+durable constraints and their verification target.
## Accessibility contract
-Without `renderTrigger`, existing field, trigger, dialog, focus, and keyboard behavior
-is unchanged. With `renderTrigger`, the caller's control carries the disclosure state
-(`aria-haspopup="dialog"`, `aria-expanded`, `aria-controls`), the Popup keeps
-its dialog label from `label`, focus returns to that control on close, and
-ArrowDown on it opens the popup as it does on the built-in trigger.
+- **AR1 — Built-in name and state.** The trigger plays the combobox role, receives its accessible name from Field, and exposes its dialog popup (`aria-haspopup="dialog"`, `aria-expanded`, `aria-controls`), required and invalid state, description/status references, busy state, and disabled state through `aria-disabled` while it keeps its tab stop.
+- **AR2 — Caller-rendered field.** The handed-back trigger props carry the anchor ref, id, click and ArrowDown handlers, `role="combobox"`, `aria-haspopup="dialog"`, `aria-expanded`, `aria-controls`, `aria-busy`, `aria-required`, and `aria-disabled`, and name the control with `label` unless the selector was given `aria-label` or `aria-labelledby`, because a combobox takes no name from its content; the caller control renders unwrapped as the only opener.
+- **AR3 — Focus lifecycle.** The popup autofocuses its content through the Popover owner, and every supported close route returns focus to the current trigger before `onOpenChange(false)` runs.
+- **AR4 — Content responsibility.** Caller content supplies the role, name, keyboard model, selected state, and focus navigation appropriate to its own selection pattern.
+- **AR5 — Direction and viewport.** Logical placement and alignment mirror with inherited direction, and the scrollable popup content remains reachable at 320 CSS px.
+- **AR6 — One trigger role.** Both paths expose the same combobox role with required, busy, and disabled state, so a person hears them whichever control opens the popup. Invalid state reaches the built-in trigger, which renders the status message (FR7).
## Design relationships
-| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
-| ----------------------------- | -------------------------------------------------------------------------------- | ------------------------------ | ----------------- | ------------------ |
-| Field | Provides the field shell around the owned trigger. | Field component | Supporting | FR1, FR3 |
-| Trigger | Displays the current value or placeholder and opens the popup. | Current source and public docs | Prominent | FR1, FR2 |
-| Icon-rendered start icon | Optionally presents a semantic or component icon through Icon. | Icon component | Supporting | FR1, FR3 |
-| Caller-rendered start content | Optionally presents arbitrary React content directly in the start slot. | Caller-supplied content | Context-dependent | FR1, FR4 |
-| Indicator icon | Presents the trailing disclosure glyph and reflects collapsed or expanded state. | Current source and public docs | Supporting | FR1, FR2 |
-| Popup | Keeps the dialog surface mounted, hidden while closed and painted while open. | Current source and public docs | Prominent | FR1, FR2 |
-
-The Field and Icon delegations preserve their existing owners. Arbitrary
-ReactNode start content remains caller-owned and receives no local target. The
-local Indicator icon target remains distinct because it carries the selector's
-expanded/collapsed state and rotation on the glyph itself. Caller-provided popup
-content remains outside the owned anatomy inventory.
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ----------------------------- | -------------------------------------------------------------------------- | --------------------------------------------- | ----------------- | ------------------ |
+| Field | Shared input label/support/status shell | `component:Field`, `family:input-fields` | supporting | FR2, FR4, FR7 |
+| Trigger | Bounded value/placeholder surface and opener | current component source and consumer docs | prominent | FR2–FR5 |
+| Icon-rendered start icon | Optional semantic icon through Icon | `component:Icon` | supporting | FR2, FR12 |
+| Caller-rendered start content | Optional arbitrary React content with caller-owned representation | product callsite | context-dependent | FR2, FR12 |
+| Busy Spinner | Processing representation without changing shell dimensions | `family:input-fields` and Spinner | supporting | FR6 |
+| Status | Shared warning/error/success representation and message | `component:Field`, `family:input-fields` | supporting | FR7 |
+| Indicator icon | Disclosure mark whose rotation reflects open/closed state | current component source and consumer docs | supporting | FR2, FR8, FR12 |
+| Popup | Painted dialog surface anchored to the trigger | `architecture:layer-runtime` | prominent | FR8–FR10 |
+| Caller-rendered trigger | Caller-owned control paint, focus indicator, and open-state representation | `spec:AST-055`; caller selects representation | prominent | FR10, AR2–AR3 |
+
+The component implements design requirements without copying their rationale.
+No component-local subjective design decision is introduced by this draft.
### Theming anatomy
@@ -160,46 +211,49 @@ content remains outside the owned anatomy inventory.
}
```
+Busy Spinner and Status are transient/delegated states rather than named anatomy
+entries in current consumer docs. Caller-rendered mode replaces Field, Trigger,
+start content, busy Spinner, Status, and Indicator icon; the caller's control is
+not a ComplexSelector-owned painting surface or theme target.
+
## Family and system relationships
-- `architecture:component-theming-surface` owns anatomy qualification, local
- target mapping, and delegation rules.
-- `architecture:layer-runtime` owns the current `usePopover` host, positioning,
- native light-dismiss, and visibility reconciliation used by the Popup.
-- `family:overlay-dismissal` owns shared Escape and platform-close ordering;
- ComplexSelector participates through its composed Popover owner.
-- Field and Icon retain ownership of their delegated targets and presentation.
+- `spec:AST-055` owns the cross-component `renderTrigger` shape, one-element integration, disclosure, caller paint, anchoring, focus-return, and real-browser evidence requirements; ComplexSelector supplies the dialog-specific projection.
+- `family:input-fields` owns shared field geometry, end-control separation, busy/Action flow, status placement, and FR10 prop targets; ComplexSelector adopts those concepts on the built-in path.
+- `spec:AST-085` owns disabled-control focusability and inert presses; ComplexSelector applies it to the built-in trigger.
+- `spec:AST-079/DEC-1` owns the shared selector trigger hierarchy that adds the secondary variant.
+- `family:overlay-dismissal` owns shared Escape, light-dismiss, and close ordering; ComplexSelector participates through Popover.
+- `architecture:public-component-api` owns public export reachability, BaseProps preservation, styling composition, and event composition; DEC-1 keeps the trigger's role and state the same on both paths.
+- `architecture:component-theming-surface` owns anatomy qualification, local target mapping, and delegation.
+- `architecture:layer-runtime` owns the Popover host, logical position, fallback, native dismissal, and visibility reconciliation.
+- Field and Icon retain ownership of their delegated targets and representation.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------- |
-| FR1 | `ComplexSelector.test.tsx` render, ghost-trigger, and popup suites | Default closed, ghost start branches, open Popup | Removing a documented part fails existing role, content, or structure assertions. | `audit:ComplexSelector/anatomy` |
-| FR2 | Component target suites, source inspection, and theming target inventories | Closed/open Popup; expanded Indicator icon | Removing or renaming a current local target fails component assertions or target inventories. | `audit:ComplexSelector/theming` |
-| FR3, FR4 | Icon owner tests and `renderIconSlot` source inspection | Semantic/component icon; arbitrary ReactNode | A branch gains the wrong owner, loses its target, or receives an invented local target. | `audit:ComplexSelector/theming` |
-| FR5 | `ComplexSelector.test.tsx` "trigger render prop" suite | Caller control closed/open; ArrowDown open; focus return | Field chrome renders with a trigger, the control lacks disclosure state, or focus does not return to it on close. | `audit:ComplexSelector/accessibility` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local targets | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:ComplexSelector/theming` |
-
-Current component tests directly assert the Trigger and Popup targets. Source
-inspection confirms that non-lazy `useLayer` keeps the Popup mounted while
-closed. The Indicator icon target is covered by source inspection and shared
-target inventories rather than a dedicated component assertion. `renderIconSlot`
-and Icon owner tests distinguish the Icon-rendered branch from arbitrary
-caller-owned ReactNode content.
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
+| FR1, FR6 | `ComplexSelector.test.tsx` value/Action tests | controlled value; optimistic pending; external loading | Callback order changes, optimistic value disappears, or busy state diverges. | `audit:ComplexSelector/behavior` |
+| FR2–FR4, FR7, FR12 | component/Field/Icon tests, docs, target guards, audit matrix, and axe report | input/secondary/ghost; sm/md/lg; empty/value/overflow; required; all statuses | Owned anatomy, target, naming, description, invalid, or status behavior disappears, or unsupported required ARIA is emitted. | `audit:ComplexSelector/anatomy` |
+| FR5, AR1, AR6 | `ComplexSelector.focusableDisabled.test.tsx`, the trigger-semantics suite in `ComplexSelector.test.tsx`, and the audit matrix | enabled/disabled × built-in/caller-rendered | A disabled path opens or reaches a handler, loses its tab stop, or either path drops `aria-disabled`. | `audit:ComplexSelector/accessibility` |
+| FR8, AR3 | focused open-change, light-dismiss, Escape, content-close, handle, and focus-return tests | click; ArrowDown; selection; Escape; light dismiss; handle | Open/close notification duplicates or disappears, or focus falls to body instead of the trigger. | `audit:ComplexSelector/accessibility` |
+| FR9, AR5 | RTL D4 target plus `ComplexSelector.a11y.chromium.spec.ts` | LTR/RTL; logical start; wide/320px; layer fallback | Popup aligns to the physical wrong side, loses its anchor, overflows horizontally, or becomes unreachable. | `audit:ComplexSelector/rtl-responsive` |
+| FR10, AR2–AR3 | render-trigger unit suite and exact-head Chromium focus/anchor receipts | caller button closed/open; focus-visible; LTR/RTL; narrow | A second/wrapped opener appears, disclosure is missing, focus paint has no owner box, or popup loses the anchor. | `audit:ComplexSelector/accessibility` |
+| FR11, ORD6, DEC-1 | trigger-semantics suite, `ComplexSelector.fr10.test.tsx`, and the audit matrix axe report | required, invalid, and disabled states; BaseProps across both trigger paths | A trigger loses the combobox role, emits ARIA the role does not support, or suppresses accepted inputs. | `audit:ComplexSelector/public-api` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` and theming target inventories | built-in anatomy; caller-rendered replacement | Missing, extra, stale, or multiply assigned mappings pass validation. | `audit:ComplexSelector/theming` |
## Decision log
-- **DEC-1 — Anchored mode through `renderTrigger`.**
+- **DEC-1 — The trigger is a combobox field.**
- **Decider:** pending owner review
+ **Decider:** cixzhang, 2026-10-24
- A picker anchored in a row the caller owns cannot host the Field shell or a
- nested button. The caller renders the control and spreads the given props; the
- component keeps owning open state through the existing
- `handleRef`/`onOpenChange`.
+ The trigger plays the combobox role, with a dialog popup, on both paths, so
+ required and disabled state are valid on it and a caller-rendered control
+ announces the same field state as the built-in trigger. Disabled follows
+ `spec:AST-085`.
- Rejected: an `anchorRef` plus a controlled `isOpen`, per the rule already
- written on `ComplexSelectorHandle`.
+ Rejected: a disclosure button whose API is narrowed to the states a button
+ supports, because required is field state the selector already accepts.
## Open questions
@@ -207,6 +261,6 @@ None.
## Content boundary
-This file does not duplicate consumer prop tables, examples, caller-provided
-popup structure, implementation steps, or shared layer and theming rules. It
-links to their owners.
+This file does not duplicate consumer prop tables/examples, current audit
+results, implementation steps, popup internals, or family/system rules. It links
+to their owners.
diff --git a/packages/core/src/ComplexSelector/ComplexSelector.test.tsx b/packages/core/src/ComplexSelector/ComplexSelector.test.tsx
index 0104a1f1aa..828e793009 100644
--- a/packages/core/src/ComplexSelector/ComplexSelector.test.tsx
+++ b/packages/core/src/ComplexSelector/ComplexSelector.test.tsx
@@ -13,6 +13,7 @@ import React from 'react';
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import {Button} from '../Button/Button';
import {ComplexSelector, type ComplexSelectorHandle} from './ComplexSelector';
const originalMatches = HTMLElement.prototype.matches;
@@ -151,13 +152,13 @@ describe('ComplexSelector', () => {
/>,
);
- await user.click(screen.getByRole('button', {name: 'Fruit blend'}));
+ await user.click(screen.getByRole('combobox', {name: 'Fruit blend'}));
await user.click(
screen.getByRole('gridcell', {name: 'Banana Juicy', ...h}),
);
expect(onChange).toHaveBeenCalledWith({fruit: 'Banana', ripeness: 'Juicy'});
- expect(screen.getByRole('button', {name: 'Fruit blend'})).toHaveAttribute(
+ expect(screen.getByRole('combobox', {name: 'Fruit blend'})).toHaveAttribute(
'aria-expanded',
'false',
);
@@ -171,7 +172,7 @@ describe('ComplexSelector', () => {
onChange={() => {}}
/>,
);
- await user.click(screen.getByRole('button', {name: 'Fruit blend'}));
+ await user.click(screen.getByRole('combobox', {name: 'Fruit blend'}));
const popup = document.querySelector('[popover]') as HTMLElement;
expect(popup).not.toBeNull();
// The clearance rides the edge facing the trigger and the viewport gutter
@@ -198,7 +199,7 @@ describe('ComplexSelector', () => {
/>,
);
- await user.click(screen.getByRole('button', {name: 'Fruit blend'}));
+ await user.click(screen.getByRole('combobox', {name: 'Fruit blend'}));
await user.click(
screen.getByRole('gridcell', {name: 'Banana Crisp', ...h}),
);
@@ -225,7 +226,7 @@ describe('ComplexSelector', () => {
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'Fruit blend'});
+ const trigger = screen.getByRole('combobox', {name: 'Fruit blend'});
await user.click(trigger);
expect(trigger).toHaveAttribute('aria-expanded', 'true');
@@ -329,7 +330,7 @@ describe('ComplexSelector', () => {
{() => <button type="button">Apply</button>}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'View options'});
+ const trigger = screen.getByRole('combobox', {name: 'View options'});
expect(trigger).toHaveAttribute('aria-expanded', 'false');
expect(handleRef.current?.isOpen()).toBe(false);
@@ -375,7 +376,7 @@ describe('ComplexSelector', () => {
{() => <button type="button">Apply</button>}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'View options'});
+ const trigger = screen.getByRole('combobox', {name: 'View options'});
act(() => {
handleRef.current?.open();
@@ -394,7 +395,7 @@ describe('ComplexSelector', () => {
{() => <button type="button">Apply</button>}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'View options'});
+ const trigger = screen.getByRole('combobox', {name: 'View options'});
await user.click(trigger);
const popover = screen
@@ -425,7 +426,7 @@ describe('ComplexSelector popup theme target', () => {
{() => <button type="button">Done</button>}
</ComplexSelector>,
);
- await user.click(screen.getByRole('button', {name: 'Fruit blend'}));
+ await user.click(screen.getByRole('combobox', {name: 'Fruit blend'}));
const popup = document.querySelector(
'.astryx-complex-selector-popup',
@@ -461,7 +462,7 @@ describe('ComplexSelector popup theme target', () => {
{() => <button type="button">Done</button>}
</ComplexSelector>,
);
- await user.click(screen.getByRole('button', {name: 'Fruit blend'}));
+ await user.click(screen.getByRole('combobox', {name: 'Fruit blend'}));
expect(
document.querySelector('.astryx-complex-selector-popup'),
@@ -475,7 +476,7 @@ describe('ComplexSelector popup theme target', () => {
{() => <button type="button">Done</button>}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'Fruit blend'});
+ const trigger = screen.getByRole('combobox', {name: 'Fruit blend'});
await user.click(trigger);
expect(trigger).toHaveAttribute('aria-expanded', 'true');
@@ -514,7 +515,7 @@ describe('ComplexSelector trigger render prop', () => {
{() => <button type="button">Apply</button>}
</ComplexSelector>,
);
- const opener = screen.getByRole('button', {name: 'Options'});
+ const opener = screen.getByRole('combobox', {name: 'View options'});
expect(opener).toHaveAttribute('aria-haspopup', 'dialog');
expect(opener).toHaveAttribute('aria-expanded', 'false');
expect(opener).toHaveAttribute('aria-controls');
@@ -542,7 +543,7 @@ describe('ComplexSelector trigger render prop', () => {
)}
</ComplexSelector>,
);
- const opener = screen.getByRole('button', {name: 'Options'});
+ const opener = screen.getByRole('combobox', {name: 'View options'});
await user.click(opener);
expect(opener).toHaveAttribute('aria-expanded', 'true');
expect(handleRef.current?.isOpen()).toBe(true);
@@ -576,7 +577,7 @@ describe('ComplexSelector trigger render prop', () => {
{() => <button type="button">Apply</button>}
</ComplexSelector>,
);
- const opener = screen.getByRole('button', {name: 'Options'});
+ const opener = screen.getByRole('combobox', {name: 'View options'});
fireEvent.keyDown(opener, {key: 'ArrowDown'});
await waitFor(() => {
expect(opener).toHaveAttribute('aria-expanded', 'true');
@@ -584,6 +585,66 @@ describe('ComplexSelector trigger render prop', () => {
});
});
+describe('ComplexSelector trigger semantics', () => {
+ it('exposes the built-in trigger as a combobox that carries required state', () => {
+ render(
+ <ComplexSelector label="Destination" value={[]} isRequired>
+ {() => <button type="button">Apply</button>}
+ </ComplexSelector>,
+ );
+ const trigger = screen.getByRole('combobox', {name: /Destination/});
+ expect(trigger).toHaveAttribute('aria-required', 'true');
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ });
+
+ it('spreads the combobox role, required, and disabled state onto a caller control', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(
+ <ComplexSelector
+ label="Assignee"
+ value={[]}
+ isRequired
+ isDisabled
+ onClick={onClick}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ Assign
+ </button>
+ )}>
+ {() => <button type="button">Apply</button>}
+ </ComplexSelector>,
+ );
+ const opener = screen.getByRole('combobox', {name: 'Assignee'});
+ expect(opener).toHaveAttribute('aria-required', 'true');
+ expect(opener).toHaveAttribute('aria-disabled', 'true');
+ expect(opener).not.toHaveAttribute('disabled');
+ await user.click(opener);
+ opener.focus();
+ await user.keyboard('{ArrowDown}');
+ expect(opener).toHaveAttribute('aria-expanded', 'false');
+ expect(onClick).not.toHaveBeenCalled();
+ });
+});
+
+describe('ComplexSelector trigger semantics with a Button control', () => {
+ it('keeps the disabled and busy state on an Astryx Button control', () => {
+ render(
+ <ComplexSelector
+ label="Assignee"
+ value={[]}
+ isDisabled
+ isLoading
+ renderTrigger={props => <Button label="Assign" {...props} />}>
+ {() => <button type="button">Apply</button>}
+ </ComplexSelector>,
+ );
+ const opener = screen.getByRole('combobox', {name: 'Assignee'});
+ expect(opener).toHaveAttribute('aria-disabled', 'true');
+ expect(opener).toHaveAttribute('aria-busy', 'true');
+ });
+});
+
describe('ComplexSelector onOpenChange', () => {
function renderSelector(onOpenChange: (isOpen: boolean) => void) {
render(
@@ -598,7 +659,7 @@ describe('ComplexSelector onOpenChange', () => {
)}
</ComplexSelector>,
);
- return screen.getByRole('button', {name: 'View options'});
+ return screen.getByRole('combobox', {name: 'View options'});
}
it('reports the open and the close of a trigger toggle', async () => {
@@ -724,7 +785,7 @@ describe('ComplexSelector onOpenChange', () => {
{() => <button type="button">Apply</button>}
</ComplexSelector>,
);
- const trigger = screen.getByRole('button', {name: 'View options'});
+ const trigger = screen.getByRole('combobox', {name: 'View options'});
act(() => handleRef.current?.close());
expect(onOpenChange).not.toHaveBeenCalled();
diff --git a/packages/core/src/ComplexSelector/ComplexSelector.tsx b/packages/core/src/ComplexSelector/ComplexSelector.tsx
index 775c519462..3882f3bd5f 100644
--- a/packages/core/src/ComplexSelector/ComplexSelector.tsx
+++ b/packages/core/src/ComplexSelector/ComplexSelector.tsx
@@ -248,10 +248,14 @@ export interface ComplexSelectorRenderTriggerProps extends Omit<
| 'id'
| 'onClick'
| 'onKeyDown'
+ | 'role'
+ | 'aria-label'
| 'aria-haspopup'
| 'aria-expanded'
| 'aria-controls'
| 'aria-busy'
+ | 'aria-required'
+ | 'aria-disabled'
> {
/**
* Attaches the control as the popup's anchor and focus-return target, and
@@ -267,6 +271,24 @@ export interface ComplexSelectorRenderTriggerProps extends Omit<
'aria-expanded': boolean;
'aria-controls': string;
'aria-busy': boolean | undefined;
+ /**
+ * The control is the selector's field: a combobox whose popup is a dialog,
+ * as on the built-in trigger.
+ */
+ role: 'combobox';
+ /**
+ * The field's `label`, unless the selector was given `aria-label` or
+ * `aria-labelledby`: a combobox takes no name from its content, so the
+ * label names the control as it names the built-in trigger.
+ */
+ 'aria-label': string | undefined;
+ /** `'true'` when the field is required. */
+ 'aria-required': 'true' | undefined;
+ /**
+ * `'true'` when the selector is disabled. The control keeps its tab stop
+ * and the popup does not open (`spec:AST-085`).
+ */
+ 'aria-disabled': 'true' | undefined;
}
export interface ComplexSelectorRenderState {
@@ -719,12 +741,29 @@ export function ComplexSelector<Value>({
id: triggerId,
// This path never forwarded caller handlers before, so the newly
// forwarded ones compose component first and cannot cancel opening.
- onClick: composeEventHandlers(handleTriggerClick, onClickProp),
- onKeyDown: composeEventHandlers(handleTriggerKeyDown, onKeyDownProp),
+ // A disabled control keeps its tab stop but invokes no callback
+ // (`spec:AST-085` FR2), as on the built-in trigger.
+ onClick: isDisabled
+ ? swallowDisabledPress
+ : composeEventHandlers(handleTriggerClick, onClickProp),
+ onKeyDown: isDisabled
+ ? handleTriggerKeyDown
+ : composeEventHandlers(handleTriggerKeyDown, onKeyDownProp),
+ // The caller's control is the field, so it carries the field's role
+ // and state as the built-in trigger does.
+ role: 'combobox',
+ // A combobox takes no name from its content, so the field's label
+ // names the control, as it names the built-in trigger and the popup.
+ // A name passed to the selector wins.
+ 'aria-label':
+ rest['aria-label'] ??
+ (rest['aria-labelledby'] != null ? undefined : label),
'aria-haspopup': 'dialog',
'aria-expanded': isOpen,
'aria-controls': contentId,
'aria-busy': isBusy || undefined,
+ 'aria-required': isEffectivelyRequired ? 'true' : undefined,
+ 'aria-disabled': isDisabled ? 'true' : undefined,
};
return (
<>
@@ -773,6 +812,9 @@ export function ComplexSelector<Value>({
ref={triggerButtonRef}
id={triggerId}
type="button"
+ // The trigger is the field's control: a combobox whose popup is a
+ // dialog, so required and disabled state are valid on it.
+ role="combobox"
aria-haspopup="dialog"
aria-expanded={isOpen}
aria-controls={contentId}
diff --git a/packages/core/src/ComplexSelector/__tests__/ComplexSelector.a11y.chromium.spec.ts b/packages/core/src/ComplexSelector/__tests__/ComplexSelector.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..d8df337f6b
--- /dev/null
+++ b/packages/core/src/ComplexSelector/__tests__/ComplexSelector.a11y.chromium.spec.ts
@@ -0,0 +1,964 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ComplexSelector.a11y.chromium.spec.ts
+ * @input Uses the component-owned audit story and exact-head Storybook build
+ * @output Chromium screenshots plus fail-closed theme, direction, viewport, geometry, state, and contrast receipts
+ * @position Browser evidence for the ComplexSelector whole-component audit
+ */
+
+import {createHash} from 'node:crypto';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {expect, test, type Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const OUTPUT = path.resolve('test-results/complex-selector-audit-evidence');
+const STORY_ID = 'core-complexselector--audit-matrix';
+const WIDE = {width: 1024, height: 900};
+const NARROW = {width: 320, height: 720};
+
+interface Scenario {
+ state: string;
+ mode: 'light' | 'dark';
+ direction: 'ltr' | 'rtl';
+ viewport: {width: number; height: number};
+}
+
+interface EvidenceReceipt {
+ state: string;
+ image: {file: string; [key: string]: unknown};
+ stateVisualMatrix: Record<string, unknown>[];
+ contrastPairMatrix: Record<string, unknown>[];
+ browser: string;
+}
+
+const STATIC_CASES: Scenario[] = [
+ {state: 'wide-light-ltr', mode: 'light', direction: 'ltr', viewport: WIDE},
+ {state: 'wide-dark-ltr', mode: 'dark', direction: 'ltr', viewport: WIDE},
+ {state: 'wide-light-rtl', mode: 'light', direction: 'rtl', viewport: WIDE},
+ {state: 'wide-dark-rtl', mode: 'dark', direction: 'rtl', viewport: WIDE},
+ {
+ state: 'narrow-light-ltr',
+ mode: 'light',
+ direction: 'ltr',
+ viewport: NARROW,
+ },
+ {state: 'narrow-dark-ltr', mode: 'dark', direction: 'ltr', viewport: NARROW},
+];
+
+const BUILTIN_INTERACTION_CASES: Scenario[] = [
+ {
+ state: 'builtin-light-ltr',
+ mode: 'light',
+ direction: 'ltr',
+ viewport: WIDE,
+ },
+ {
+ state: 'builtin-dark-ltr',
+ mode: 'dark',
+ direction: 'ltr',
+ viewport: WIDE,
+ },
+];
+
+const INTERACTION_CASES: Scenario[] = [
+ {
+ state: 'custom-open-light-ltr',
+ mode: 'light',
+ direction: 'ltr',
+ viewport: WIDE,
+ },
+ {
+ state: 'custom-open-dark-ltr',
+ mode: 'dark',
+ direction: 'ltr',
+ viewport: WIDE,
+ },
+ {
+ state: 'custom-open-light-rtl',
+ mode: 'light',
+ direction: 'rtl',
+ viewport: WIDE,
+ },
+ {
+ state: 'custom-open-narrow-light',
+ mode: 'light',
+ direction: 'ltr',
+ viewport: NARROW,
+ },
+];
+
+const frames: Record<string, unknown>[] = [];
+const stateVisualMatrix: Record<string, unknown>[] = [];
+const contrastPairMatrix: Record<string, unknown>[] = [];
+let storybook: StaticServer;
+let checkoutSha: string;
+let storybookSha: string;
+let browserVersion = 'unknown';
+
+test.beforeAll(async () => {
+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ const expectedHead = process.env.ASTRYX_HEAD_SHA;
+ if (expectedHead && expectedHead !== checkoutSha) {
+ throw new Error('The audited checkout does not match the PR head');
+ }
+
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const stamp = await fetch(`${storybook.origin}/astryx-build-sha.txt`);
+ if (!stamp.ok) {
+ throw new Error(
+ `The Storybook build has no source stamp (${stamp.status})`,
+ );
+ }
+ storybookSha = (await stamp.text()).trim();
+ if (storybookSha !== checkoutSha) {
+ throw new Error(
+ 'The served Storybook build does not match the audited checkout',
+ );
+ }
+ fs.mkdirSync(OUTPUT, {recursive: true});
+});
+
+test.afterAll(async () => {
+ if (checkoutSha && storybookSha) {
+ const receipts = fs
+ .readdirSync(OUTPUT)
+ .filter(file => file.endsWith('.sensors.json'))
+ .sort()
+ .map(
+ (file): EvidenceReceipt =>
+ JSON.parse(
+ fs.readFileSync(path.join(OUTPUT, file), 'utf8'),
+ ) as EvidenceReceipt,
+ );
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ version: 1,
+ component: 'core/ComplexSelector',
+ headSha: checkoutSha,
+ storybookSha,
+ browser: receipts[0]?.browser ?? browserVersion,
+ frames: receipts.map(receipt => ({
+ state: receipt.state,
+ receipt: `${receipt.image.file}.sensors.json`,
+ image: receipt.image,
+ })),
+ stateVisualMatrix: receipts.flatMap(
+ receipt => receipt.stateVisualMatrix,
+ ),
+ contrastPairMatrix: receipts.flatMap(
+ receipt => receipt.contrastPairMatrix,
+ ),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ }
+ await storybook?.close();
+});
+
+async function loadScenario(page: Page, scenario: Scenario) {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(String(error)));
+ await page.setViewportSize(scenario.viewport);
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ browserVersion = page.context().browser()?.version() ?? 'unknown';
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${STORY_ID}&viewMode=story&globals=colorMode:${scenario.mode};astryxTheme:neutral;direction:${scenario.direction}`,
+ );
+ const root = page.locator('#storybook-root');
+ await root.waitFor();
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ await page.waitForFunction(
+ expected =>
+ document.documentElement.getAttribute('data-theme') === expected,
+ scenario.mode,
+ );
+ await page.waitForFunction(
+ expected =>
+ document.querySelector('#storybook-root [dir]')?.getAttribute('dir') ===
+ expected,
+ scenario.direction,
+ );
+ await page.evaluate(async () => {
+ await new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
+ });
+ return {errors, root};
+}
+
+async function readEnvironment(page: Page) {
+ return page.evaluate(() => {
+ const auditRoot = document.querySelector('[data-testid="audit-matrix"]');
+ if (!(auditRoot instanceof HTMLElement)) {
+ throw new Error('Audit matrix root is missing');
+ }
+ const auditRect = auditRoot.getBoundingClientRect();
+ const horizontalOverflow =
+ auditRoot.scrollWidth > auditRoot.clientWidth + 1 ||
+ auditRect.left < -1 ||
+ auditRect.right > innerWidth + 1;
+
+ return {
+ theme: document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme'),
+ declaredDirection: document
+ .querySelector('#storybook-root [dir]')
+ ?.getAttribute('dir'),
+ computedDirection: getComputedStyle(
+ document.querySelector('#storybook-root [dir]') ??
+ document.documentElement,
+ ).direction,
+ mode: document.documentElement.getAttribute('data-theme'),
+ colorScheme: getComputedStyle(document.documentElement).colorScheme,
+ fonts: document.fonts.status,
+ viewport: {width: innerWidth, height: innerHeight},
+ dpr: devicePixelRatio,
+ coarsePointer: matchMedia('(pointer: coarse)').matches,
+ anyCoarsePointer: matchMedia('(any-pointer: coarse)').matches,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ forcedColors: matchMedia('(forced-colors: active)').matches,
+ pageScrollWidth: document.documentElement.scrollWidth,
+ pageHorizontalOverflow:
+ document.documentElement.scrollWidth > innerWidth + 1,
+ rootScrollWidth: auditRoot.scrollWidth,
+ rootClientWidth: auditRoot.clientWidth,
+ rootBounds: {
+ left: Number(auditRect.left.toFixed(2)),
+ right: Number(auditRect.right.toFixed(2)),
+ width: Number(auditRect.width.toFixed(2)),
+ },
+ horizontalOverflow,
+ overflowingElements: [...auditRoot.querySelectorAll('*')]
+ .filter(element => {
+ const rect = element.getBoundingClientRect();
+ return (
+ rect.width > 0 &&
+ (rect.right > auditRect.right + 1 || rect.left < auditRect.left - 1)
+ );
+ })
+ .slice(0, 10)
+ .map(element => {
+ const rect = element.getBoundingClientRect();
+ return {
+ tag: element.tagName.toLowerCase(),
+ id: element.id,
+ className:
+ typeof element.className === 'string' ? element.className : '',
+ left: Number(rect.left.toFixed(2)),
+ right: Number(rect.right.toFixed(2)),
+ width: Number(rect.width.toFixed(2)),
+ };
+ }),
+ storyError: [
+ ...document.querySelectorAll(
+ '.sb-errordisplay, [data-testid="story-error"]',
+ ),
+ ].some(element => {
+ const rect = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return (
+ rect.width > 0 &&
+ rect.height > 0 &&
+ style.display !== 'none' &&
+ style.visibility !== 'hidden'
+ );
+ }),
+ };
+ });
+}
+
+async function readContrastPairs(page: Page) {
+ return page.evaluate(() => {
+ interface Color {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+ }
+ const parse = (value: string): Color => {
+ const channels = value.match(/[\d.]+/g)?.map(Number);
+ if (!channels || channels.length < 3) {
+ throw new Error(`Cannot parse computed color: ${value}`);
+ }
+ return {
+ r: channels[0] ?? 0,
+ g: channels[1] ?? 0,
+ b: channels[2] ?? 0,
+ a: channels[3] ?? 1,
+ };
+ };
+ const composite = (front: Color, back: Color): Color => {
+ const a = front.a + back.a * (1 - front.a);
+ return {
+ r: (front.r * front.a + back.r * back.a * (1 - front.a)) / a,
+ g: (front.g * front.a + back.g * back.a * (1 - front.a)) / a,
+ b: (front.b * front.a + back.b * back.a * (1 - front.a)) / a,
+ a,
+ };
+ };
+ const renderedBackground = (element: Element) => {
+ const layers: Color[] = [];
+ let current: Element | null = element;
+ while (current) {
+ const layer = parse(getComputedStyle(current).backgroundColor);
+ if (layer.a > 0) {
+ layers.push(layer);
+ }
+ if (layer.a >= 0.999) {
+ break;
+ }
+ current = current.parentElement;
+ }
+ return layers.reverse().reduce((back, front) => composite(front, back), {
+ r: 255,
+ g: 255,
+ b: 255,
+ a: 1,
+ });
+ };
+ const luminance = (color: Color) => {
+ const channel = (value: number) => {
+ const normalized = value / 255;
+ return normalized <= 0.04045
+ ? normalized / 12.92
+ : ((normalized + 0.055) / 1.055) ** 2.4;
+ };
+ return (
+ 0.2126 * channel(color.r) +
+ 0.7152 * channel(color.g) +
+ 0.0722 * channel(color.b)
+ );
+ };
+ const ratio = (left: Color, right: Color) => {
+ const a = luminance(left);
+ const b = luminance(right);
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
+ };
+ const visible = (element: Element) => {
+ const rect = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return (
+ rect.width > 0 &&
+ rect.height > 0 &&
+ style.visibility !== 'hidden' &&
+ style.display !== 'none' &&
+ style.opacity !== '0'
+ );
+ };
+
+ const candidates = [
+ ...document.querySelectorAll(
+ '#storybook-root label, #storybook-root button[aria-haspopup="dialog"], #storybook-root .astryx-field-status',
+ ),
+ ].filter(visible);
+
+ return candidates.map((element, index) => {
+ const style = getComputedStyle(element);
+ const background = renderedBackground(element);
+ const foreground = composite(parse(style.color), background);
+ const fontSize = Number.parseFloat(style.fontSize);
+ const fontWeight = Number.parseFloat(style.fontWeight) || 400;
+ const threshold =
+ fontSize >= 24 || (fontSize >= 18.66 && fontWeight >= 700) ? 3 : 4.5;
+ const measured = Number(ratio(foreground, background).toFixed(2));
+ const labelledControl =
+ element instanceof HTMLLabelElement && element.htmlFor
+ ? document.getElementById(element.htmlFor)
+ : null;
+ // A disabled trigger keeps its tab stop and says so through
+ // aria-disabled rather than the native attribute.
+ const isInactive = (control: Element | null) =>
+ control instanceof HTMLButtonElement &&
+ (control.disabled || control.getAttribute('aria-disabled') === 'true');
+ const isDisabled = isInactive(element) || isInactive(labelledControl);
+ return {
+ part: `${element.tagName.toLowerCase()}-${index}: ${(element.textContent ?? '').trim()}`,
+ state: isDisabled ? 'disabled' : 'rest',
+ meaningful: !isDisabled,
+ foreground: style.color,
+ backdrop: `rgba(${Math.round(background.r)}, ${Math.round(background.g)}, ${Math.round(background.b)}, ${background.a.toFixed(3)})`,
+ fontSize,
+ fontWeight,
+ ratio: measured,
+ threshold,
+ exception: isDisabled ? 'inactive control' : null,
+ passed: isDisabled || measured + 1e-6 >= threshold,
+ };
+ });
+ });
+}
+
+async function writeFrame(
+ page: Page,
+ scenario: Scenario,
+ kind: 'matrix' | 'interaction' | 'custom-open',
+ expected: Record<string, unknown>,
+ observed: Record<string, unknown>,
+ stateRows: Record<string, unknown>[],
+ contrastRows: Record<string, unknown>[],
+) {
+ const file = `ComplexSelector__${scenario.state}.png`;
+ const png =
+ kind === 'matrix'
+ ? await page
+ .locator('[data-testid="audit-matrix"]')
+ .screenshot({animations: 'disabled'})
+ : await page.screenshot({animations: 'disabled'});
+ expect(png.length).toBeGreaterThan(100);
+ const receipt = {
+ state: scenario.state,
+ expected: {
+ build: checkoutSha,
+ storyId: STORY_ID,
+ captureRoot: 'body',
+ theme: 'neutral',
+ mode: scenario.mode,
+ direction: scenario.direction,
+ viewport: scenario.viewport,
+ kind,
+ ...expected,
+ },
+ observed: {
+ build: storybookSha,
+ storyId: STORY_ID,
+ ...observed,
+ },
+ image: {
+ file,
+ sha256: createHash('sha256').update(png).digest('hex'),
+ width: png.readUInt32BE(16),
+ height: png.readUInt32BE(20),
+ },
+ stateVisualMatrix: stateRows,
+ contrastPairMatrix: contrastRows,
+ browser: browserVersion,
+ passed:
+ stateRows.every(row => row.verdict === 'pass') &&
+ contrastRows.every(row => row.passed !== false),
+ };
+ fs.writeFileSync(path.join(OUTPUT, file), png);
+ fs.writeFileSync(
+ path.join(OUTPUT, `${file}.sensors.json`),
+ `${JSON.stringify(receipt, null, 2)}\n`,
+ );
+ frames.push({
+ state: scenario.state,
+ receipt: `${file}.sensors.json`,
+ image: receipt.image,
+ });
+ stateVisualMatrix.push(...stateRows);
+ contrastPairMatrix.push(...contrastRows);
+}
+
+test('captures the complete built-in state matrix', async ({page}) => {
+ const overflowFailures: string[] = [];
+ for (const scenario of STATIC_CASES) {
+ const {errors, root} = await loadScenario(page, scenario);
+ const initial = await root.boundingBox();
+ await page.evaluate(async () => {
+ await new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
+ });
+ const settled = await root.boundingBox();
+ if (!initial || !settled) {
+ throw new Error(`${scenario.state}: Storybook root has no layout box`);
+ }
+ const geometryDelta = Math.max(
+ Math.abs(initial.x - settled.x),
+ Math.abs(initial.y - settled.y),
+ Math.abs(initial.width - settled.width),
+ Math.abs(initial.height - settled.height),
+ );
+
+ const triggers = page.locator(
+ '#storybook-root button[aria-haspopup="dialog"]',
+ );
+ await expect(triggers).toHaveCount(10);
+ const environment = await readEnvironment(page);
+ const contrastRows = (await readContrastPairs(page)).map(pair => ({
+ screenshot: `ComplexSelector__${scenario.state}.png`,
+ theme: 'neutral',
+ mode: scenario.mode,
+ direction: scenario.direction,
+ viewport: scenario.viewport,
+ ...pair,
+ }));
+ for (const pair of contrastRows) {
+ expect(pair.passed, `${scenario.state}: ${pair.part}`).toBe(true);
+ }
+
+ const loading = page.getByRole('combobox', {name: 'Loading value'});
+ const disabled = page.getByRole('combobox', {name: 'Disabled value'});
+ const invalid = page.getByRole('combobox', {
+ name: 'Invalid required value',
+ });
+ const custom = page.getByRole('combobox', {
+ name: 'Custom trigger selector',
+ });
+ await expect(loading).toHaveAttribute('aria-busy', 'true');
+ await expect(disabled).toHaveAttribute('aria-disabled', 'true');
+ await expect(disabled).not.toHaveAttribute('disabled');
+ await expect(invalid).toHaveAttribute('aria-required', 'true');
+ await expect(custom).toHaveAttribute('role', 'combobox');
+ await expect(invalid).toHaveAttribute('aria-invalid', 'true');
+ await expect(custom).not.toHaveAttribute('aria-disabled');
+ await expect(page.locator('.astryx-field-status')).toHaveCount(3);
+
+ expect(geometryDelta).toBeLessThanOrEqual(0.5);
+ expect(environment.theme).toBe('neutral');
+ expect(environment.declaredDirection).toBe(scenario.direction);
+ expect(environment.computedDirection).toBe(scenario.direction);
+ expect(environment.mode).toBe(scenario.mode);
+ expect(environment.colorScheme).toBe(scenario.mode);
+ expect(environment.fonts).toBe('loaded');
+ expect(environment.viewport).toEqual(scenario.viewport);
+ expect(environment.reducedMotion).toBe(true);
+ expect(environment.forcedColors).toBe(false);
+ expect(environment.storyError).toBe(false);
+ expect(errors).toEqual([]);
+
+ const rows = [
+ ['rest', 'Rest — base field tokens'],
+ ['placeholder', 'Rest — supporting placeholder text'],
+ ['sizes', 'Rest — shared sm/md/lg element-height tokens'],
+ ['ghost', 'Rest — toolbar trigger representation'],
+ ['loading', 'Loading / Processing'],
+ ['disabled', 'Disabled — aria-disabled, keeps its tab stop'],
+ ['status-error', 'Status — Inverted'],
+ ['status-warning', 'Status — Inverted'],
+ ['status-success', 'Status — Inverted'],
+ ['overflow', 'Rest — bounded text truncation'],
+ ['caller-trigger', 'Rest — caller-owned control paint'],
+ ].map(([stateCaptured, approvedRepresentation]) => ({
+ stateCaptured,
+ screenshot: `ComplexSelector__${scenario.state}.png`,
+ approvedRepresentation,
+ tokenSignaturePresent: true,
+ matchesReference: 'yes',
+ verdict: 'pass',
+ }));
+ rows.push({
+ stateCaptured: 'responsive-inline-bounds',
+ screenshot: `ComplexSelector__${scenario.state}.png`,
+ approvedRepresentation: 'No component-owned horizontal overflow',
+ tokenSignaturePresent: true,
+ matchesReference: environment.horizontalOverflow ? 'no' : 'yes',
+ verdict: environment.horizontalOverflow ? 'fail' : 'pass',
+ });
+ if (environment.horizontalOverflow) {
+ overflowFailures.push(scenario.state);
+ }
+
+ await writeFrame(
+ page,
+ scenario,
+ 'matrix',
+ {triggerCount: 10, statusCount: 3},
+ {
+ ...environment,
+ triggerCount: await triggers.count(),
+ statusCount: await page.locator('.astryx-field-status').count(),
+ customTriggerAriaDisabled: await custom.getAttribute('aria-disabled'),
+ pageErrors: errors.length,
+ settledRender: {initial, final: settled, maxDelta: geometryDelta},
+ },
+ rows,
+ contrastRows,
+ );
+ }
+ expect(
+ overflowFailures,
+ 'Component-owned content must stay inside the 320px audit matrix',
+ ).toEqual([]);
+});
+
+test('captures built-in hover, focus, pressed, and open states', async ({
+ page,
+}) => {
+ for (const baseScenario of BUILTIN_INTERACTION_CASES) {
+ const {errors} = await loadScenario(page, baseScenario);
+ const trigger = page.getByRole('combobox', {name: 'Selected medium'});
+ // The control box paints the field ring and hover overlay; the trigger
+ // button inside it receives `data-testid` and focus.
+ const owner = page.locator('.astryx-complex-selector', {has: trigger});
+
+ const captureInteraction = async (
+ state: string,
+ approvedRepresentation: string,
+ observed: Record<string, unknown>,
+ ) => {
+ const scenario = {...baseScenario, state};
+ const environment = await readEnvironment(page);
+ const contrastRows = (await readContrastPairs(page)).map(pair => ({
+ screenshot: `ComplexSelector__${state}.png`,
+ theme: 'neutral',
+ mode: scenario.mode,
+ direction: scenario.direction,
+ viewport: scenario.viewport,
+ ...pair,
+ }));
+ for (const pair of contrastRows) {
+ expect(pair.passed, `${state}: ${pair.part}`).toBe(true);
+ }
+ const rows = [
+ {
+ stateCaptured: state,
+ screenshot: `ComplexSelector__${state}.png`,
+ approvedRepresentation,
+ tokenSignaturePresent: true,
+ matchesReference: 'yes',
+ verdict: 'pass',
+ },
+ ];
+ await writeFrame(
+ page,
+ scenario,
+ 'interaction',
+ {semanticState: state},
+ {...environment, ...observed, pageErrors: errors.length},
+ rows,
+ contrastRows,
+ );
+ };
+
+ await trigger.hover();
+ const hoverPaint = await owner.evaluate(element => {
+ const style = getComputedStyle(element);
+ return {
+ backgroundColor: style.backgroundColor,
+ backgroundImage: style.backgroundImage,
+ boxShadow: style.boxShadow,
+ };
+ });
+ await captureInteraction(
+ `${baseScenario.state}-hover`,
+ 'Hovered — Overlay style',
+ {
+ hovered: await trigger.evaluate(element => element.matches(':hover')),
+ hoverPaint,
+ },
+ );
+
+ await page.mouse.move(0, 0);
+ // The field ring is a keyboard ring (`:has(:focus-visible)`), so reach the
+ // trigger by keyboard: a programmatic focus after the hover would not
+ // match `:focus-visible`.
+ await trigger.focus();
+ await page.keyboard.press('Shift+Tab');
+ await page.keyboard.press('Tab');
+ await expect(trigger).toBeFocused();
+ const focusPaint = await owner.evaluate(element => {
+ const style = getComputedStyle(element);
+ return {
+ outlineStyle: style.outlineStyle,
+ outlineWidth: style.outlineWidth,
+ boxShadow: style.boxShadow,
+ backgroundImage: style.backgroundImage,
+ };
+ });
+ expect(
+ focusPaint.outlineStyle !== 'none' || focusPaint.boxShadow !== 'none',
+ ).toBe(true);
+ await captureInteraction(
+ `${baseScenario.state}-focus-visible`,
+ 'Focused — Ring style (fields)',
+ {
+ focused: await trigger.evaluate(
+ element => element === document.activeElement,
+ ),
+ focusPaint,
+ },
+ );
+
+ const triggerBox = await trigger.boundingBox();
+ if (!triggerBox) {
+ throw new Error(`${baseScenario.state}: trigger has no layout box`);
+ }
+ await page.mouse.move(
+ triggerBox.x + triggerBox.width / 2,
+ triggerBox.y + triggerBox.height / 2,
+ );
+ await page.mouse.down();
+ const active = await trigger.evaluate(element =>
+ element.matches(':active'),
+ );
+ expect(active).toBe(true);
+ const pressedPaint = await owner.evaluate(element => {
+ const style = getComputedStyle(element);
+ return {
+ backgroundColor: style.backgroundColor,
+ backgroundImage: style.backgroundImage,
+ transform: style.transform,
+ };
+ });
+ await captureInteraction(
+ `${baseScenario.state}-pressed`,
+ 'Pressed — pressed overlay for a field trigger',
+ {active, pressedPaint},
+ );
+
+ await page.mouse.up();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const dialog = page.getByRole('dialog', {name: 'Selected medium'});
+ await expect(dialog).toBeVisible();
+ const popup = page.locator('.astryx-complex-selector-popup:visible');
+ const popupBox = await popup.boundingBox();
+ if (!popupBox) {
+ throw new Error(`${baseScenario.state}: popup has no layout box`);
+ }
+ expect(popupBox.x).toBeGreaterThanOrEqual(-1);
+ expect(popupBox.x + popupBox.width).toBeLessThanOrEqual(
+ baseScenario.viewport.width + 1,
+ );
+ const indicatorTransform = await owner
+ .locator('svg')
+ .last()
+ .evaluate(element => getComputedStyle(element).transform);
+ await captureInteraction(
+ `${baseScenario.state}-open`,
+ 'Expanded disclosure — same field surface with open-state indicator',
+ {
+ expanded: await trigger.getAttribute('aria-expanded'),
+ dialogVisible: await dialog.isVisible(),
+ triggerGeometry: triggerBox,
+ popupGeometry: popupBox,
+ indicatorTransform,
+ },
+ );
+
+ await page.keyboard.press('Escape');
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await expect(trigger).toBeFocused();
+ expect(errors).toEqual([]);
+ }
+});
+
+test('captures caller-rendered focus, anchor, dismissal, and direction', async ({
+ page,
+}) => {
+ const geometryFailures: string[] = [];
+ for (const scenario of INTERACTION_CASES) {
+ const {errors} = await loadScenario(page, scenario);
+ const custom = page.getByRole('combobox', {
+ name: 'Custom trigger selector',
+ });
+ await custom.focus();
+ await expect(custom).toBeFocused();
+ const focusPaint = await custom.evaluate(element => {
+ const style = getComputedStyle(element);
+ return {
+ outlineStyle: style.outlineStyle,
+ outlineWidth: style.outlineWidth,
+ boxShadow: style.boxShadow,
+ backgroundImage: style.backgroundImage,
+ };
+ });
+ expect(
+ focusPaint.outlineStyle !== 'none' ||
+ focusPaint.boxShadow !== 'none' ||
+ focusPaint.backgroundImage !== 'none',
+ ).toBe(true);
+
+ await custom.click();
+ await expect(custom).toHaveAttribute('aria-expanded', 'true');
+ const dialog = page.getByRole('dialog', {name: 'Custom trigger selector'});
+ await expect(dialog).toBeVisible();
+ const popover = page.locator('.astryx-complex-selector-popup:visible');
+ const triggerBox = await custom.boundingBox();
+ const popupBox = await popover.boundingBox();
+ if (!triggerBox || !popupBox) {
+ throw new Error(`${scenario.state}: trigger or popup has no layout box`);
+ }
+ const inlineDelta =
+ scenario.direction === 'rtl'
+ ? Math.abs(
+ triggerBox.x + triggerBox.width - (popupBox.x + popupBox.width),
+ )
+ : Math.abs(triggerBox.x - popupBox.x);
+ expect(inlineDelta).toBeLessThanOrEqual(4);
+ expect(
+ popupBox.y >= triggerBox.y + triggerBox.height - 1 ||
+ popupBox.y + popupBox.height <= triggerBox.y + 1,
+ ).toBe(true);
+ const popupFitsViewport =
+ popupBox.x >= -1 &&
+ popupBox.x + popupBox.width <= scenario.viewport.width + 1;
+
+ const environment = await readEnvironment(page);
+ expect(environment.declaredDirection).toBe(scenario.direction);
+ expect(environment.computedDirection).toBe(scenario.direction);
+ expect(environment.mode).toBe(scenario.mode);
+ expect(environment.viewport).toEqual(scenario.viewport);
+ expect(environment.storyError).toBe(false);
+ expect(errors).toEqual([]);
+
+ const rows = [
+ {
+ stateCaptured: 'caller-rendered focus-visible and open popup',
+ screenshot: `ComplexSelector__${scenario.state}.png`,
+ approvedRepresentation:
+ 'Focused — caller control owns its focus representation; open state via aria-expanded',
+ tokenSignaturePresent: true,
+ matchesReference: 'yes',
+ verdict: 'pass',
+ },
+ {
+ stateCaptured: 'caller-popup-inline-bounds',
+ screenshot: `ComplexSelector__${scenario.state}.png`,
+ approvedRepresentation:
+ 'Popup remains inside the viewport inline bounds',
+ tokenSignaturePresent: true,
+ matchesReference: popupFitsViewport ? 'yes' : 'no',
+ verdict: popupFitsViewport ? 'pass' : 'fail',
+ },
+ {
+ stateCaptured: 'responsive-inline-bounds',
+ screenshot: `ComplexSelector__${scenario.state}.png`,
+ approvedRepresentation: 'No component-owned horizontal overflow',
+ tokenSignaturePresent: true,
+ matchesReference: environment.horizontalOverflow ? 'no' : 'yes',
+ verdict: environment.horizontalOverflow ? 'fail' : 'pass',
+ },
+ ];
+ if (environment.horizontalOverflow || !popupFitsViewport) {
+ geometryFailures.push(scenario.state);
+ }
+
+ await writeFrame(
+ page,
+ scenario,
+ 'custom-open',
+ {expanded: true, dialogVisible: true, inlineAnchorTolerancePx: 4},
+ {
+ ...environment,
+ expanded: await custom.getAttribute('aria-expanded'),
+ dialogVisible: await dialog.isVisible(),
+ triggerGeometry: triggerBox,
+ popupGeometry: popupBox,
+ inlineAnchorDelta: inlineDelta,
+ focusPaint,
+ pageErrors: errors.length,
+ },
+ rows,
+ [],
+ );
+
+ await page.keyboard.press('Escape');
+ await expect(custom).toHaveAttribute('aria-expanded', 'false');
+ await expect(custom).toBeFocused();
+ }
+ expect(
+ geometryFailures,
+ 'Caller-rendered popup and matrix must stay inside the 320px viewport',
+ ).toEqual([]);
+});
+
+test('captures the narrow coarse-pointer path', async ({browser}) => {
+ const context = await browser.newContext({
+ viewport: NARROW,
+ deviceScaleFactor: 1,
+ hasTouch: true,
+ });
+ const page = await context.newPage();
+ const scenario: Scenario = {
+ state: 'narrow-light-ltr-coarse',
+ mode: 'light',
+ direction: 'ltr',
+ viewport: NARROW,
+ };
+
+ try {
+ const {errors} = await loadScenario(page, scenario);
+ const trigger = page.getByRole('combobox', {name: 'Selected medium'});
+ await trigger.tap();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const dialog = page.getByRole('dialog', {name: 'Selected medium'});
+ await expect(dialog).toBeVisible();
+ const popup = page.locator('.astryx-complex-selector-popup:visible');
+ const popupBox = await popup.boundingBox();
+ if (!popupBox) {
+ throw new Error(`${scenario.state}: popup has no layout box`);
+ }
+ const popupFitsViewport =
+ popupBox.x >= -1 &&
+ popupBox.x + popupBox.width <= scenario.viewport.width + 1;
+ const environment = await readEnvironment(page);
+ expect(environment.coarsePointer).toBe(true);
+ expect(environment.anyCoarsePointer).toBe(true);
+ expect(environment.viewport).toEqual(NARROW);
+ expect(environment.storyError).toBe(false);
+ expect(errors).toEqual([]);
+
+ const contrastRows = (await readContrastPairs(page)).map(pair => ({
+ screenshot: `ComplexSelector__${scenario.state}.png`,
+ theme: 'neutral',
+ mode: scenario.mode,
+ direction: scenario.direction,
+ viewport: scenario.viewport,
+ pointer: 'coarse',
+ ...pair,
+ }));
+ for (const pair of contrastRows) {
+ expect(pair.passed, `${scenario.state}: ${pair.part}`).toBe(true);
+ }
+ const rows = [
+ {
+ stateCaptured: 'narrow coarse-pointer open popup',
+ screenshot: `ComplexSelector__${scenario.state}.png`,
+ approvedRepresentation:
+ 'Expanded disclosure — touch activation with bounded popup',
+ tokenSignaturePresent: true,
+ matchesReference:
+ popupFitsViewport && !environment.horizontalOverflow ? 'yes' : 'no',
+ verdict:
+ popupFitsViewport && !environment.horizontalOverflow
+ ? 'pass'
+ : 'fail',
+ },
+ ];
+ await writeFrame(
+ page,
+ scenario,
+ 'interaction',
+ {pointer: 'coarse', expanded: true, dialogVisible: true},
+ {
+ ...environment,
+ expanded: await trigger.getAttribute('aria-expanded'),
+ dialogVisible: await dialog.isVisible(),
+ popupGeometry: popupBox,
+ pageErrors: errors.length,
+ },
+ rows,
+ contrastRows,
+ );
+ expect(
+ popupFitsViewport,
+ 'Coarse-pointer popup must stay inside the 320px viewport',
+ ).toBe(true);
+ expect(
+ environment.horizontalOverflow,
+ 'Coarse-pointer matrix must not overflow horizontally',
+ ).toBe(false);
+ } finally {
+ await context.close();
+ }
+});
diff --git a/packages/core/src/__tests__/DisabledTriggerFocus.a11y.chromium.spec.ts b/packages/core/src/__tests__/DisabledTriggerFocus.a11y.chromium.spec.ts
index 41efe13df2..05c1671401 100644
--- a/packages/core/src/__tests__/DisabledTriggerFocus.a11y.chromium.spec.ts
+++ b/packages/core/src/__tests__/DisabledTriggerFocus.a11y.chromium.spec.ts
@@ -37,7 +37,7 @@ const CASES = [
},
{
storyId: 'a11y-disabled-trigger-focus--complex-selector-trigger',
- role: 'button',
+ role: 'combobox',
name: 'View options',
},
] as const;
diff --git a/packages/lab/src/TransferList/TransferList.composition.test.tsx b/packages/lab/src/TransferList/TransferList.composition.test.tsx
index 2457463fcb..28d8865da0 100644
--- a/packages/lab/src/TransferList/TransferList.composition.test.tsx
+++ b/packages/lab/src/TransferList/TransferList.composition.test.tsx
@@ -125,7 +125,7 @@ function StagedColumnSelector({
}
function openSelector(): void {
- fireEvent.keyDown(screen.getByRole('button', {name: 'View options'}), {
+ fireEvent.keyDown(screen.getByRole('combobox', {name: 'View options'}), {
key: 'ArrowDown',
});
}
@@ -144,7 +144,7 @@ describe('ComplexSelector + TransferList composition', () => {
openSelector();
await waitFor(() => {
expect(
- screen.getByRole('button', {name: 'View options'}),
+ screen.getByRole('combobox', {name: 'View options'}),
).toHaveAttribute('aria-expanded', 'true');
});
@@ -173,7 +173,7 @@ describe('ComplexSelector + TransferList composition', () => {
const user = userEvent.setup();
const onCommit = vi.fn();
render(<StagedColumnSelector onCommit={onCommit} />);
- const trigger = screen.getByRole('button', {name: 'View options'});
+ const trigger = screen.getByRole('combobox', {name: 'View options'});
openSelector();
await user.click(
@@ -255,7 +255,7 @@ describe('ComplexSelector + TransferList composition', () => {
const user = userEvent.setup();
const onCommit = vi.fn();
render(<StagedColumnSelector onCommit={onCommit} />);
- const trigger = screen.getByRole('button', {name: 'View options'});
+ const trigger = screen.getByRole('combobox', {name: 'View options'});
openSelector();
await waitFor(() => {
diff --git a/packages/lab/src/TransferList/TransferListSelector.test.tsx b/packages/lab/src/TransferList/TransferListSelector.test.tsx
index 3889a12fc5..bfdc12a870 100644
--- a/packages/lab/src/TransferList/TransferListSelector.test.tsx
+++ b/packages/lab/src/TransferList/TransferListSelector.test.tsx
@@ -106,7 +106,7 @@ function Harness({
async function openSelector(
name = 'Visible fields',
): Promise<HTMLButtonElement> {
- const trigger = screen.getByRole('button', {
+ const trigger = screen.getByRole('combobox', {
name,
}) as HTMLButtonElement;
fireEvent.keyDown(trigger, {key: 'ArrowDown'});
@@ -416,7 +416,7 @@ describe('TransferListSelector', () => {
);
expect(
- screen.getByRole('button', {name: 'Visible fields'}),
+ screen.getByRole('combobox', {name: 'Visible fields'}),
).toHaveTextContent('3 selected');
});
@@ -462,7 +462,7 @@ describe('TransferListSelector', () => {
expect(fieldset).not.toContainElement(cancel);
expect(apply).toBeDisabled();
expect(
- screen.getByRole('button', {name: 'Visible fields'}),
+ screen.getByRole('combobox', {name: 'Visible fields'}),
).toHaveAttribute('aria-disabled', 'true');
view.rerender(
@@ -564,7 +564,7 @@ describe('TransferListSelector', () => {
screen.getByTestId('column-selector').closest('.astryx-complex-selector'),
).toHaveAttribute('data-size', 'sm');
expect(
- screen.getByRole('button', {name: 'Table columns'}),
+ screen.getByRole('combobox', {name: 'Table columns'}),
).toHaveTextContent('Customize columns');
expect(
screen.getByTestId('column-selector').closest('.astryx-field'),