An open source design system that's fully customizable and agent ready
TypeScript
feat(ComplexSelector): trigger render prop — hang the popup off a control the caller renders (#6827)
Christopher Chedeau45b691a8c9fe
diff --git a/.changeset/complex-selector-trigger.md b/.changeset/complex-selector-trigger.mdnew file mode 100644index 0000000000..af4e04f86d--- /dev/null+++ b/.changeset/complex-selector-trigger.md@@ -0,0 +1,14 @@+---+'@astryxdesign/core': patch+---++[feat] `ComplexSelector` can hang off a control the caller renders.++A new `renderTrigger` render prop renders the control the popup hangs off — a glyph+in a list row, a chip, an icon button — in place of the selector's own field+and button. Spread the given props onto it; the popup is anchored to it, keeps+its dialog label from `label`, opens on click or ArrowDown, and returns focus+to the control on close. The existing `handleRef` and `onOpenChange` work+unchanged beside it. Off by default; existing selectors are unchanged.++@vjeux @cixzhangdiff --git a/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs b/packages/core/src/ComplexSelector/ComplexSelector.doc.mjsindex 00404ad6d2..2e47e12c13 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs+++ b/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs@@ -177,6 +177,12 @@ export const docs = {description: 'Popup alignment along the placement axis.',default: "'start'",},+ {+ 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.",+ },{name: 'handleRef',type: 'React.Ref<ComplexSelectorHandle>',@@ -321,6 +327,8 @@ export const docsDense = {startIcon: 'Leading trigger icon.',placement: 'Popup placement.',alignment: 'Popup alignment.',+ renderTrigger:+ 'Caller-rendered opener replacing the field+button; spread the given props; popup anchored to it, labelled by label.',handleRef: 'Imperative open/close/toggle handle.',onOpenChange: 'Notified on every open and close, whatever caused it.',accessibility:diff --git a/packages/core/src/ComplexSelector/ComplexSelector.spec.md b/packages/core/src/ComplexSelector/ComplexSelector.spec.mdindex 826bf13076..607833213c 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.spec.md+++ b/packages/core/src/ComplexSelector/ComplexSelector.spec.md@@ -38,8 +38,10 @@ styling, targets, or public API.## Compatibility and migration- Released default preserved: `yes`-- Compatibility class: additive documentation only; runtime, DOM, styling,- targets, and public API remain unchanged+- 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@@ -68,17 +70,23 @@ Consumer migration instructions belong in consumer docs and release notes.## Public concepts-No new public concept is introduced. Consumer props and usage remain documented-in `ComplexSelector.doc.mjs`.+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`.## 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 |+| 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 |### Allowed variation@@ -107,8 +115,11 @@ in `ComplexSelector.doc.mjs`.## Accessibility contract-This draft does not change or extend ComplexSelector's existing field, trigger,-dialog, focus, or keyboard behavior.+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.## Design relationships@@ -160,12 +171,13 @@ content remains outside the owned anatomy inventory.## 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` |-| 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` |+| 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. Sourceinspection confirms that non-lazy `useLayer` keeps the Popup mounted while@@ -176,8 +188,13 @@ caller-owned ReactNode content.## Decision log-None. This draft records current facts and introduces no component-local design,-API, theming, or layer-system decision.+- **DEC-1 — Anchored mode through `renderTrigger`.** 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`. Rejected: an+ `anchorRef` plus a controlled `isOpen`, per the rule already written on+ `ComplexSelectorHandle`. Proposed in a pull request; FR5 becomes policy only+ when an owner approves this record.## Open questionsdiff --git a/packages/core/src/ComplexSelector/ComplexSelector.test.tsx b/packages/core/src/ComplexSelector/ComplexSelector.test.tsxindex be89e21d93..c2f9991100 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.test.tsx+++ b/packages/core/src/ComplexSelector/ComplexSelector.test.tsx@@ -451,6 +451,90 @@ describe('ComplexSelector popup theme target', () => {});});+describe('ComplexSelector trigger render prop', () => {+ it('renders the caller control instead of the field and button', () => {+ render(+ <ComplexSelector+ label="View options"+ value={[]}+ renderTrigger={props => (+ <button type="button" {...props}>+ Options+ </button>+ )}>+ {() => <button type="button">Apply</button>}+ </ComplexSelector>,+ );+ const opener = screen.getByRole('button', {name: 'Options'});+ expect(opener).toHaveAttribute('aria-haspopup', 'dialog');+ expect(opener).toHaveAttribute('aria-expanded', 'false');+ expect(opener).toHaveAttribute('aria-controls');+ expect(screen.queryByText('View options')).toBeNull();+ expect(screen.queryByRole('button', {name: 'View options'})).toBeNull();+ });++ it('opens against the caller control and returns focus to it on close', async () => {+ const user = userEvent.setup();+ const handleRef = React.createRef<ComplexSelectorHandle>();+ render(+ <ComplexSelector+ label="View options"+ value={[]}+ handleRef={handleRef}+ renderTrigger={props => (+ <button type="button" {...props}>+ Options+ </button>+ )}>+ {(_value, _onChange, close) => (+ <button type="button" onClick={close}>+ Apply+ </button>+ )}+ </ComplexSelector>,+ );+ const opener = screen.getByRole('button', {name: 'Options'});+ await user.click(opener);+ expect(opener).toHaveAttribute('aria-expanded', 'true');+ expect(handleRef.current?.isOpen()).toBe(true);+ const content = document.getElementById(+ opener.getAttribute('aria-controls')!,+ );+ expect(content).not.toBeNull();++ await user.click(screen.getByRole('button', {name: 'Apply', hidden: true}));+ await waitFor(() => {+ expect(opener).toHaveAttribute('aria-expanded', 'false');+ });+ // Focus return lands after the attribute flips, so it needs its own+ // wait: asserting it synchronously passes alone and fails in a full-file+ // run, where the surrounding work shifts the timing.+ await waitFor(() => {+ expect(opener).toHaveFocus();+ });+ });++ it('ArrowDown on the caller control opens the popup', async () => {+ render(+ <ComplexSelector+ label="View options"+ value={[]}+ renderTrigger={props => (+ <button type="button" {...props}>+ Options+ </button>+ )}>+ {() => <button type="button">Apply</button>}+ </ComplexSelector>,+ );+ const opener = screen.getByRole('button', {name: 'Options'});+ fireEvent.keyDown(opener, {key: 'ArrowDown'});+ await waitFor(() => {+ expect(opener).toHaveAttribute('aria-expanded', 'true');+ });+ });+});+describe('ComplexSelector onOpenChange', () => {function renderSelector(onOpenChange: (isOpen: boolean) => void) {render(diff --git a/packages/core/src/ComplexSelector/ComplexSelector.tsx b/packages/core/src/ComplexSelector/ComplexSelector.tsxindex 5bae9a3945..4d5027de30 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.tsx+++ b/packages/core/src/ComplexSelector/ComplexSelector.tsx@@ -191,6 +191,26 @@ export type ComplexSelectorVariant = 'input' | 'ghost';export type ComplexSelectorSize = 'sm' | 'md' | 'lg';+/**+ * Props the `renderTrigger` render prop hands to the control the caller+ * renders.+ * Spread them onto that control: it becomes the popup's anchor, the element+ * focus returns to, and the control that announces the popup's state.+ */+export interface ComplexSelectorRenderTriggerProps {+ /** Attaches the control as the popup's anchor and focus-return target. */+ ref: (element: HTMLElement | null) => void;+ /** The id the field would have given its own button. */+ id: string;+ onClick: (event: React.MouseEvent<HTMLElement>) => void;+ /** ArrowDown opens the popup, as it does on the built-in button. */+ onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;+ 'aria-haspopup': 'dialog';+ 'aria-expanded': boolean;+ 'aria-controls': string;+ 'aria-busy': boolean | undefined;+}+export interface ComplexSelectorRenderState {/** Whether the selector surface is open. */isOpen: boolean;@@ -286,6 +306,35 @@ export interface ComplexSelectorProps<Value> extends Omit<* state in the parent — the selector owns its visibility.*/handleRef?: React.Ref<ComplexSelectorHandle>;+ /**+ * 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 onto it; the popup is then anchored to that control and+ * still labelled by `label`. The field chrome (`Field`, status, spinner,+ * chevron) is not rendered; the caller owns the opener. Pair with+ * `handleRef` to open the popup from a keystroke elsewhere.+ *+ * Hover and pressed paint stay yours. The open state reaches your control+ * as `aria-expanded` on the given props, so style it from the rendered+ * attribute. A pressed look keyed to `:active` is not a substitute:+ * `:active` does not behave the same under a coarse pointer, which is why+ * menu rows drop coarse-pointer `:active` paint entirely.+ *+ * @example+ * ```+ * <ComplexSelector+ * label="Assignee"+ * renderTrigger={props => <IconButton icon="user" label="Assign" {...props} />}+ * />+ * ```+ *+ * @example+ * ```+ * // Styling the open state from the rendered attribute:+ * // .my-trigger[aria-expanded='true'] { background: var(--color-overlay-pressed); }+ * ```+ */+ renderTrigger?: (props: ComplexSelectorRenderTriggerProps) => ReactNode;/*** Called whenever the selector surface opens or closes, however it happened* — the trigger, the keyboard, a light dismiss, Escape, content that calls@@ -350,6 +399,7 @@ export function ComplexSelector<Value>({placement = 'below',alignment = 'start',handleRef,+ renderTrigger,onOpenChange,contentXstyle,xstyle,@@ -380,7 +430,7 @@ export function ComplexSelector<Value>({.filter((id): id is string => id != null).join(' ') || undefined;- const triggerRef = useRef<HTMLButtonElement>(null);+ const triggerRef = useRef<HTMLElement>(null);const [isPending, startTransition] = useTransition();const [optimisticValue, setOptimisticValue] = useOptimistic(value);@@ -478,6 +528,43 @@ export function ComplexSelector<Value>({</div>);+ const popup = popover.render(content, {+ placement,+ alignment,+ offset: spacingVars['--spacing-1'],+ xstyle: [styles.popover, layerAnimations[placement]],+ });++ if (renderTrigger != null) {+ // Anchor-only mode: the caller renders the opener and spreads these props+ // on it. No Field, no status, no chevron — the caller owns the control;+ // the selector owns the popup, its anchor, and focus return.+ const triggerProps: ComplexSelectorRenderTriggerProps = {+ ref: el => {+ popover.triggerRef(el);+ triggerRef.current = el;+ },+ id: triggerId,+ onClick: handleTriggerClick,+ onKeyDown: event => {+ if (event.key === 'ArrowDown' && !isOpen && !isDisabled) {+ event.preventDefault();+ popover.show();+ }+ },+ 'aria-haspopup': 'dialog',+ 'aria-expanded': isOpen,+ 'aria-controls': contentId,+ 'aria-busy': isBusy || undefined,+ };+ return (+ <>+ {renderTrigger(triggerProps)}+ {popup}+ </>+ );+ }+const selectorContent = (<><div@@ -513,7 +600,7 @@ export function ComplexSelector<Value>({)}>{isRenderable(startIconSlot) && startIconSlot}<button- ref={triggerRef}+ ref={triggerRef as React.Ref<HTMLButtonElement>}id={triggerId}type="button"aria-haspopup="dialog"@@ -554,12 +641,7 @@ export function ComplexSelector<Value>({/></div>- {popover.render(content, {- placement,- alignment,- offset: spacingVars['--spacing-1'],- xstyle: [styles.popover, layerAnimations[placement]],- })}+ {popup}</>);diff --git a/packages/core/src/ComplexSelector/index.ts b/packages/core/src/ComplexSelector/index.tsindex f3ebcfa6bc..b4fe7b2199 100644--- a/packages/core/src/ComplexSelector/index.ts+++ b/packages/core/src/ComplexSelector/index.ts@@ -15,5 +15,6 @@ export {type ComplexSelectorRenderState,type ComplexSelectorSize,type ComplexSelectorStatus,+ type ComplexSelectorRenderTriggerProps,type ComplexSelectorVariant,} from './ComplexSelector';