An open source design system that's fully customizable and agent ready
TypeScript
fix(SegmentedControl): cap the hug layout at its container (#6815)
David Petersenca3d6b97f7b0
diff --git a/.changeset/segmented-control-hug-caps.md b/.changeset/segmented-control-hug-caps.mdnew file mode 100644index 0000000000..84f18ac48b--- /dev/null+++ b/.changeset/segmented-control-hug-caps.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] SegmentedControl's default `hug` layout is now capped at its container width, and its segments shrink and truncate their labels instead of overflowing narrow cards and phone rows+@thedjpetersendiff --git a/apps/storybook/stories/SegmentedControl.stories.tsx b/apps/storybook/stories/SegmentedControl.stories.tsxindex 16a932f721..7a5ea9e0de 100644--- a/apps/storybook/stories/SegmentedControl.stories.tsx+++ b/apps/storybook/stories/SegmentedControl.stories.tsx@@ -6,7 +6,10 @@ import {SegmentedControl,SegmentedControlItem,} from '@astryxdesign/core/SegmentedControl';+import {Card} from '@astryxdesign/core/Card';+import {Heading} from '@astryxdesign/core/Heading';import {Icon} from '@astryxdesign/core/Icon';+import {Text} from '@astryxdesign/core/Text';import {VStack} from '@astryxdesign/core/Stack';import {Squares2X2Icon,@@ -81,6 +84,67 @@ export const InVerticalStack: Story = {},};+const WORKSPACE_SUMMARY: Record<string, string> = {+ overview: '4 projects, 2 due this week.',+ activity: '18 updates since Monday.',+ members: '12 members, 3 pending invites.',+ billing: 'Next invoice on October 1.',+};++function WorkspaceCard() {+ const [view, setView] = useState('overview');+ return (+ <Card maxWidth={480}>+ <VStack gap={3}>+ <Heading level={3}>Team workspace</Heading>+ <SegmentedControl+ label="Workspace view"+ value={view}+ onChange={setView}>+ <SegmentedControlItem value="overview" label="Overview" />+ <SegmentedControlItem value="activity" label="Activity" />+ <SegmentedControlItem value="members" label="Members" />+ <SegmentedControlItem value="billing" label="Billing" />+ </SegmentedControl>+ <Text color="secondary">{WORKSPACE_SUMMARY[view]}</Text>+ </VStack>+ </Card>+ );+}++/**+ * The SegmentedControl.doc.mjs "In a narrow card" example at 320px, 390px, and+ * 480px. With room (390px and 480px) the hug control keeps its content width+ * inside the VStack instead of stretching. At 320px it caps at the card width+ * and its labels truncate instead of running past the card edge.+ */+export const InNarrowCard: Story = {+ name: 'In a narrow card',+ render: () => (+ <div+ style={{+ display: 'flex',+ gap: 24,+ flexWrap: 'wrap',+ alignItems: 'flex-start',+ }}>+ {[320, 390, 480].map(width => (+ <div key={width} style={{width}}>+ <p+ style={{+ fontSize: 12,+ color: 'var(--color-text-secondary)',+ marginBottom: 8,+ }}>+ {width}px+ </p>+ <WorkspaceCard />+ </div>+ ))}+ </div>+ ),+};+export const WithIcons: Story = {args: {size: 'md',diff --git a/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs b/packages/core/src/SegmentedControl/SegmentedControl.doc.mjsindex 17678441b8..7eb8bba4dd 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs+++ b/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs@@ -37,6 +37,52 @@ export const docs = {value: 'option-1',},},+ examples: [+ {+ label: 'In a narrow card',+ code: `+import {useState} from 'react';+import {Card} from '@astryxdesign/core/Card';+import {Heading} from '@astryxdesign/core/Heading';+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@astryxdesign/core/SegmentedControl';+import {Text} from '@astryxdesign/core/Text';+import {VStack} from '@astryxdesign/core/VStack';++const SUMMARY = {+ overview: '4 projects, 2 due this week.',+ activity: '18 updates since Monday.',+ members: '12 members, 3 pending invites.',+ billing: 'Next invoice on October 1.',+};++// Inside a VStack the default hug layout keeps its content width; it does not+// stretch to the card. When the card is narrower than the control (a 320px+// phone column), the control caps at the card width and each label truncates+// with an ellipsis instead of running past the card edge. The full label stays+// each segment's accessible name. Keep labels short for phone widths.+function WorkspaceCard() {+ const [view, setView] = useState('overview');+ return (+ <Card maxWidth={480}>+ <VStack gap={3}>+ <Heading level={3}>Team workspace</Heading>+ <SegmentedControl label="Workspace view" value={view} onChange={setView}>+ <SegmentedControlItem value="overview" label="Overview" />+ <SegmentedControlItem value="activity" label="Activity" />+ <SegmentedControlItem value="members" label="Members" />+ <SegmentedControlItem value="billing" label="Billing" />+ </SegmentedControl>+ <Text color="secondary">{SUMMARY[view]}</Text>+ </VStack>+ </Card>+ );+}+`,+ },+ ],theming: {targets: [{className: 'astryx-segmented-control', visualProps: ['size']},@@ -80,7 +126,7 @@ export const docs = {{name: 'layout',type: "'hug' | 'fill'",- description: 'Layout mode. hug (default) sizes segments to content; fill stretches them equally to fill the container.',+ description: 'Layout mode. hug (default) sizes segments to content, capped at the container width (segment labels truncate when it is too narrow); fill stretches them equally to fill the container.',default: "'hug'",},{@@ -224,7 +270,7 @@ export const docsDense = {onChange: 'callback on segment selection',label: 'aria-label for radio group (never rendered)',size: 'size variant',- layout: 'hug (default) sizes to content; fill stretches equally',+ layout: 'hug (default) sizes to content, capped at container; fill stretches equally',isDisabled: 'disables entire control',children: 'SegmentedControlItem children',xstyle: 'additional StyleX styles for container',diff --git a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx b/packages/core/src/SegmentedControl/SegmentedControl.test.tsxindex 35561f69fe..1241c8a3ab 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControl.test.tsx@@ -229,6 +229,122 @@ describe('SegmentedControl', () => {expect(labelStyle.textOverflow).toBe('ellipsis');});+ it('caps the hug layout at its container and lets segments truncate', () => {+ render(+ <SegmentedControl value="grid" onChange={() => {}} label="View mode">+ <SegmentedControlItem+ value="grid"+ label="A very long segment label that should truncate"+ />+ <SegmentedControlItem value="list" label="List" />+ <SegmentedControlItem+ value="icon"+ label="Icon"+ icon={<span>*</span>}+ isLabelHidden+ />+ </SegmentedControl>,+ );++ const group = getComputedStyle(screen.getByRole('radiogroup'));+ expect(group.width).toBe('fit-content');+ expect(group.maxWidth).toBe('100%');+ expect(group.minWidth).toBe('0');++ const segment = screen.getByRole('radio', {name: /very long/});+ expect(getComputedStyle(segment).minWidth).toBe('0');+ expect(getComputedStyle(segment).flexShrink).not.toBe('0');++ // Icon-only segments have nothing to truncate and keep their size.+ const iconOnly = screen.getByRole('radio', {name: 'Icon'});+ expect(getComputedStyle(iconOnly).flexShrink).toBe('0');+ });++ it('keeps the content-sized hug layout from #6643 while adding the cap', () => {+ // #6643 stops a stretching column from widening hug; the cap must not+ // undo that. Both declarations coexist: fit-content sizes it, the cap+ // only applies when the container is narrower than the content.+ render(+ <div style={{display: 'flex', flexDirection: 'column'}}>+ <SegmentedControl value="grid" onChange={() => {}} label="View mode">+ <SegmentedControlItem value="grid" label="Grid" />+ <SegmentedControlItem value="list" label="List" />+ </SegmentedControl>+ </div>,+ );+ const group = getComputedStyle(screen.getByRole('radiogroup'));+ expect(group.width).toBe('fit-content');+ expect(group.maxWidth).toBe('100%');+ expect(group.display).toBe('inline-flex');+ });++ it('lets a fill control yield to a narrow row too', () => {+ render(+ <SegmentedControl+ value="grid"+ onChange={() => {}}+ label="View mode"+ layout="fill">+ <SegmentedControlItem value="grid" label="Grid" />+ <SegmentedControlItem value="list" label="List" />+ </SegmentedControl>,+ );+ const group = getComputedStyle(screen.getByRole('radiogroup'));+ expect(group.width).toBe('100%');+ expect(group.minWidth).toBe('0');+ expect(group.maxWidth).toBe('100%');+ });++ it('truncates the label of an icon-and-label segment but keeps its icon', () => {+ render(+ <SegmentedControl value="grid" onChange={() => {}} label="View mode">+ <SegmentedControlItem+ value="grid"+ label="Grid with thumbnails and captions"+ icon={<span data-testid="grid-icon">#</span>}+ />+ <SegmentedControlItem value="list" label="List" />+ </SegmentedControl>,+ );+ const segment = screen.getByRole('radio', {name: /Grid with/});+ expect(getComputedStyle(segment).minWidth).toBe('0');+ // Icon + label is not icon-only: the segment itself still shrinks.+ expect(getComputedStyle(segment).flexShrink).not.toBe('0');+ const iconWrapper = screen.getByTestId('grid-icon').parentElement!;+ expect(getComputedStyle(iconWrapper).flexShrink).toBe('0');+ const label = screen.getByText('Grid with thumbnails and captions');+ expect(getComputedStyle(label).textOverflow).toBe('ellipsis');+ });++ it('does not cap a control whose segments are all icon-only', () => {+ // Nothing in it can shrink, so a cap would only leave the last segments+ // hanging outside the control's track in a too-narrow container.+ render(+ <SegmentedControl value="list" onChange={() => {}} label="View mode">+ <SegmentedControlItem+ value="list"+ label="List"+ icon={<span>=</span>}+ isLabelHidden+ />+ <SegmentedControlItem+ value="board"+ label="Board"+ icon={<span>#</span>}+ isLabelHidden+ />+ </SegmentedControl>,+ );+ const group = getComputedStyle(screen.getByRole('radiogroup'));+ expect(group.width).toBe('fit-content');+ expect(group.maxWidth).toBe('none');+ // No min-size reset either, so a flex row cannot squeeze it.+ expect(group.minWidth).toBe('auto');+ for (const radio of screen.getAllByRole('radio')) {+ expect(getComputedStyle(radio).flexShrink).toBe('0');+ }+ });+it('promotes the first enabled item when the value matches no item and the first is disabled', () => {render(<SegmentedControldiff --git a/packages/core/src/SegmentedControl/SegmentedControl.tsx b/packages/core/src/SegmentedControl/SegmentedControl.tsxindex 53ef103b6b..11aca10d3d 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControl.tsx@@ -56,7 +56,8 @@ export interface SegmentedControlProps extends Omit<size?: SegmentedControlSize;/*** Layout mode for segment sizing.- * - `'hug'` (default): the control and each segment hug their content width.+ * - `'hug'` (default): the control and each segment hug their content width,+ * capped at the container (segment labels truncate when it is too narrow).* - `'fill'`: segments stretch equally to fill the container width.* @default 'hug'*/@@ -92,6 +93,21 @@ const styles = stylex.create({display: 'inline-flex',alignItems: 'center',width: 'fit-content',+ // Hug sizes to its segments but never past its container: in a narrow+ // card or a phone row the segments shrink and their labels truncate+ // instead of the control running off the edge. The cap and the min-size+ // reset apply only when a segment has a visible label to truncate+ // (icon-only segments carry `aria-label` and keep their size): a control+ // of icon-only segments has nothing that can shrink, and squeezing it+ // would leave segments hanging outside its track.+ maxWidth: {+ default: 'none',+ ':has([role="radio"]:not([aria-label]))': '100%',+ },+ minWidth: {+ default: 'auto',+ ':has([role="radio"]:not([aria-label]))': 0,+ },gap: spacingVars['--spacing-0-5'],'--_segmented-control-padding': spacingVars['--spacing-0-5'],padding: 'var(--_segmented-control-padding)',diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsxindex 2d4bc34791..7bf85de193 100644--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx@@ -88,6 +88,9 @@ const styles = stylex.create({':is(:disabled,[aria-disabled="true"])': 'default',},whiteSpace: 'nowrap',+ // In both layouts a segment may be narrower than its label, so the+ // label's ellipsis can engage when the control is capped by its container.+ minWidth: 0,transitionProperty: 'color, background-color, box-shadow',transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],@@ -125,6 +128,10 @@ const styles = stylex.create({minWidth: 0,justifyContent: 'center',},+ // An icon-only segment has no label to truncate, so it keeps its size.+ iconOnly: {+ flexShrink: 0,+ },icon: {display: 'inline-flex',alignItems: 'center',@@ -240,6 +247,7 @@ export function SegmentedControlItem({styles.base,sizeStyles[size],isFill && styles.fill,+ isLabelHidden && styles.iconOnly,isSelected && styles.selected,// The shared hover and pressed overlay, on the segments a press can// change: the selected segment keeps its raised surface as it is.