An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector): carry option descriptions, and render the selected option in the closed trigger (#5202)
Cindy Zhangffd05c4db99d
diff --git a/.changeset/selector-option-description-trigger-value.md b/.changeset/selector-option-description-trigger-value.mdnew file mode 100644index 0000000000..3f92240b46--- /dev/null+++ b/.changeset/selector-option-description-trigger-value.md@@ -0,0 +1,11 @@+---+'@astryxdesign/core': patch+---++[fix] Selector: `SelectorOptionData` gains `description`, and the closed trigger now shows the selected option instead of just its label. The two-line option row `SelectorOption` draws was unreachable from the `options` prop — the data type carried only `value/label/disabled/icon` — so consumers kept a side map of descriptions keyed by value and re-rendered the row through `renderOption`. `description` now sits on the option data and `DefaultOption` forwards it. On the trigger, the selected option's own `icon` renders in the closed state (`startIcon` still wins when set, so a pinned field icon never doubles up), which retires the app-side `startIcon={value === 'x' ? … : …}` mirroring of state the component already knows. `renderValue` is the seam for drawing the selection yourself — the description included.++[feat] Item: new `layout` prop — `'stacked'` (default, unchanged) or `'inline'`, which keeps the description on the label's line with the description ellipsizing first. The inline row centers its two lines rather than sharing a baseline: two font sizes on one baseline make a line box taller than either line, which would push a fixed-height host off its size token. Every row built on `Item` gets the axis, `SelectorOption` included.++[fix] Selector: the trigger is sized by padding rather than a fixed height, so it is the `--size-element-*` token for a one-line value (28/32/36) and exactly one text line taller for a two-line one (48/52/56). The token and a text line are both multiples of 4, so every trigger lands on the 4px rhythm and lines up with the Buttons and inputs beside it — and no prop chooses the height, the content does. It previously swapped the fixed height for a minimum whenever `renderValue` was passed, keyed on the prop being present rather than on the content needing the room: a one-line value measured 39px and a two-line one 58px at _every_ size, so the `size` prop stopped affecting the trigger at all. Inside an `InputGroup`, where the group pins the row, the relaxed height did nothing and the content bled 4px through its own border. The group owns the row now and the trigger clamps its own value box to it, so nothing a caller draws can paint over the rows above and below: a `SelectorOption` folds onto one line and ellipsizes, and any other node is cut off at the row's edge. The trigger also stops asserting a height floor of its own there, so a control sized above its group — `<InputGroup size="md">` around a `size="lg"` control — sits in the group's row instead of growing it. The trigger's line box is pinned to that same token rather than a ratio, so the coarse-pointer font bump — and any theme that changes `--font-size-base` — grows the glyphs without moving the control off its size token.++@cixzhangdiff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsxindex 3717832fe1..6ac9ea482a 100644--- a/apps/storybook/stories/Selector.stories.tsx+++ b/apps/storybook/stories/Selector.stories.tsx@@ -3,10 +3,17 @@import type {Meta, StoryObj} from '@storybook/react';import {useState} from 'react';import {Button} from '@astryxdesign/core/Button';+import {InputGroup} from '@astryxdesign/core/InputGroup';import {Selector, SelectorOption} from '@astryxdesign/core/Selector';import {Theme, defineTheme} from '@astryxdesign/core/theme';import {RadioIndicator} from '@astryxdesign/core/Indicator';-import {UserIcon, CogIcon, BellIcon} from '@heroicons/react/24/outline';+import {+ UserIcon,+ CogIcon,+ BellIcon,+ LockClosedIcon,+ GlobeAltIcon,+} from '@heroicons/react/24/outline';const meta: Meta<typeof Selector> = {title: 'Core/Selector',@@ -403,6 +410,85 @@ export const CustomRender: Story = {},};+// Two-line options: description on the data, and the trigger seam+export const OptionDescriptions: Story = {+ render: () => {+ const visibility = [+ {+ value: 'private',+ label: 'Private',+ icon: LockClosedIcon,+ description: 'Only members can access this space and its content.',+ },+ {+ value: 'public',+ label: 'Public',+ icon: GlobeAltIcon,+ description: 'Anyone at the company can find and join this space.',+ },+ ];+ const [condensed, setCondensed] = useState<string | undefined>('private');+ const [oneLine, setOneLine] = useState<string | undefined>('private');+ const [full, setFull] = useState<string | undefined>('private');+ const [grouped, setGrouped] = useState<string | undefined>('private');+ return (+ <div style={{display: 'grid', gap: 24}}>+ <Selector+ label="Visibility (default trigger)"+ options={visibility}+ value={condensed}+ onChange={setCondensed}+ data-testid="condensed"+ />+ <Selector+ label="Visibility (renderValue, one line)"+ options={visibility}+ value={oneLine}+ onChange={setOneLine}+ data-testid="one-line"+ renderValue={option => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ />+ )}+ />+ <Selector+ label="Visibility (renderValue)"+ options={visibility}+ value={full}+ onChange={setFull}+ data-testid="full"+ renderValue={option => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />+ )}+ />+ <InputGroup label="Visibility">+ <Selector+ label="Visibility (in a group)"+ isLabelHidden+ options={visibility}+ value={grouped}+ onChange={setGrouped}+ renderValue={option => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />+ )}+ />+ <Button label="Save" />+ </InputGroup>+ </div>+ );+ },+};+// Size variantsexport const SizeVariants: Story = {render: () => {diff --git a/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.doc.mjs b/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.doc.mjsnew file mode 100644index 0000000000..ce7ce60837--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.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: 'Selector',+ name: 'Selector — Option descriptions',+ displayName: 'Selector — Option descriptions',+ description:+ 'Options carry a description, so the dropdown draws a two-line row. The closed trigger is sized by padding, so it is the size token for a one-line value and exactly one line taller for a two-line one — both on the 4px rhythm. An InputGroup pins the row, so the value folds back onto one line there.',+ isReady: true,+ aspectRatio: 16 / 9,+ componentsUsed: ['Selector', 'SelectorOption', 'InputGroup', 'Button', 'Stack'],+};diff --git a/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.tsx b/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.tsxnew file mode 100644index 0000000000..fa2ca56646--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.tsx@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState} from 'react';+import {Selector, SelectorOption} from '@astryxdesign/core/Selector';+import {InputGroup} from '@astryxdesign/core/InputGroup';+import {Button} from '@astryxdesign/core/Button';+import {Stack} from '@astryxdesign/core/Layout';+import {LockClosedIcon, GlobeAltIcon} from '@heroicons/react/24/outline';++const VISIBILITY = [+ {+ value: 'private',+ label: 'Private',+ icon: LockClosedIcon,+ description: 'Only members can access this space and its content.',+ },+ {+ value: 'public',+ label: 'Public',+ icon: GlobeAltIcon,+ description: 'Anyone at the company can find and join this space.',+ },+];++export default function SelectorOptionDescriptions() {+ const [condensed, setCondensed] = useState<string | undefined>('private');+ const [full, setFull] = useState<string | undefined>('private');+ const [grouped, setGrouped] = useState<string | undefined>('private');++ return (+ <Stack direction="vertical" gap={6}>+ <Selector+ style={{width: 320}}+ label="Visibility"+ description="Default trigger: one line at the size token."+ options={VISIBILITY}+ value={condensed}+ onChange={setCondensed}+ />+ <Selector+ style={{width: 320}}+ label="Visibility"+ description="A stacked SelectorOption: the description gets its own line, and the trigger grows by exactly one line."+ options={VISIBILITY}+ value={full}+ onChange={setFull}+ renderValue={option => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />+ )}+ />+ <InputGroup label="Visibility">+ <Selector+ label="Visibility"+ isLabelHidden+ options={VISIBILITY}+ value={grouped}+ onChange={setGrouped}+ renderValue={option => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />+ )}+ />+ <Button label="Save" />+ </InputGroup>+ </Stack>+ );+}diff --git a/packages/core/src/Item/Item.doc.mjs b/packages/core/src/Item/Item.doc.mjsindex b713c47a2d..d3ae0344c3 100644--- a/packages/core/src/Item/Item.doc.mjs+++ b/packages/core/src/Item/Item.doc.mjs@@ -40,6 +40,7 @@ export const docs = {{name: 'density', type: "'compact' | 'balanced' | 'spacious'", description: 'Spacing density. "compact" uses 4px block padding, "balanced" uses 8px, and "spacious" uses 12px block and inline padding.', default: "'balanced'"},{name: 'labelLines', type: 'number', description: 'Max lines before label truncates with ellipsis.'},{name: 'descriptionLines', type: 'number', description: 'Max lines before description truncates with ellipsis.'},+ {name: 'layout', type: "'stacked' | 'inline'", description: 'How the label and description sit together. stacked puts the description on its own line below the label; inline keeps both on one line, description ellipsizing first, so the row fits a fixed-height host.', default: "'stacked'"},{name: 'onClick', type: '(event: MouseEvent) => void', description: 'Click handler. Makes the item clickable with button semantics.'},{name: 'interactiveRef', type: 'RefObject<HTMLElement | null>', description: 'Ref to a nested control (e.g. a checkbox in startContent) that owns the item\'s keyboard access and action. The row becomes an enlarged click/tap target that delegates surface clicks to it (useClickableContainer) and renders no invisible button/anchor, so the row adds no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href; those are ignored when set.'},{name: 'href', type: 'string', description: 'Link URL. Makes the item a link via an invisible anchor element.'},diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsxindex 36df1c048e..248826d0d8 100644--- a/packages/core/src/Item/Item.test.tsx+++ b/packages/core/src/Item/Item.test.tsx@@ -508,4 +508,54 @@ describe('Item', () => {expect(screen.getByText('Alice')).toBeInTheDocument();expect(screen.getByText(/commented/)).toBeInTheDocument();});+ it('puts the label and description in one row when layout is inline', () => {+ const stacked = render(+ <Item label="Private" description="Only members can access" />,+ );+ const stackedRow = screen.getByText('Private').parentElement;+ stacked.unmount();++ render(+ <Item+ label="Private"+ description="Only members can access"+ layout="inline"+ />,+ );+ const inlineRow = screen.getByText('Private').parentElement;++ // Same container, different styling: the shared content box switches from+ // a column to a row, so its class list must differ from the stacked one.+ expect(inlineRow?.className).not.toBe(stackedRow?.className);+ });++ it('ellipsizes a ReactNode description when layout is inline', () => {+ // A stacked ReactNode description is left alone (it may wrap); an inline+ // one is one line by definition, so it truncates like a string does.+ const stacked = render(+ <Item+ label="Private"+ description={<span>Only members can access</span>}+ />,+ );+ const stackedDescription = screen.getByText('Only members can access')+ .parentElement?.className;+ stacked.unmount();++ render(+ <Item+ label="Private"+ description={<span>Only members can access</span>}+ layout="inline"+ />,+ );+ expect(+ screen.getByText('Only members can access').parentElement?.className,+ ).not.toBe(stackedDescription);+ });++ it('ignores inline layout when there is no description', () => {+ render(<Item label="Private" layout="inline" />);+ expect(screen.getByText('Private')).toBeInTheDocument();+ });});diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 99afbd7853..5b4cc9acfb 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -106,6 +106,15 @@ export interface ItemProps extends BaseProps<HTMLElement> {*/descriptionLines?: number;+ /**+ * How the label and description sit together. `stacked` puts the description+ * on its own line below the label; `inline` keeps both on one line, with the+ * description ellipsizing first, so the row fits a fixed-height host.+ *+ * @default 'stacked'+ */+ layout?: 'stacked' | 'inline';+/*** Click handler. Makes the item clickable with button semantics.*/@@ -264,6 +273,25 @@ const styles = stylex.create({minWidth: 0,textAlign: 'start',},+ // `layout="inline"`: label and description share one line, so the row fits a+ // fixed-height host such as a Selector trigger inside an InputGroup.+ inlineContent: {+ flexDirection: 'row',+ // Centered, not baseline-aligned: two different font sizes on a shared+ // baseline make a line box taller than either line, which would push a+ // fixed-height host (a Selector trigger) a pixel off its size token.+ alignItems: 'center',+ columnGap: spacingVars['--spacing-1'],+ },+ inlineLabel: {+ flexShrink: 0,+ },+ // The description yields width first, so the label — the part that identifies+ // the item — is the last thing to ellipsize.+ inlineDescription: {+ flexShrink: 1,+ minWidth: 0,+ },label: {// Falls back to the primary text token; a parent (e.g. a destructive menu// item) can recolor the label by setting --_item-label-color.@@ -358,6 +386,7 @@ export function Item({density = 'balanced',labelLines,descriptionLines,+ layout = 'stacked',onClick,interactiveRef,href,@@ -420,12 +449,16 @@ export function Item({? styles.labelSingleTruncate: null;+ // Inline rows are one line by definition, so the description always+ // ellipsizes there — a ReactNode description cannot wrap the row open.+ const isInline = layout === 'inline' && description != null;+const descriptionTruncateStyle =descriptionLines != null? descriptionLines === 1? styles.descriptionSingleTruncate: styles.descriptionMultiTruncate- : isStringDescription+ : isStringDescription || isInline? styles.descriptionSingleTruncate: null;@@ -434,6 +467,7 @@ export function Item({<span{...stylex.props(styles.label,+ isInline && styles.inlineLabel,labelTruncateStyle,labelLines != null &&labelLines > 1 &&@@ -445,6 +479,7 @@ export function Item({<span{...stylex.props(styles.description,+ isInline && styles.inlineDescription,descriptionTruncateStyle,descriptionLines != null &&descriptionLines > 1 &&@@ -481,6 +516,7 @@ export function Item({<span{...stylex.props(styles.content,+ isInline && styles.inlineContent,isDisabled && styles.disabledContent,)}>{labelAndDescription}@@ -494,6 +530,7 @@ export function Item({tabIndex={isDisabled ? -1 : undefined}{...stylex.props(styles.invisibleAnchor,+ isInline && styles.inlineContent,isDisabled && styles.disabledContent,)}>{labelAndDescription}@@ -505,6 +542,7 @@ export function Item({disabled={isDisabled}{...stylex.props(styles.invisibleButton,+ isInline && styles.inlineContent,isDisabled && styles.disabledContent,)}>{labelAndDescription}@@ -513,6 +551,7 @@ export function Item({<span{...stylex.props(styles.content,+ isInline && styles.inlineContent,isDisabled && styles.disabledContent,)}>{labelAndDescription}diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjsindex 0b4c68fbde..31ef527ce4 100644--- a/packages/core/src/Selector/Selector.doc.mjs+++ b/packages/core/src/Selector/Selector.doc.mjs@@ -30,7 +30,10 @@ export const docs = {{className: 'astryx-selector-search'},{className: 'astryx-selector-section-heading'},{className: 'astryx-selector-empty-state'},- {className: 'astryx-selector-clear-icon', deprecatedFor: 'input-clear-icon'},+ {+ className: 'astryx-selector-clear-icon',+ deprecatedFor: 'input-clear-icon',+ },{className: 'astryx-selector-indicator-icon', states: ['state']},{className: 'astryx-selector-check'},{className: 'astryx-selector-popup'},@@ -48,7 +51,7 @@ export const docs = {name: 'options',type: 'SelectorOption[]',description:- 'Array of items: strings, objects with value/label/icon/disabled, dividers ({type: "divider"}), or sections ({type: "section", title, items}).',+ 'Array of items: strings, objects with value/label/description/icon/disabled, dividers ({type: "divider"}), or sections ({type: "section", title, items}).',required: true,},{@@ -159,6 +162,12 @@ export const docs = {description:'Custom render function for each selectable option in the dropdown. Use this instead of JSX children; dividers and sections are rendered by the selector.',},+ {+ name: 'renderValue',+ type: '(option: SelectorOptionData) => ReactNode',+ description:+ 'Custom render function for the selected option inside the closed trigger. The trigger is sized by padding, so it is the size token for a one-line value (28/32/36) and exactly one text line taller for a two-line one (48/52/56) — always on the 4px rhythm, always aligned with the buttons and inputs beside it. Inside an InputGroup the group owns the row height: a SelectorOption folds onto one line and ellipsizes, and any taller node is cut off at the row.',+ },{name: 'indicatorPosition',type: "'start' | 'end'",diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex 301b75f60a..3d2916a9dd 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -19,8 +19,11 @@ import {} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {useState} from 'react';+import type {ReactNode} from 'react';import {Selector} from './Selector';import {SelectorOption} from './SelectorOption';+import {Item} from '../Item';+import type {SelectorOptionData} from './types';import {Icon} from '../Icon';import {RadioIndicator} from '../Indicator';import {InputGroup, InputGroupText} from '../InputGroup';@@ -2993,3 +2996,406 @@ describe('Selector popup theme target', () => {},);});++describe('Selector option descriptions and trigger value', () => {+ const LOCK = <span data-testid="lock-glyph" />;+ const GLOBE = <span data-testid="globe-glyph" />;+ const VISIBILITY = [+ {+ value: 'private',+ label: 'Private',+ icon: LOCK,+ description: 'Only members can access this space.',+ },+ {+ value: 'public',+ label: 'Public',+ icon: GLOBE,+ description: 'Anyone at the company can join.',+ },+ ];++ it('renders an option description in the dropdown row', () => {+ render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ isDefaultOpen+ />,+ );++ const [row] = screen.getAllByRole('option', {hidden: true});+ expect(row).toHaveTextContent('Private');+ expect(row).toHaveTextContent('Only members can access this space.');+ });++ it('keeps the description out of the closed trigger by default', () => {+ render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ />,+ );++ const trigger = screen.getByRole('combobox');+ expect(trigger).toHaveTextContent('Private');+ expect(trigger).not.toHaveTextContent(+ 'Only members can access this space.',+ );+ });++ it("renders the selected option's icon in the closed trigger", () => {+ render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ />,+ );++ const trigger = screen.getByRole('combobox');+ expect(within(trigger).getByTestId('lock-glyph')).toBeInTheDocument();+ expect(+ within(trigger).queryByTestId('globe-glyph'),+ ).not.toBeInTheDocument();+ });++ it('renders no option icon while showing the placeholder', () => {+ render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value={undefined}+ onChange={() => {}}+ placeholder="Choose..."+ />,+ );++ const trigger = screen.getByRole('combobox');+ expect(trigger).toHaveTextContent('Choose...');+ expect(within(trigger).queryByTestId('lock-glyph')).not.toBeInTheDocument();+ });++ it('lets startIcon win over the selected option icon', () => {+ render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ startIcon={<span data-testid="pinned-icon" />}+ />,+ );++ // One leading glyph in the trigger, not two.+ expect(screen.getByTestId('pinned-icon')).toBeInTheDocument();+ expect(+ within(screen.getByRole('combobox')).queryByTestId('lock-glyph'),+ ).not.toBeInTheDocument();+ });++ it('renders the selected option through renderValue', () => {+ render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ renderValue={option => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />+ )}+ />,+ );++ const trigger = screen.getByRole('combobox');+ expect(trigger).toHaveTextContent('Private');+ expect(trigger).toHaveTextContent('Only members can access this space.');+ expect(within(trigger).getByTestId('lock-glyph')).toBeInTheDocument();+ });++ it('sizes the trigger from what renderValue draws, not from it being passed', () => {+ // The regression this guards: keying the height off `renderValue != null`+ // handed a one-line custom value a taller control than the same value in+ // the default trigger, so `size` quietly stopped meaning its token. The+ // trigger carries one set of sizing classes for every case — a one-line+ // value measures the token, and only a second line of content adds a+ // second line of height.+ const triggerSizing = () =>+ new Set(+ (screen.getByRole('combobox').parentElement?.className ?? '')+ .split(' ')+ .filter(Boolean),+ );++ const plain = render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ />,+ );+ const defaultSizing = triggerSizing();+ plain.unmount();++ const oneLine = render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ renderValue={option => <span>{option.label}</span>}+ />,+ );+ expect(triggerSizing()).toEqual(defaultSizing);+ oneLine.unmount();++ render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ renderValue={option => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />+ )}+ />,+ );+ expect(triggerSizing()).toEqual(defaultSizing);+ });++ it("follows the caller's SelectorOption layout, but folds inline in a group", () => {+ // The trigger has no layout prop: the SelectorOption the caller renders+ // decides, and the trigger's padding sizes it to whatever that draws. The+ // one exception is an InputGroup, which pins the row height — the value+ // box is clamped to it, so a stacked row would lose its second line at the+ // cut. Folding inline keeps the description visible instead.+ const renderValue = (option: SelectorOptionData) => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />+ );+ const classesOf = (label: HTMLElement) =>+ new Set((label.parentElement?.className ?? '').split(' '));+ const triggerClasses = () =>+ classesOf(within(screen.getByRole('combobox')).getByText('Private'));++ const stackedRef = render(<Item label="Private" description="Why" />);+ const stackedClasses = classesOf(screen.getByText('Private'));+ stackedRef.unmount();++ const inlineRef = render(+ <Item label="Private" description="Why" layout="inline" />,+ );+ const inlineOnly = [...classesOf(screen.getByText('Private'))].filter(+ c => c !== '' && !stackedClasses.has(c),+ );+ inlineRef.unmount();+ expect(inlineOnly.length).toBeGreaterThan(0);++ const standalone = render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ renderValue={renderValue}+ />,+ );+ expect(inlineOnly.some(c => triggerClasses().has(c))).toBe(false);+ standalone.unmount();++ render(+ <InputGroup label="Space settings">+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ renderValue={renderValue}+ />+ </InputGroup>,+ );+ expect(inlineOnly.every(c => triggerClasses().has(c))).toBe(true);+ });++ it('clamps the trigger value box in a group, whatever renderValue draws', () => {+ // The hole this guards: the one-line fold a group imposes used to reach+ // only SelectorOption, which reads the row-layout context. Any other node+ // ignored it and bled through the trigger's border, over the rows above+ // and below the group. The clamp is on the trigger's own value box, so it+ // cannot depend on what the value is.+ const valueBox = () => {+ const box = screen.getByRole('combobox').firstElementChild;+ return new Set((box?.className ?? '').split(' ').filter(Boolean));+ };+ const grouped = (+ renderValue: (option: SelectorOptionData) => ReactNode,+ ) => (+ <InputGroup label="Space settings">+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ renderValue={renderValue}+ />+ </InputGroup>+ );++ const standalone = render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ renderValue={option => <span>{option.label}</span>}+ />,+ );+ const unclamped = valueBox();+ standalone.unmount();++ const withOption = render(+ grouped(option => (+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />+ )),+ );+ const clamped = valueBox();+ expect(clamped).not.toEqual(unclamped);+ withOption.unmount();++ // A row the Selector knows nothing about, and a bare element: same box.+ const withItem = render(+ grouped(option => (+ <Item+ label={option.label ?? option.value}+ description={option.description}+ />+ )),+ );+ expect(valueBox()).toEqual(clamped);+ withItem.unmount();++ render(+ grouped(option => (+ <div>+ <div>{option.label}</div>+ <div>{option.description}</div>+ </div>+ )),+ );+ expect(valueBox()).toEqual(clamped);+ });++ it('does not let a control sized above its group grow the row', () => {+ // The group's height is the row, so inside one the trigger drops the floor+ // its own `size` would otherwise assert: <InputGroup size="md"> with a+ // <Selector size="lg"> stays the group's 32px. The size still reaches the+ // theme (the trigger keeps its `size` marker class); what it no longer+ // does is set a height. Standalone, the two sizes still differ.+ const triggerSizing = () =>+ new Set(+ (screen.getByRole('combobox').parentElement?.className ?? '')+ .split(' ')+ .filter(Boolean),+ );+ // What changes between the two sizes. StyleX keeps a debug class per style+ // object even where every declaration in it lost, and the theme keeps its+ // own `size` marker; the atomic classes are what carry the geometry.+ const geometryDiff = (a: Set<string>, b: Set<string>) => {+ const atomic = (classes: Set<string>) =>+ [...classes].filter(c => !c.includes('__') && c !== 'md' && c !== 'lg');+ return [...atomic(a), ...atomic(b)].filter(c => !(a.has(c) && b.has(c)));+ };+ const selector = (size: 'md' | 'lg') => (+ <Selector+ label="Visibility"+ size={size}+ options={VISIBILITY}+ value="private"+ onChange={() => {}}+ />+ );++ const standaloneMd = render(selector('md'));+ const standaloneMdSizing = triggerSizing();+ standaloneMd.unmount();++ const standaloneLg = render(selector('lg'));+ expect(geometryDiff(standaloneMdSizing, triggerSizing())).not.toEqual([]);+ standaloneLg.unmount();++ const groupedMd = render(+ <InputGroup label="Space settings" size="md">+ {selector('md')}+ </InputGroup>,+ );+ const groupedMdSizing = triggerSizing();+ groupedMd.unmount();++ render(+ <InputGroup label="Space settings" size="md">+ {selector('lg')}+ </InputGroup>,+ );+ expect(geometryDiff(groupedMdSizing, triggerSizing())).toEqual([]);+ });++ it('does not call renderValue for the placeholder', () => {+ const renderValue = vi.fn(() => <span>custom</span>);+ render(+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value={undefined}+ onChange={() => {}}+ placeholder="Choose..."+ renderValue={renderValue}+ />,+ );++ expect(renderValue).not.toHaveBeenCalled();+ expect(screen.getByRole('combobox')).toHaveTextContent('Choose...');+ });++ it('matches type-ahead on the label, not the description', () => {+ // "Anyone" starts the public description; typing "a" must not select it.+ function Harness() {+ const [value, setValue] = useState<string | undefined>(undefined);+ return (+ <Selector+ label="Visibility"+ options={VISIBILITY}+ value={value}+ onChange={setValue}+ />+ );+ }+ render(<Harness />);++ const trigger = screen.getByRole('combobox');+ trigger.focus();+ type('pu', trigger);+ expect(trigger).toHaveTextContent('Public');+ expect(trigger).not.toHaveTextContent('Anyone at the company can join.');+ });+});diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex 378ce85bda..13912ba6ac 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -73,6 +73,7 @@ import {useCombobox, useSelectedItemOffset} from './hooks';import {useTypeahead} from '../hooks/useTypeahead';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {SelectorOption} from './SelectorOption';+import {SelectorRowLayoutContext} from './SelectorRowLayoutContext';import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';import {useSize} from '../SizeContext/SizeContext';import type {BaseProps} from '../BaseProps';@@ -101,7 +102,13 @@ const styles = stylex.create({default: typeScaleVars['--text-label-size'],'@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-label-size']})`,},- lineHeight: typeScaleVars['--text-label-leading'],+ // A FIXED line box, not the ratio: the trigger's padding is derived from+ // one line being `--spacing-5` tall, and a ratio makes the line box track+ // the font — which the coarse-pointer bump above (and any theme that+ // changes `--font-size-base`) then moves, taking the control off its size+ // token. The glyphs still grow for touch; only the box they sit in is+ // pinned. Item's own rows set their line heights and are unaffected.+ lineHeight: spacingVars['--spacing-5'],color: colorVars['--color-text-primary'],cursor: 'pointer',},@@ -142,6 +149,43 @@ const styles = stylex.create({whiteSpace: 'nowrap',textAlign: 'start',},+ // Inside an InputGroup the group's own height is the row, and the trigger+ // takes it: `height: 100%` from `groupStyles.inGroup` can only govern if the+ // trigger stops asserting a floor of its own — otherwise a control sized+ // above its group (`<InputGroup size="md"><Selector size="lg">`) grows the+ // row it was supposed to sit in. The padding goes with it: the row is+ // already the size token, and the value box is centred in it.+ triggerInGroup: {+ minHeight: 0,+ paddingBlock: 0,+ },+ // Wrapper for `renderValue` output. Takes the free width and clips+ // horizontally so a long value ellipsizes rather than widening the trigger;+ // vertically the content sizes the control, which the size styles below+ // handle.+ triggerValue: {+ flexGrow: 1,+ minWidth: 0,+ overflow: 'hidden',+ textAlign: 'start',+ },+ // Inside an InputGroup the row height is the group's, so the trigger clamps+ // its own value box to that row rather than asking the value to fit it: any+ // node is cut off at the row's edge instead of bleeding through the border+ // over whatever sits above and below the group. The rows the system draws+ // itself never reach the cut — the row-layout context folds them onto one+ // line first (SelectorRowLayoutContext).+ //+ // The clamp is a percentage, not the size token, because a group can be a+ // different size than the control inside it; the row is whatever the group+ // made it. That needs a definite height to resolve against, which is what+ // stretching the button provides.+ triggerButtonInGroup: {+ alignSelf: 'stretch',+ },+ triggerValueInGroup: {+ maxHeight: '100%',+ },// Only what Icon does not already provide: `size="sm"` gives the 16px box// and `color` the token, but the glyph still must not shrink inside the flex// trigger.@@ -328,15 +372,31 @@ const styles = stylex.create({},});+// The trigger is sized by PADDING, not by a fixed height, so it is the size+// token plus one text line for each extra line the value uses: 28/32/36 for+// one line, 48/52/56 for two. The token and a text line are both multiples of+// 4, so every trigger lands on the 4px rhythm and lines up with the Buttons+// and inputs beside it. No prop picks the height — the content does, and it+// can only land on the grid.+//+// `--spacing-5` is one line here because `triggerContainer` pins its+// line-height to exactly that; the two must stay in step, which is why both+// read the same token rather than one hardcoding 20px.+const linePad = (token: string) =>+ `calc((${token} - ${spacingVars['--spacing-5']} - 2 * ${borderVars['--border-width']}) / 2)`;+const sizeStyles = stylex.create({sm: {- height: sizeVars['--size-element-sm'],+ minHeight: sizeVars['--size-element-sm'],+ paddingBlock: linePad(sizeVars['--size-element-sm']),},md: {- height: sizeVars['--size-element-md'],+ minHeight: sizeVars['--size-element-md'],+ paddingBlock: linePad(sizeVars['--size-element-md']),},lg: {- height: sizeVars['--size-element-lg'],+ minHeight: sizeVars['--size-element-lg'],+ paddingBlock: linePad(sizeVars['--size-element-lg']),},});@@ -517,7 +577,8 @@ interface SelectorPropsBase<labelTooltip?: string;/**- * Icon displayed at the start of the selector trigger.+ * Icon displayed at the start of the selector trigger. Takes precedence over+ * the selected option's own `icon`, which the trigger otherwise renders.*/startIcon?: ReactNode | IconType;@@ -527,6 +588,31 @@ interface SelectorPropsBase<*/renderOption?: (option: SelectorOptionData) => ReactNode;+ /**+ * Custom render function for the selected option inside the closed trigger.+ * Only called when something is selected; the placeholder is unaffected.+ *+ * Passing this does not change the trigger's height — what it draws does. A+ * one-line value measures exactly the `size` token, so the control still+ * lines up with the Buttons and inputs beside it; each further line of+ * content adds one text line. Inside an `InputGroup` the group owns the row+ * height: the trigger clamps its value box to that row, so a `SelectorOption`+ * folds onto one line and ellipsizes, and anything taller than the row is cut+ * off at it rather than bleeding over the rows above and below.+ *+ * @example+ * ```+ * renderValue={option => (+ * <SelectorOption+ * icon={option.icon}+ * label={option.label}+ * description={option.description}+ * />+ * )}+ * ```+ */+ renderValue?: (option: SelectorOptionData) => ReactNode;+/*** Which edge of the option row carries the selected mark. `start` reserves a* mark column ahead of every label so they stay aligned, the way a native@@ -614,7 +700,11 @@ export type SelectorProps<T extends SelectorOptionType = SelectorOptionType> =*/function DefaultOption({option}: {option: SelectorOptionData}) {return (- <SelectorOption icon={option.icon} label={option.label ?? option.value} />+ <SelectorOption+ icon={option.icon}+ label={option.label ?? option.value}+ description={option.description}+ />);}@@ -687,6 +777,7 @@ export function Selector<T extends SelectorOptionType>(startIcon,htmlName,renderOption,+ renderValue,indicatorPosition = 'end',hasSearch = false,searchPlaceholder: searchPlaceholderFromProps,@@ -1281,6 +1372,40 @@ export function Selector<T extends SelectorOptionType>(const showStatusTooltip =status != null && effectiveStatusVariant === 'tooltip' && !!status.message;+ // Two lines cannot fit inside an InputGroup: the group pins the row height,+ // and the trigger clamps its value box to one line so nothing bleeds through+ // its border (styles.triggerValueInGroup). The clamp holds for any node; the+ // context is what lets the rows the system draws itself reflow into that one+ // line — label and description side by side — instead of being cut off at+ // it. Outside a group the caller's own row decides, and the trigger's+ // padding sizes it to whatever that draws.+ const rowLayout = inputGroup ? 'inline' : 'stacked';++ // What the closed trigger shows for the current selection: the option's icon+ // and label. `startIcon` wins over the option's own icon so a caller who+ // pins a field icon does not get two.+ const valueContent =+ selectedItem && renderValue ? (+ <SelectorRowLayoutContext value={rowLayout}>+ <span+ {...stylex.props(+ styles.triggerValue,+ inputGroup && styles.triggerValueInGroup,+ )}>+ {renderValue(selectedItem)}+ </span>+ </SelectorRowLayoutContext>+ ) : (+ <>+ {!startIcon &&+ selectedItem?.icon != null &&+ renderIconSlot(selectedItem.icon, {size: 'sm', color: 'secondary'})}+ <span {...stylex.props(styles.triggerLabel)}>+ {selectedItem?.label ?? placeholder}+ </span>+ </>+ );+const selectorContent = (<><div@@ -1318,6 +1443,7 @@ export function Selector<T extends SelectorOptionType>(!isDisabled &&inputStatusHoverShadowStyles[status.type],variant !== 'ghost' && inputGroup && groupStyles.inGroup,+ inputGroup && styles.triggerInGroup,xstyle,),className,@@ -1357,10 +1483,11 @@ export function Selector<T extends SelectorOptionType>(aria-disabled={showsDisabledMessage ? 'true' : undefined}onKeyDown={handleTriggerKeyDown}tabIndex={isDisabled && !showsDisabledMessage ? -1 : 0}- {...stylex.props(styles.trigger)}>- <span {...stylex.props(styles.triggerLabel)}>- {selectedItem?.label ?? placeholder}- </span>+ {...stylex.props(+ styles.trigger,+ inputGroup && styles.triggerButtonInGroup,+ )}>+ {valueContent}</button>{htmlName != null && (<inputdiff --git a/packages/core/src/Selector/SelectorOption.doc.mjs b/packages/core/src/Selector/SelectorOption.doc.mjsindex 826ba83ead..abb6f80efc 100644--- a/packages/core/src/Selector/SelectorOption.doc.mjs+++ b/packages/core/src/Selector/SelectorOption.doc.mjs@@ -27,6 +27,13 @@ export const docs = {type: 'ReactNode',description: 'Secondary description text displayed below the label.',},+ {+ name: 'layout',+ type: "'stacked' | 'inline'",+ description:+ "How the label and description sit together. 'stacked' puts the description on its own line; 'inline' keeps both on one line so the row fits a fixed-height host. Inside a Selector trigger the trigger's padding sizes itself to whichever layout you pick, so both land on the 4px rhythm; an InputGroup pins the row height and forces 'inline'.",+ default: "'stacked'",+ },{name: 'endContent',type: 'ReactNode',diff --git a/packages/core/src/Selector/SelectorOption.tsx b/packages/core/src/Selector/SelectorOption.tsxindex 6ea09d9ab6..61b857c207 100644--- a/packages/core/src/Selector/SelectorOption.tsx+++ b/packages/core/src/Selector/SelectorOption.tsx@@ -13,6 +13,7 @@ import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {renderIconSlot, type IconType} from '../Icon';import {Item} from '../Item';+import {useSelectorRowLayout} from './SelectorRowLayoutContext';import {mergeProps} from '../utils';import {themeProps} from '../utils/themeProps';@@ -40,6 +41,20 @@ export interface SelectorOptionProps {*/description?: ReactNode;+ /**+ * How the label and description sit together. `stacked` puts the+ * description on its own line below the label; `inline` keeps both on one+ * line, with the description ellipsizing first.+ *+ * In a Selector trigger this is the caller's choice and the trigger sizes+ * itself to it — one line at the size token, two lines exactly one text line+ * taller. Inside an `InputGroup` the row height is pinned by the group, so+ * `inline` is forced.+ *+ * @default 'stacked'+ */+ layout?: 'stacked' | 'inline';+/*** Additional content to render after the label/description.*/@@ -95,11 +110,16 @@ export function SelectorOption({icon,label,description,+ layout,endContent,xstyle,className,style,}: SelectorOptionProps) {+ // A height-pinned host (the trigger inside an InputGroup) overrides the+ // caller's choice: the row physically cannot be two lines there.+ const enforcedLayout = useSelectorRowLayout();+return (<ItemstartContent={@@ -109,6 +129,7 @@ export function SelectorOption({}label={label}description={description}+ layout={enforcedLayout === 'inline' ? 'inline' : layout}endContent={endContent}xstyle={[embeddedStyles.root, xstyle]}{...mergeProps(themeProps('selector-option'), {className, style})}diff --git a/packages/core/src/Selector/SelectorRowLayoutContext.ts b/packages/core/src/Selector/SelectorRowLayoutContext.tsnew file mode 100644index 0000000000..5d3cd9e711--- /dev/null+++ b/packages/core/src/Selector/SelectorRowLayoutContext.ts@@ -0,0 +1,32 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file SelectorRowLayoutContext.ts+ * @input React createContext/use+ * @output Exports the row-layout context and useSelectorRowLayout hook+ * @position Internal to the Selector module; read by SelectorOption+ *+ * The trigger inside an InputGroup is height-pinned by the group, so its value+ * box is clamped to one line and anything taller is cut off at the fold. This+ * context is how the rows the system draws itself avoid being cut: they reflow+ * label and description onto that one line instead. The geometry does not+ * depend on it — a node that ignores this context still cannot grow the row.+ */++import {createContext, use} from 'react';++export type SelectorRowLayout = 'stacked' | 'inline';++export const SelectorRowLayoutContext =+ createContext<SelectorRowLayout>('stacked');+SelectorRowLayoutContext.displayName = 'SelectorRowLayoutContext';++/**+ * The row layout a host imposes on the options it renders. `stacked` outside+ * any height-pinned host.+ */+export function useSelectorRowLayout(): SelectorRowLayout {+ return use(SelectorRowLayoutContext);+}diff --git a/packages/core/src/Selector/types.ts b/packages/core/src/Selector/types.tsindex e41a83e3d8..df15278705 100644--- a/packages/core/src/Selector/types.ts+++ b/packages/core/src/Selector/types.ts@@ -14,7 +14,10 @@ import type {IconType} from '../Icon';*/export type SelectorOptionData = {value: string;+ // Kept a string, not ReactNode: search filtering and type-ahead both+ // lowercase this to match keystrokes.label?: string;+ description?: ReactNode;disabled?: boolean;icon?: ReactNode | IconType;};@@ -40,7 +43,4 @@ export type SelectorSection = {* Can be a plain string, option data object, divider, or section.*/export type SelectorOptionType =- | string- | SelectorOptionData- | SelectorDivider- | SelectorSection;+ string | SelectorOptionData | SelectorDivider | SelectorSection;