An open source design system that's fully customizable and agent ready
TypeScript
feat(core): expand ComplexSelector composition API (#4769)
Ernest01592f7b7361
diff --git a/.changeset/complex-selector-composition-api.md b/.changeset/complex-selector-composition-api.mdnew file mode 100644index 0000000000..a0548e4710--- /dev/null+++ b/.changeset/complex-selector-composition-api.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] ComplexSelector: support ghost toolbar triggers, leading icons, popup alignment, and an imperative `handleRef` (open/close/toggle/isOpen) for programmatic control.+@ernesttdiff --git a/.changeset/complex-selector-size-heights.md b/.changeset/complex-selector-size-heights.mdnew file mode 100644index 0000000000..d757db1db5--- /dev/null+++ b/.changeset/complex-selector-size-heights.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] ComplexSelector: honor the `sm`, `md`, and `lg` element-height tokens exactly.++@ernesttdiff --git a/apps/storybook/stories/ComplexSelector.stories.tsx b/apps/storybook/stories/ComplexSelector.stories.tsxindex 797fb63bea..ca87baf78c 100644--- a/apps/storybook/stories/ComplexSelector.stories.tsx+++ b/apps/storybook/stories/ComplexSelector.stories.tsx@@ -1,9 +1,24 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file ComplexSelector.stories.tsx+ * @input Uses React state, Astryx primitives, and ComplexSelector+ * @output Storybook examples for rich selector surfaces and trigger variants+ * @position Core component stories and visual integration coverage+ *+ * SYNC: When modified, update:+ * - /packages/core/src/ComplexSelector/ComplexSelector.tsx+ * - /packages/core/src/ComplexSelector/ComplexSelector.doc.mjs+ * - /packages/core/src/ComplexSelector/ComplexSelector.test.tsx+ */+import type {Meta, StoryObj} from '@storybook/react';-import {useEffect, useMemo, useState} from 'react';+import {useEffect, useMemo, useRef, useState} from 'react';import * as stylex from '@stylexjs/stylex';-import {ComplexSelector} from '@astryxdesign/core/ComplexSelector';+import {+ ComplexSelector,+ type ComplexSelectorHandle,+} from '@astryxdesign/core/ComplexSelector';import {Button} from '@astryxdesign/core/Button';import {Text} from '@astryxdesign/core/Text';import {TextInput} from '@astryxdesign/core/TextInput';@@ -34,7 +49,7 @@ const meta: Meta<typeof ComplexSelector> = {docs: {description: {component:- 'A high-level selector shell for rich custom content. The component owns the field, trigger, popover, focus restore, and async changeAction flow while consumers render the content. Custom content should use Astryx focus hooks where appropriate and be evaluated against WCAG 2.2.',+ 'A high-level selector shell for rich custom content. The component owns the field, trigger, popover, focus restore, and async changeAction flow while consumers render the content. Its sm, md, and lg triggers use the 28px, 32px, and 36px element-height tokens. Custom content should use Astryx focus hooks where appropriate and be evaluated against WCAG 2.2.',},},},@@ -373,6 +388,20 @@ const styles = stylex.create({color: colorVars['--color-text-secondary'],textAlign: 'center',},+ toolbarDemo: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'flex-end',+ gap: spacingVars['--spacing-1'],+ width: 360,+ padding: spacingVars['--spacing-1'],+ borderRadius: radiusVars['--radius-container'],+ backgroundColor: colorVars['--color-background-muted'],+ },+ toolbarContent: {+ width: 280,+ padding: spacingVars['--spacing-3'],+ },});function formatFruitValue(value: FruitValue) {@@ -728,3 +757,69 @@ export const CategoryTreeSelector: Story = {},},};++type ViewDensity = 'Comfortable' | 'Compact';++export const ControlledToolbarTrigger: Story = {+ name: 'Controlled toolbar trigger',+ render: () => {+ const [density, setDensity] = useState<ViewDensity>('Comfortable');+ const selectorRef = useRef<ComplexSelectorHandle>(null);++ return (+ <div {...stylex.props(styles.toolbarDemo)}>+ <Button+ label="Open options externally"+ variant="ghost"+ size="sm"+ onClick={() => selectorRef.current?.toggle()}+ />+ <ComplexSelector<ViewDensity>+ label="View options"+ isLabelHidden+ value={density}+ onChange={setDensity}+ triggerLabel={`Density: ${density}`}+ variant="ghost"+ startIcon="viewColumns"+ alignment="end"+ handleRef={selectorRef}+ contentXstyle={styles.toolbarContent}>+ {(selectedDensity, onChange, close) => (+ <VStack gap={3}>+ <Text type="supporting" color="secondary">+ The selector owns visibility. An external control drives it+ imperatively via handleRef; choosing a density commits the value+ and closes the surface.+ </Text>+ <HStack gap={2}>+ {(['Comfortable', 'Compact'] as const).map(option => (+ <Button+ key={option}+ label={option}+ size="sm"+ variant={+ selectedDensity === option ? 'primary' : 'secondary'+ }+ onClick={() => {+ onChange(option);+ close();+ }}+ />+ ))}+ </HStack>+ </VStack>+ )}+ </ComplexSelector>+ </div>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'A compact toolbar composition using the ghost trigger, a leading icon, end-aligned content, and an external control that opens the selector imperatively through its handleRef. The selector still owns its own visibility, focus restoration, and light dismiss.',+ },+ },+ },+};diff --git a/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorDeadlinePicker.doc.mjs b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorDeadlinePicker.doc.mjsnew file mode 100644index 0000000000..831335e50e--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorDeadlinePicker.doc.mjs@@ -0,0 +1,20 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'ComplexSelector',+ name: 'ComplexSelector — Deadline Picker',+ displayName: 'Complex Selector — Deadline Picker',+ description:+ 'A multi-step deadline field: pick a preset like Today or Next week, or switch to a custom date and time before applying. The popup stays open until the user commits, so the content owns the Apply action.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: [+ 'ComplexSelector',+ 'RadioList',+ 'DateInput',+ 'TimeInput',+ 'Button',+ ],+};diff --git a/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorDeadlinePicker.tsx b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorDeadlinePicker.tsxnew file mode 100644index 0000000000..15afc5169a--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorDeadlinePicker.tsx@@ -0,0 +1,87 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState} from 'react';+import {ComplexSelector} from '@astryxdesign/core/ComplexSelector';+import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';+import {DateInput} from '@astryxdesign/core/DateInput';+import {TimeInput} from '@astryxdesign/core/TimeInput';+import {Button} from '@astryxdesign/core/Button';+import {VStack} from '@astryxdesign/core/Layout';++type ISODate =+ `${number}${number}${number}${number}-${number}${number}-${number}${number}`;+type ISOTime = string & {readonly __brand: 'ISOTimeString'};++interface Deadline {+ preset: 'today' | 'next-week' | 'custom';+ date: ISODate;+ time: ISOTime;+}++const presetLabels: Record<Deadline['preset'], string> = {+ today: 'Today',+ 'next-week': 'Next week',+ custom: 'Custom date',+};++function formatDeadline(value: Deadline) {+ if (value.preset === 'custom') {+ return `${value.date} at ${value.time}`;+ }+ return presetLabels[value.preset];+}++export default function ComplexSelectorDeadlinePicker() {+ const [value, setValue] = useState<Deadline>({+ preset: 'today',+ date: '2026-04-06' as ISODate,+ time: '17:00' as ISOTime,+ });++ return (+ <ComplexSelector<Deadline>+ label="Deadline"+ description="Choose a preset or set a custom date and time."+ value={value}+ onChange={setValue}+ triggerLabel={formatDeadline(value)}+ style={{width: 320}}>+ {(selectedValue, onChange, close) => {+ const set = (patch: Partial<Deadline>) =>+ onChange({...selectedValue, ...patch});++ return (+ <VStack gap={4} style={{width: 320}}>+ <RadioList+ label="When is it due?"+ value={selectedValue.preset}+ onChange={preset => set({preset: preset as Deadline['preset']})}>+ <RadioListItem label="Today" value="today" />+ <RadioListItem label="Next week" value="next-week" />+ <RadioListItem label="Custom date" value="custom" />+ </RadioList>++ {selectedValue.preset === 'custom' && (+ <VStack gap={3}>+ <DateInput+ label="Date"+ value={selectedValue.date}+ onChange={date => date && set({date})}+ />+ <TimeInput+ label="Time"+ value={selectedValue.time}+ onChange={time => time && set({time})}+ />+ </VStack>+ )}++ <Button label="Apply" variant="primary" onClick={close} />+ </VStack>+ );+ }}+ </ComplexSelector>+ );+}diff --git a/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorShowcase.doc.mjsnew file mode 100644index 0000000000..90ceb8b7dd--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorShowcase.doc.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'ComplexSelector',+ name: 'ComplexSelector',+ displayName: 'Complex Selector',+ description:+ 'A two-axis picker: choose a fruit and a ripeness level from one control. ComplexSelector owns the trigger, popover, and focus restore while the custom grid owns its keyboard semantics.',+ isReady: true,+ aspectRatio: 1,+ isShowcase: true,+ componentsUsed: ['ComplexSelector', 'Text'],+};diff --git a/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorShowcase.tsx b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorShowcase.tsxnew file mode 100644index 0000000000..f7942882a8--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorShowcase.tsx@@ -0,0 +1,199 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useEffect, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {ComplexSelector} from '@astryxdesign/core/ComplexSelector';+import {Text} from '@astryxdesign/core/Text';+import {useGridFocus} from '@astryxdesign/core/hooks';+import {+ borderVars,+ colorVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';++type Fruit = 'Apple' | 'Pear' | 'Peach' | 'Plum';+type Ripeness = 'Crisp' | 'Tender' | 'Juicy' | 'Peak';++interface FruitValue {+ fruit: Fruit;+ ripeness: Ripeness;+}++const fruits: Array<{id: Fruit; emoji: string; description: string}> = [+ {id: 'Apple', emoji: '🍎', description: 'Bright and balanced'},+ {id: 'Pear', emoji: '🍐', description: 'Soft floral sweetness'},+ {id: 'Peach', emoji: '🍑', description: 'Round summer flavor'},+ {id: 'Plum', emoji: '🟣', description: 'Jammy and tart'},+];++const ripenessLevels: Array<{+ id: Ripeness;+ shortLabel: string;+ description: string;+}> = [+ {id: 'Crisp', shortLabel: 'C', description: 'Snappy bite'},+ {id: 'Tender', shortLabel: 'T', description: 'Easy bite'},+ {id: 'Juicy', shortLabel: 'J', description: 'Full juice'},+ {id: 'Peak', shortLabel: 'P', description: 'Most intense'},+];++const GRID_CELL_SELECTOR = '[role="gridcell"]';++const styles = stylex.create({+ grid: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-1'],+ minWidth: 280,+ },+ row: {+ display: 'grid',+ gridTemplateColumns: 'minmax(150px, 1fr) repeat(4, 44px)',+ alignItems: 'center',+ columnGap: spacingVars['--spacing-1'],+ },+ rowHeader: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ textAlign: 'start',+ minWidth: 0,+ },+ emoji: {+ fontSize: 18,+ flexShrink: 0,+ },+ fruitText: {+ display: 'flex',+ flexDirection: 'column',+ minWidth: 0,+ },+ cell: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ height: 36,+ borderWidth: borderVars['--border-width'],+ borderStyle: 'solid',+ borderColor: colorVars['--color-border'],+ borderRadius: radiusVars['--radius-container'],+ backgroundColor: colorVars['--color-background-card'],+ color: colorVars['--color-text-secondary'],+ fontFamily: 'inherit',+ cursor: 'pointer',+ ':hover': {+ '@media (hover: hover)': {+ borderColor: colorVars['--color-border-emphasized'],+ color: colorVars['--color-text-primary'],+ },+ },+ },+ cellSelected: {+ borderColor: colorVars['--color-accent'],+ backgroundColor: colorVars['--color-accent'],+ color: colorVars['--color-on-accent'],+ },+});++function FruitRipenessGrid({+ value,+ onChange,+}: {+ value: FruitValue;+ onChange: (value: FruitValue) => void;+}) {+ const {gridRef, handleKeyDown, handleFocus, focusCell} =+ useGridFocus<HTMLDivElement>({+ columns: ripenessLevels.length,+ cellSelector: GRID_CELL_SELECTOR,+ hasRovingTabIndex: true,+ });++ useEffect(() => {+ const rowIndex = fruits.findIndex(f => f.id === value.fruit);+ const columnIndex = ripenessLevels.findIndex(l => l.id === value.ripeness);+ requestAnimationFrame(() => {+ focusCell(+ rowIndex >= 0 && columnIndex >= 0+ ? rowIndex * ripenessLevels.length + columnIndex+ : 0,+ );+ });+ }, [focusCell, value]);++ return (+ <div+ ref={gridRef}+ role="grid"+ aria-label="Fruit ripeness choices"+ onKeyDown={handleKeyDown}+ onFocus={handleFocus}+ {...stylex.props(styles.grid)}>+ {fruits.map(fruit => (+ <div key={fruit.id} role="row" {...stylex.props(styles.row)}>+ <div role="rowheader" {...stylex.props(styles.rowHeader)}>+ <span aria-hidden="true" {...stylex.props(styles.emoji)}>+ {fruit.emoji}+ </span>+ <span {...stylex.props(styles.fruitText)}>+ <Text type="body">{fruit.id}</Text>+ <Text type="supporting" color="secondary">+ {fruit.description}+ </Text>+ </span>+ </div>+ {ripenessLevels.map(level => {+ const isSelected =+ value.fruit === fruit.id && value.ripeness === level.id;+ return (+ <button+ key={`${fruit.id}-${level.id}`}+ type="button"+ role="gridcell"+ aria-label={`${fruit.id}, ${level.id}: ${level.description}`}+ aria-selected={isSelected || undefined}+ tabIndex={isSelected ? 0 : -1}+ onClick={() => onChange({fruit: fruit.id, ripeness: level.id})}+ {...stylex.props(+ styles.cell,+ isSelected && styles.cellSelected,+ )}>+ {level.shortLabel}+ </button>+ );+ })}+ </div>+ ))}+ </div>+ );+}++export default function ComplexSelectorShowcase() {+ const [value, setValue] = useState<FruitValue>({+ fruit: 'Apple',+ ripeness: 'Juicy',+ });++ return (+ <ComplexSelector<FruitValue>+ label="Fruit blend"+ description="Choose a fruit and ripeness in one control. Arrow keys move across the grid."+ value={value}+ onChange={setValue}+ triggerLabel={`${value.fruit} · ${value.ripeness}`}+ style={{width: 280}}>+ {(selectedValue, onChange, close) => (+ <FruitRipenessGrid+ value={selectedValue}+ onChange={nextValue => {+ onChange(nextValue);+ close();+ }}+ />+ )}+ </ComplexSelector>+ );+}diff --git a/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorTreeSearch.doc.mjs b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorTreeSearch.doc.mjsnew file mode 100644index 0000000000..e453ee6eba--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorTreeSearch.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'ComplexSelector',+ name: 'ComplexSelector — Tree Search',+ displayName: 'Complex Selector — Tree Search',+ description:+ 'A destination picker that combines a search field with a TreeList hierarchy. TreeList owns tree keyboard navigation; ComplexSelector owns the trigger, popover, and focus restore. Selecting a folder closes the popup.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['ComplexSelector', 'TextInput', 'TreeList'],+};diff --git a/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorTreeSearch.tsx b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorTreeSearch.tsxnew file mode 100644index 0000000000..f1c493d24d--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/ComplexSelector/ComplexSelectorTreeSearch.tsx@@ -0,0 +1,188 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useMemo, useState} from 'react';+import {ComplexSelector} from '@astryxdesign/core/ComplexSelector';+import {TextInput} from '@astryxdesign/core/TextInput';+import {TreeList, type TreeListItemData} from '@astryxdesign/core/TreeList';+import {Text} from '@astryxdesign/core/Text';+import {VStack} from '@astryxdesign/core/Layout';++interface DestinationNode {+ id: string;+ label: string;+ path: string;+ children?: DestinationNode[];+}++interface Destination {+ id: string;+ label: string;+ path: string;+}++const destinationTree: DestinationNode[] = [+ {+ id: 'workspace',+ label: 'Workspace',+ path: '/Workspace',+ children: [+ {+ id: 'research',+ label: 'Research',+ path: '/Workspace/Research',+ children: [+ {+ id: 'field-notes',+ label: 'Field notes',+ path: '/Workspace/Research/Field notes',+ },+ {+ id: 'interviews',+ label: 'Interviews',+ path: '/Workspace/Research/Interviews',+ },+ ],+ },+ {+ id: 'roadmap',+ label: 'Roadmap',+ path: '/Workspace/Roadmap',+ },+ ],+ },+ {+ id: 'teams',+ label: 'Teams',+ path: '/Teams',+ children: [+ {+ id: 'design-systems',+ label: 'Design systems',+ path: '/Teams/Design systems',+ children: [+ {+ id: 'accessibility',+ label: 'Accessibility',+ path: '/Teams/Design systems/Accessibility',+ },+ ],+ },+ ],+ },+];++function matches(node: DestinationNode, query: string): boolean {+ if (node.label.toLowerCase().includes(query)) {+ return true;+ }+ return (node.children ?? []).some(child => matches(child, query));+}++function filterTree(+ nodes: DestinationNode[],+ query: string,+): DestinationNode[] {+ if (!query) {+ return nodes;+ }+ return nodes+ .filter(node => matches(node, query))+ .map(node => ({+ ...node,+ children: node.children ? filterTree(node.children, query) : undefined,+ }));+}++function toItems(+ nodes: DestinationNode[],+ selectedId: string,+ onSelect: (value: Destination) => void,+): TreeListItemData[] {+ return nodes.map(node => {+ const hasChildren = (node.children ?? []).length > 0;+ return {+ id: node.id,+ label: node.label,+ isSelected: node.id === selectedId,+ isExpanded: true,+ onClick: hasChildren+ ? undefined+ : () => onSelect({id: node.id, label: node.label, path: node.path}),+ children: hasChildren+ ? toItems(node.children ?? [], selectedId, onSelect)+ : undefined,+ };+ });+}++function DestinationSearch({+ value,+ onChange,+ close,+}: {+ value: Destination;+ onChange: (value: Destination) => void;+ close: () => void;+}) {+ const [query, setQuery] = useState('');+ const items = useMemo(+ () =>+ toItems(+ filterTree(destinationTree, query.toLowerCase()),+ value.id,+ next => {+ onChange(next);+ close();+ },+ ),+ [query, value.id, onChange, close],+ );++ return (+ <VStack gap={3} style={{width: 360}}>+ <TextInput+ label="Search destinations"+ isLabelHidden+ value={query}+ onChange={setQuery}+ hasClear+ placeholder="Search folders or teams"+ />+ {items.length > 0 ? (+ <TreeList items={items} density="compact" />+ ) : (+ <Text type="supporting" color="secondary">+ No matching destinations.+ </Text>+ )}+ </VStack>+ );+}++export default function ComplexSelectorTreeSearch() {+ const [value, setValue] = useState<Destination>({+ id: 'accessibility',+ label: 'Accessibility',+ path: '/Teams/Design systems/Accessibility',+ });++ return (+ <ComplexSelector<Destination>+ label="Destination"+ description="Search and browse nested folders."+ value={value}+ onChange={setValue}+ triggerLabel={value.path}+ style={{width: 360}}>+ {(selectedValue, onChange, close) => (+ <DestinationSearch+ value={selectedValue}+ onChange={onChange}+ close={close}+ />+ )}+ </ComplexSelector>+ );+}diff --git a/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs b/packages/core/src/ComplexSelector/ComplexSelector.doc.mjsindex 3ef6f8af94..ff93f792e3 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs+++ b/packages/core/src/ComplexSelector/ComplexSelector.doc.mjs@@ -1,5 +1,14 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file ComplexSelector.doc.mjs+ * @input ComplexSelector public API and composition contract+ * @output Exports full and dense component documentation+ * @position Core documentation consumed by CLI and Storybook autodocs+ *+ * SYNC: When modified, update ComplexSelector.tsx, tests, and stories.+ */+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */export const docs = {@@ -19,7 +28,10 @@ export const docs = {],theming: {targets: [- {className: 'astryx-complex-selector', visualProps: ['size', 'status']},+ {+ className: 'astryx-complex-selector',+ visualProps: ['variant', 'size', 'status'],+ },{className: 'astryx-complex-selector-indicator-icon',states: ['state'],@@ -32,7 +44,7 @@ export const docs = {name: 'ComplexSelector',displayName: 'Complex Selector',description:- 'A field and dialog-popover shell for custom selector content.',+ 'An input or toolbar trigger and dialog-popover shell for custom selector content.',props: [{name: 'label',@@ -93,9 +105,21 @@ export const docs = {{name: 'size',type: "'sm' | 'md' | 'lg'",- description: 'Trigger and field size.',+ description: 'Exact trigger height: sm 28px, md 32px, or lg 36px.',default: "'md'",},+ {+ name: 'variant',+ type: "'input' | 'ghost'",+ description:+ 'Visual trigger style. Input is the bordered form treatment; ghost matches toolbar buttons.',+ default: "'input'",+ },+ {+ name: 'startIcon',+ type: 'ReactNode | IconType',+ description: 'Icon displayed at the start of the trigger.',+ },{name: 'width',type: 'SizeValue',@@ -107,6 +131,18 @@ export const docs = {description: 'Popup placement.',default: "'below'",},+ {+ name: 'alignment',+ type: "'start' | 'center' | 'end'",+ description: 'Popup alignment along the placement axis.',+ default: "'start'",+ },+ {+ name: 'handleRef',+ type: 'React.Ref<ComplexSelectorHandle>',+ description:+ 'Imperative handle for programmatic control. Exposes open(), close(), toggle(), and isOpen().',+ },{name: 'contentXstyle',type: 'StyleXStyles',@@ -119,6 +155,16 @@ export const docs = {description:'Use ComplexSelector when a selection needs richer custom content than a Selector option row. It is intentionally one component: ComplexSelector owns the field, trigger, popover, focus restore, and changeAction flow, while the content render prop owns the selector-specific accessible structure.',bestPractices: [+ {+ guidance: true,+ description:+ 'Use variant="ghost" with a startIcon when the selector is triggered from a toolbar. Use alignment="end" when a wide surface should align its end edge to the trigger.',+ },+ {+ guidance: true,+ description:+ 'For staged editors, keep draft state in the composed content and call the provided onChange helper only from Apply. Cancel or dismiss without committing.',+ },{guidance: true,description:@@ -164,7 +210,7 @@ export const docsDense = {group: 'Selector',category: 'Data Input',description:- 'Field+dialog-popover shell for rich custom selectors. Content gets value/onChange/close/state; content owns semantics. Use focus hooks and evaluate custom content against WCAG 2.2.',+ 'Input/ghost trigger + dialog-popover shell for rich custom selectors. Content gets value/onChange/close/state; content owns semantics. Use focus hooks and evaluate custom content against WCAG 2.2.',usage: {description:'Use when a selection needs richer custom content than a Selector row. One component: it owns field, trigger, popover, focus restore, and changeAction; the render prop owns the selector-specific accessible structure.',@@ -211,10 +257,13 @@ export const docsDense = {value: 'Controlled value.',onChange: 'Commit value.',changeAction: 'Async action after onChange; drives optimistic value/busy.',- children:- 'Render custom dialog content from (value,onChange,close,state).',+ children: 'Render custom dialog content from (value,onChange,close,state).',triggerLabel: 'Closed trigger label/content.',+ variant: 'input for forms; ghost for toolbar triggers.',+ startIcon: 'Leading trigger icon.',placement: 'Popup placement.',+ alignment: 'Popup alignment.',+ handleRef: 'Imperative open/close/toggle handle.',accessibility:'Custom content must provide its own accessible structure. Use focus hooks and evaluate against WCAG 2.2.',},diff --git a/packages/core/src/ComplexSelector/ComplexSelector.test.tsx b/packages/core/src/ComplexSelector/ComplexSelector.test.tsxindex 57bd7e4916..079a234514 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.test.tsx+++ b/packages/core/src/ComplexSelector/ComplexSelector.test.tsx@@ -2,17 +2,45 @@/*** @file ComplexSelector.test.tsx- * @input Uses vitest, Testing Library, user-event- * @output Unit tests for ComplexSelector- * @position Tests; validates custom content, async actions, and dialog composition+ * @input Uses vitest, Testing Library, user-event, and ComplexSelector+ * @output Unit tests for selection, trigger variants, positioning, and the imperative handle+ * @position Tests; validates the ComplexSelector public interaction contract** SYNC: When ComplexSelector.tsx API changes, update these tests.*/-import {describe, expect, it, vi} from 'vitest';-import {render, screen, waitFor} from '@testing-library/react';+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 {ComplexSelector} from './ComplexSelector';+import {ComplexSelector, type ComplexSelectorHandle} from './ComplexSelector';++const originalMatches = HTMLElement.prototype.matches;++// Mock the Popover API, which jsdom does not implement.+beforeEach(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ this.setAttribute('popover-open', '');+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'open'});+ this.dispatchEvent(event);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ this.removeAttribute('popover-open');+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'closed'});+ this.dispatchEvent(event);+ });+ Object.defineProperty(HTMLElement.prototype, 'matches', {+ configurable: true,+ value: function (this: HTMLElement, selector: string): boolean {+ if (selector === ':popover-open') {+ return this.hasAttribute('popover-open');+ }+ return originalMatches.call(this, selector);+ },+ });+});type FruitValue = {fruit: 'Apple' | 'Banana';@@ -83,6 +111,35 @@ function FruitComplexSelector({}describe('ComplexSelector', () => {+ it('defaults to md and reflects explicit trigger sizes', () => {+ const {container, rerender} = render(+ <ComplexSelector label="Fruit blend" value="Apple">+ {() => <div>Options</div>}+ </ComplexSelector>,+ );++ const getSelector = () =>+ container.querySelector('.astryx-complex-selector');++ expect(getSelector()).toHaveAttribute('data-size', 'md');++ rerender(+ <ComplexSelector label="Fruit blend" value="Apple" size="sm">+ {() => <div>Options</div>}+ </ComplexSelector>,+ );++ expect(getSelector()).toHaveAttribute('data-size', 'sm');++ rerender(+ <ComplexSelector label="Fruit blend" value="Apple" size="lg">+ {() => <div>Options</div>}+ </ComplexSelector>,+ );++ expect(getSelector()).toHaveAttribute('data-size', 'lg');+ });+it('renders custom content with value and commits through onChange', async () => {const user = userEvent.setup();const onChange = vi.fn();@@ -174,6 +231,140 @@ describe('ComplexSelector', () => {await user.click(screen.getByRole('button', {name: 'Done', ...h}));expect(trigger).toHaveAttribute('aria-expanded', 'false');});++ it('renders a ghost toolbar trigger with a start icon', () => {+ const {container} = render(+ <ComplexSelector+ label="View options"+ value={['name']}+ variant="ghost"+ startIcon="viewColumns"+ status={{type: 'warning', message: 'Unsaved changes'}}+ data-testid="view-options">+ {() => <div>Columns</div>}+ </ComplexSelector>,+ );++ expect(container.querySelector('.astryx-complex-selector')).toHaveAttribute(+ 'data-variant',+ 'ghost',+ );+ expect(container.querySelector('.astryx-field-status')).toHaveAttribute(+ 'data-variant',+ 'detached',+ );+ expect(+ screen.getByTestId('view-options').querySelectorAll('svg'),+ ).toHaveLength(2);+ });++ it('supports end-aligned popup positioning', () => {+ render(+ <ComplexSelector label="View options" value={[]} alignment="end">+ {() => <div>Columns</div>}+ </ComplexSelector>,+ );++ const popover = screen+ .getByRole('dialog', {hidden: true})+ .closest('[popover]');+ expect(popover?.getAttribute('style')).toContain(+ 'position-area: self-block-end span-self-inline-start',+ );+ });++ it('exposes imperative open, close, toggle, and isOpen via handleRef', async () => {+ const handleRef = React.createRef<ComplexSelectorHandle>();+ render(+ <ComplexSelector label="View options" value={[]} handleRef={handleRef}>+ {() => <button type="button">Apply</button>}+ </ComplexSelector>,+ );+ const trigger = screen.getByRole('button', {name: 'View options'});+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(handleRef.current?.isOpen()).toBe(false);++ act(() => {+ handleRef.current?.open();+ });+ await waitFor(() => {+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });+ expect(handleRef.current?.isOpen()).toBe(true);++ act(() => {+ handleRef.current?.close();+ });+ await waitFor(() => {+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });+ expect(handleRef.current?.isOpen()).toBe(false);++ act(() => {+ handleRef.current?.toggle();+ });+ await waitFor(() => {+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });++ act(() => {+ handleRef.current?.toggle();+ });+ await waitFor(() => {+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('does not open via the imperative handle when disabled', async () => {+ const handleRef = React.createRef<ComplexSelectorHandle>();+ render(+ <ComplexSelector+ label="View options"+ value={[]}+ isDisabled+ handleRef={handleRef}>+ {() => <button type="button">Apply</button>}+ </ComplexSelector>,+ );+ const trigger = screen.getByRole('button', {name: 'View options'});++ act(() => {+ handleRef.current?.open();+ });+ act(() => {+ handleRef.current?.toggle();+ });+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(handleRef.current?.isOpen()).toBe(false);+ });++ it('does not reopen from the trigger click that follows light dismiss', async () => {+ const user = userEvent.setup();+ render(+ <ComplexSelector label="View options" value={[]}>+ {() => <button type="button">Apply</button>}+ </ComplexSelector>,+ );+ const trigger = screen.getByRole('button', {name: 'View options'});++ await user.click(trigger);+ const popover = screen+ .getByRole('dialog', {hidden: true})+ .closest('[popover]');+ expect(popover).not.toBeNull();++ const closeEvent = new Event('toggle');+ Object.defineProperty(closeEvent, 'newState', {value: 'closed'});+ fireEvent(popover as HTMLElement, closeEvent);+ expect(trigger).toHaveAttribute('aria-expanded', 'false');++ const showCallCount = vi.mocked(HTMLElement.prototype.showPopover).mock+ .calls.length;+ fireEvent.click(trigger);+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(+ showCallCount,+ );+ });});describe('ComplexSelector popup theme target', () => {diff --git a/packages/core/src/ComplexSelector/ComplexSelector.tsx b/packages/core/src/ComplexSelector/ComplexSelector.tsxindex a1db1da004..6dcd3d19ae 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.tsx+++ b/packages/core/src/ComplexSelector/ComplexSelector.tsx@@ -4,8 +4,8 @@/*** @file ComplexSelector.tsx- * @input Uses React, StyleX, Field, usePopover- * @output Exports ComplexSelector component for custom selector surfaces+ * @input Uses React, StyleX, Field, Icon slots, Layer positioning, and usePopover+ * @output Exports a rich-selector shell with exact token-sized input and ghost triggers, plus an imperative open/close handle* @position Core implementation; consumed by index.ts** SYNC: When modified, update:@@ -13,12 +13,15 @@* - /packages/core/src/ComplexSelector/ComplexSelector.test.tsx* - /packages/core/src/ComplexSelector/index.ts* - /apps/storybook/stories/ComplexSelector.stories.tsx+ * - /packages/cli/assets/templates/blocks/components/ComplexSelector/ (showcase blocks)*/import React, {useCallback,useId,+ useImperativeHandle,useOptimistic,+ useRef,useTransition,type ReactNode,} from 'react';@@ -26,15 +29,17 @@ import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import {Field, inputWrapperStyles, type FieldStatusVariant} from '../Field';-import {Icon} from '../Icon';+import {Icon, renderIconSlot, type IconType} from '../Icon';import {Spinner} from '../Spinner';import {useTranslator} from '../i18n';import {layerAnimations} from '../Layer/layerAnimations.stylex';+import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';import {usePopover} from '../Popover/usePopover';import {colorVars,durationVars,easeVars,+ fontWeightVars,radiusVars,sizeVars,spacingVars,@@ -99,6 +104,39 @@ const styles = stylex.create({placeholder: {color: colorVars['--color-text-secondary'],},+ triggerGhost: {+ width: 'auto',+ borderWidth: 0,+ backgroundColor: 'transparent',+ backgroundImage: {+ default: null,+ ':hover': {+ '@media (hover: hover)': `linear-gradient(${colorVars['--color-overlay-hover']}, ${colorVars['--color-overlay-hover']})`,+ },+ ':active': `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`,+ },+ boxShadow: {+ default: 'none',+ ':hover:not(:focus-within)': {+ '@media (hover: hover)': 'none',+ },+ ':focus-within': 'none',+ },+ fontWeight: fontWeightVars['--font-weight-medium'],+ transitionProperty:+ 'background-image, background-color, color, opacity, transform',+ transform: {+ default: 'scale(1)',+ ':active': 'scale(0.98)',+ },+ },+ triggerGhostDisabled: {+ backgroundImage: 'none',+ transform: {+ default: 'none',+ ':active': 'none',+ },+ },// Only what Icon does not already provide: `sm` gives the 16px box and// `color="secondary"` the color, but the glyph still must not shrink inside// the flex trigger.@@ -129,19 +167,21 @@ const styles = stylex.create({padding: spacingVars['--spacing-3'],},sm: {- minHeight: sizeVars['--size-element-sm'],+ height: sizeVars['--size-element-sm'],},md: {- minHeight: sizeVars['--size-element-md'],+ height: sizeVars['--size-element-md'],},lg: {- minHeight: sizeVars['--size-element-lg'],+ height: sizeVars['--size-element-lg'],},disabled: {cursor: 'not-allowed',},});+export type ComplexSelectorVariant = 'input' | 'ghost';+export type ComplexSelectorSize = 'sm' | 'md' | 'lg';export interface ComplexSelectorRenderState {@@ -155,6 +195,25 @@ export interface ComplexSelectorRenderState {contentId: string;}+/**+ * Imperative control surface for ComplexSelector, accessed via the `handleRef`+ * prop. Methods drive the same popover machinery as the built-in trigger, so+ * they respect focus restoration, light dismiss, and Escape. Prefer these+ * callbacks over mirroring open state in the parent — the selector owns its+ * visibility, and imperative calls avoid the focus-management pitfalls of+ * syncing an external `isOpen` prop.+ */+export interface ComplexSelectorHandle {+ /** Open the selector surface. No-op when disabled or already open. */+ open(): void;+ /** Close the selector surface. Restores focus to the trigger. */+ close(): void;+ /** Toggle the selector surface open or closed. */+ toggle(): void;+ /** Whether the selector surface is currently open. Reads live state. */+ isOpen(): boolean;+}+export interface ComplexSelectorStatus {type: 'warning' | 'error' | 'success';message?: string;@@ -203,10 +262,22 @@ export interface ComplexSelectorProps<Value> extends Omit<labelTooltip?: string;/** Trigger and field size. */size?: ComplexSelectorSize;+ /** Visual trigger style. Ghost matches toolbar buttons. */+ variant?: ComplexSelectorVariant;+ /** Icon displayed at the start of the trigger. */+ startIcon?: ReactNode | IconType;/** Width of the field. */width?: SizeValue;/** Popup placement. */- placement?: 'above' | 'below' | 'start' | 'end';+ placement?: LayerPlacement;+ /** Popup alignment along the placement axis. */+ alignment?: LayerAlignment;+ /**+ * Imperative handle for programmatic open/close control. Exposes open,+ * close, toggle, and the isOpen query. Use this instead of mirroring open+ * state in the parent — the selector owns its visibility.+ */+ handleRef?: React.Ref<ComplexSelectorHandle>;/** StyleX styles for the popup content container. */contentXstyle?: StyleXStyles;/** Test ID for the trigger container. */@@ -258,8 +329,12 @@ export function ComplexSelector<Value>({statusVariant = 'attached',labelTooltip,size = 'md',+ variant = 'input',+ startIcon,width,placement = 'below',+ alignment = 'start',+ handleRef,contentXstyle,xstyle,className,@@ -270,6 +345,10 @@ export function ComplexSelector<Value>({}: ComplexSelectorProps<Value>) {const t = useTranslator();const placeholder = placeholderFromProps ?? t('@astryx.selector.placeholder');+ const effectiveStatusVariant =+ variant === 'ghost' && statusVariant === 'attached'+ ? 'detached'+ : statusVariant;const triggerId = useId();const labelId = useId();@@ -284,24 +363,67 @@ export function ComplexSelector<Value>({.filter((id): id is string => id != null).join(' ') || undefined;+ const triggerRef = useRef<HTMLButtonElement>(null);+ const lastHideTimeRef = useRef(0);+const [isPending, startTransition] = useTransition();const [optimisticValue, setOptimisticValue] = useOptimistic(value);const isBusy = isLoading || isPending;+ const handlePopoverHide = useCallback(() => {+ lastHideTimeRef.current = Date.now();+ triggerRef.current?.focus();+ }, []);+const popover = usePopover({dialogLabel: label,hasCloseButton: false,hasAutoFocus: true,- // The popup's theme target belongs on the SURFACE — the element painting- // background, radius and elevation — which `usePopover` owns. Rendered on- // the content box below it, a theme's background or radius rule paints the- // wrong box.surfaceTarget: 'complex-selector-popup',- onHide: () => {- document.getElementById(triggerId)?.focus();- },+ onHide: handlePopoverHide,});+ const isOpen = popover.isOpen;++ const handleTriggerClick = useCallback(() => {+ if (isDisabled || Date.now() - lastHideTimeRef.current < 50) {+ return;+ }+ if (popover.isOpen) {+ popover.hide();+ } else {+ popover.show();+ }+ }, [isDisabled, popover]);++ const close = useCallback(() => {+ popover.hide();+ }, [popover]);++ useImperativeHandle(+ handleRef,+ () => ({+ open: () => {+ if (!isDisabled) {+ popover.show();+ }+ },+ close: () => popover.hide(),+ toggle: () => {+ if (isDisabled) {+ return;+ }+ if (popover.isOpen) {+ popover.hide();+ } else {+ popover.show();+ }+ },+ isOpen: () => popover.isOpen,+ }),+ [isDisabled, popover],+ );+const commitValue = useCallback((nextValue: Value) => {onChange?.(nextValue);@@ -319,8 +441,8 @@ export function ComplexSelector<Value>({const content = (<div id={contentId} {...stylex.props(styles.content, contentXstyle)}>- {children(optimisticValue, commitValue, popover.hide, {- isOpen: popover.isOpen,+ {children(optimisticValue, commitValue, close, {+ isOpen,isBusy,triggerId,contentId,@@ -334,13 +456,10 @@ export function ComplexSelector<Value>({ref={popover.triggerRef}data-testid={testId}{...props}- onClick={composeEventHandlers(onClickProp, () => {- if (!isDisabled) {- popover.toggle();- }- })}+ onClick={composeEventHandlers(onClickProp, handleTriggerClick)}{...mergeProps(themeProps('complex-selector', {+ variant,size,status: status?.type ?? null,}),@@ -348,12 +467,11 @@ export function ComplexSelector<Value>({inputWrapperStyles.base,styles.triggerContainer,styles[size],- // The ring belongs to the wrapper (the focusable `<button>` sits- // inside it), but it must still be a KEYBOARD ring: `:focus-within`- // matched a mouse click on the trigger and drew the outline for- // pointer users too. `focusWithin` here is `:has(:focus-visible)`.- focusOutlineStyles.focusWithin,+ variant === 'input' && focusOutlineStyles.focusWithin,+ variant === 'ghost' && styles.triggerGhost,+ variant === 'ghost' && focusOutlineStyles.focusWithin,isDisabled && inputWrapperStyles.disabled,+ variant === 'ghost' && isDisabled && styles.triggerGhostDisabled,isDisabled && styles.disabled,triggerLabel == null && styles.placeholder,xstyle,@@ -361,11 +479,14 @@ export function ComplexSelector<Value>({className,style,)}>+ {startIcon &&+ renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}<button+ ref={triggerRef}id={triggerId}type="button"aria-haspopup="dialog"- aria-expanded={popover.isOpen}+ aria-expanded={isOpen}aria-controls={contentId}aria-describedby={ariaDescribedBy}aria-labelledby={labelId}@@ -374,7 +495,7 @@ export function ComplexSelector<Value>({aria-busy={isBusy || undefined}disabled={isDisabled}onKeyDown={event => {- if (event.key === 'ArrowDown' && !popover.isOpen && !isDisabled) {+ if (event.key === 'ArrowDown' && !isOpen && !isDisabled) {event.preventDefault();popover.show();}@@ -394,17 +515,17 @@ export function ComplexSelector<Value>({xstyle={[styles.triggerIcon,styles.triggerIconRotation,- popover.isOpen && styles.triggerIconOpen,+ isOpen && styles.triggerIconOpen,]}{...themeProps('complex-selector-indicator-icon', {- state: popover.isOpen ? 'expanded' : 'collapsed',+ state: isOpen ? 'expanded' : 'collapsed',})}/></div>{popover.render(content, {placement,- alignment: 'start',+ alignment,offset: spacingVars['--spacing-1'],xstyle: [styles.popover, layerAnimations[placement]],})}@@ -431,7 +552,7 @@ export function ComplexSelector<Value>({}: undefined}- statusVariant={statusVariant}+ statusVariant={effectiveStatusVariant}labelTooltip={labelTooltip}width={width}>{selectorContent}diff --git a/packages/core/src/ComplexSelector/index.ts b/packages/core/src/ComplexSelector/index.tsindex 182e9a1e5b..f3ebcfa6bc 100644--- a/packages/core/src/ComplexSelector/index.ts+++ b/packages/core/src/ComplexSelector/index.ts@@ -4,14 +4,16 @@/*** @file index.ts- * @output Exports ComplexSelector and types+ * @output Exports ComplexSelector and its trigger-size contract types* @position Public API entry point*/export {ComplexSelector,+ type ComplexSelectorHandle,type ComplexSelectorProps,type ComplexSelectorRenderState,type ComplexSelectorSize,type ComplexSelectorStatus,+ type ComplexSelectorVariant,} from './ComplexSelector';