Skip to content

The open alternative to Salesforce, designed for AI.

Use radio groups for segmented settings (#26465)

Raphaël Bosi1cf681f131ed
diff --git a/packages/twenty-companion/src/renderer/components/Settings.tsx b/packages/twenty-companion/src/renderer/components/Settings.tsx
index 33daf485dfc..3e702b50533 100644
--- a/packages/twenty-companion/src/renderer/components/Settings.tsx
+++ b/packages/twenty-companion/src/renderer/components/Settings.tsx
@@ -80,16 +80,17 @@ export const Settings = ({ state, isPending, command }: ActionProps) => (
>
<SegmentedControl
itemWidth="content"
- ariaLabel={i18n._('Appearance')}
+ aria-label={i18n._('Appearance')}
+ disabled={isPending('settings')}
value={state.settings.appearance}
- options={(
+ options={
[
{ value: 'system', label: i18n._('System') },
{ value: 'light', label: i18n._('Light') },
{ value: 'dark', label: i18n._('Dark') },
] as const
- ).map((option) => ({ ...option, disabled: isPending('settings') }))}
- onChange={(appearance) =>
+ }
+ onValueChange={(appearance) =>
void command({ type: 'settings', settings: { appearance } })
}
/>
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
index 84aa5a8ab9d..7b7b2148740 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
@@ -1,3 +1,5 @@
+import { inputPreactTest } from '@/__stories__/twenty-ui-gallery/utils/inputPreactTest';
+import { inputReactTest } from '@/__stories__/twenty-ui-gallery/utils/inputReactTest';
import { settingsRowTest } from '@/__stories__/twenty-ui-gallery/utils/settingsRowTest';
import { resizeHandleTest } from '@/__stories__/twenty-ui-gallery/utils/resizeHandleTest';
import { createListItemSandboxFailureTest } from '@/__stories__/twenty-ui-gallery/utils/createListItemSandboxFailureTest';
@@ -32,8 +34,6 @@ import {
codeEditorTest,
displayHelpersTest,
galleryRenderTest,
- inputPreactTest,
- inputReactTest,
themeTokenTest,
} from '@/__stories__/twenty-ui-gallery/utils/galleryRenderTests';
import {
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
index af898a24dc3..6666cea2a11 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
@@ -46,6 +46,8 @@ No stories are skipped or marked as expected-to-fail by the runner.
| --- | --- |
| Field controls | Forwarded events lack the native event used for `composedPath`. React serializes boolean `aria-invalid` as an empty string; Textarea's cloned render element loses its change handler in React. The value report checks the state received by the component after typing. |
| Tabs | React cannot mount without `compareDocumentPosition`; Preact activation fails on the missing native event for `composedPath`. |
+| Radio, RadioGroup | Unselected radios need `Element.matches(':disabled')`; React also orders radio groups with `compareDocumentPosition`. |
+| SegmentedControl | Ordering its radios needs `compareDocumentPosition`, so React cannot mount it. In the Preact input gallery the `Radio` failure skips that ordering at mount, so the control fails on first focus instead. Selecting would also need `PointerEvent` and native radio activation. |
| Popover, AlertDialog | Opening fails while reading unavailable viewport width data. |
| Menu, Select | Opening fails on viewport data and/or missing `nativeEvent.pointerType`. |
| Switch | Activation attempts to construct an unavailable `PointerEvent`. |
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/SEGMENTED_CONTROL_ORDERING_ERROR.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/SEGMENTED_CONTROL_ORDERING_ERROR.ts
new file mode 100644
index 00000000000..ee394ad9508
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/SEGMENTED_CONTROL_ORDERING_ERROR.ts
@@ -0,0 +1,2 @@
+export const SEGMENTED_CONTROL_ORDERING_ERROR =
+ /SegmentedControl: \w+\.compareDocumentPosition is not a function(?: \| |$)/;
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-input-gallery.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-input-gallery.front-component.tsx
index 59a6f6b3b7a..53ceab9c0c0 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-input-gallery.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-input-gallery.front-component.tsx
@@ -142,9 +142,8 @@ const INPUT_ENTRIES: GalleryEntry[] = [
name: 'SegmentedControl',
node: (
<SegmentedControl
- ariaLabel="Choose"
- value="left"
- onChange={() => {}}
+ aria-label="Choose"
+ defaultValue="left"
options={[
{ value: 'left', label: 'Left' },
{ value: 'right', label: 'Right' },
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/galleryRenderTests.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/galleryRenderTests.ts
index 8e7c67b7ac8..a92757c7f24 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/galleryRenderTests.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/galleryRenderTests.ts
@@ -10,15 +10,6 @@ export const galleryRenderTest = createGalleryRenderTest({
expectedFailedComponents: [],
});
-// Unselected radios need Element.matches(':disabled'); React radio groups
-// also need compareDocumentPosition, which the sandbox DOM does not implement.
-export const inputReactTest = createGalleryRenderTest({
- expectedFailedComponents: ['Radio', 'RadioGroup'],
-});
-export const inputPreactTest = createGalleryRenderTest({
- expectedFailedComponents: ['Radio'],
-});
-
// Monaco cannot load scripts inside the sandbox worker, so the wrapper mounts
// but the editor's onMount never fires.
export const codeEditorTest: TwentyUiGalleryPlayFunction = async ({
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputPreactTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputPreactTest.ts
new file mode 100644
index 00000000000..9becb5bdb76
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputPreactTest.ts
@@ -0,0 +1,40 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { SANDBOX_ERROR_PATTERNS } from '@/__stories__/twenty-ui-gallery/constants/SANDBOX_ERROR_PATTERNS';
+import { SEGMENTED_CONTROL_ORDERING_ERROR } from '@/__stories__/twenty-ui-gallery/constants/SEGMENTED_CONTROL_ORDERING_ERROR';
+import { expectSandboxErrors } from '@/__stories__/twenty-ui-gallery/utils/expectSandboxErrors';
+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+import { createGalleryRenderTest } from '@/__stories__/twenty-ui-gallery/utils/createGalleryRenderTest';
+
+export const inputPreactTest: TwentyUiGalleryPlayFunction = async (context) => {
+ await createGalleryRenderTest({ expectedFailedComponents: ['Radio'] })(
+ context,
+ );
+
+ const canvas = within(context.canvasElement);
+
+ await userEvent.click(
+ within(canvas.getByRole('radiogroup', { name: 'Choose' })).getByRole(
+ 'radio',
+ { name: 'Right' },
+ ),
+ );
+ await expectSandboxErrors({
+ requiredErrors: [SANDBOX_ERROR_PATTERNS.COMPOSED_PATH],
+ });
+ await waitFor(() => {
+ const status = canvas.getByTestId('gallery-status');
+
+ expect(status).toHaveAttribute(
+ 'data-failed-names',
+ 'Radio, SegmentedControl',
+ );
+ expect(status).toHaveAttribute(
+ 'data-failed-messages',
+ expect.stringMatching(SEGMENTED_CONTROL_ORDERING_ERROR),
+ );
+ });
+ await expect(
+ canvas.queryByRole('radiogroup', { name: 'Choose' }),
+ ).not.toBeInTheDocument();
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputReactTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputReactTest.ts
new file mode 100644
index 00000000000..94faac0a9fa
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/inputReactTest.ts
@@ -0,0 +1,18 @@
+import { expect, within } from 'storybook/test';
+
+import { SEGMENTED_CONTROL_ORDERING_ERROR } from '@/__stories__/twenty-ui-gallery/constants/SEGMENTED_CONTROL_ORDERING_ERROR';
+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+import { createGalleryRenderTest } from '@/__stories__/twenty-ui-gallery/utils/createGalleryRenderTest';
+
+export const inputReactTest: TwentyUiGalleryPlayFunction = async (context) => {
+ await createGalleryRenderTest({
+ expectedFailedComponents: ['Radio', 'RadioGroup', 'SegmentedControl'],
+ })(context);
+
+ expect(
+ within(context.canvasElement).getByTestId('gallery-status'),
+ ).toHaveAttribute(
+ 'data-failed-messages',
+ expect.stringMatching(SEGMENTED_CONTROL_ORDERING_ERROR),
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlanComparisonTable.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlanComparisonTable.tsx
index 62ffcd18660..eea1cc8e626 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlanComparisonTable.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlanComparisonTable.tsx
@@ -185,9 +185,9 @@ export const SettingsBillingPlanComparisonTable = ({
</StyledPlanSubtitle>
</StyledHeaderText>
<SegmentedControl
- ariaLabel={t`Billing period`}
+ aria-label={t`Billing period`}
itemWidth="content"
- onChange={onBillingIntervalChange}
+ onValueChange={onBillingIntervalChange}
options={billingIntervalOptions}
value={billingInterval}
/>
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/__stories__/SettingsBillingPlanComparisonTable.stories.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/__stories__/SettingsBillingPlanComparisonTable.stories.tsx
new file mode 100644
index 00000000000..18a52b586a1
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/__stories__/SettingsBillingPlanComparisonTable.stories.tsx
@@ -0,0 +1,87 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { type ComponentProps, useState } from 'react';
+import { expect, fn, userEvent, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { SettingsBillingPlanComparisonTable } from '@/settings/billing/components/internal/SettingsBillingPlanComparisonTable';
+import {
+ BillingPlanKey,
+ SubscriptionInterval,
+} from '~/generated-metadata/graphql';
+
+const BillingComparison = (
+ props: ComponentProps<typeof SettingsBillingPlanComparisonTable>,
+) => {
+ const [billingInterval, setBillingInterval] = useState(props.billingInterval);
+
+ return (
+ <SettingsBillingPlanComparisonTable
+ {...props}
+ billingInterval={billingInterval}
+ onBillingIntervalChange={(interval) => {
+ props.onBillingIntervalChange(interval);
+ setBillingInterval(interval);
+ }}
+ />
+ );
+};
+
+const meta = {
+ title: 'Modules/Settings/Billing/SettingsBillingPlanComparisonTable',
+ component: SettingsBillingPlanComparisonTable,
+ decorators: [ComponentDecorator],
+ parameters: { container: { width: 694 } },
+ args: {
+ billingInterval: SubscriptionInterval.Year,
+ onBillingIntervalChange: fn(),
+ planActions: {
+ [BillingPlanKey.PRO]: { title: 'Choose Pro', variant: 'solid' },
+ [BillingPlanKey.ENTERPRISE]: {
+ title: 'Choose Organization',
+ variant: 'outline',
+ },
+ },
+ planPrices: {
+ [BillingPlanKey.PRO]: {
+ [SubscriptionInterval.Year]: 9,
+ [SubscriptionInterval.Month]: 12,
+ },
+ [BillingPlanKey.ENTERPRISE]: {
+ [SubscriptionInterval.Year]: 19,
+ [SubscriptionInterval.Month]: 25,
+ },
+ },
+ },
+ render: (args) => <BillingComparison {...args} />,
+} satisfies Meta<typeof SettingsBillingPlanComparisonTable>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const BillingPeriod: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const period = within(
+ canvas.getByRole('radiogroup', { name: 'Billing period' }),
+ );
+
+ await expect(period.getByRole('radio', { name: 'Annual' })).toBeChecked();
+ await expect(
+ canvas.getByText('Save 25% when billed annually'),
+ ).toBeVisible();
+ await userEvent.click(period.getByRole('radio', { name: 'Monthly' }));
+ await expect(period.getByRole('radio', { name: 'Monthly' })).toBeChecked();
+ await expect(args.onBillingIntervalChange).toHaveBeenLastCalledWith(
+ SubscriptionInterval.Month,
+ );
+ await expect(canvas.getByText('Billed monthly')).toBeVisible();
+ await userEvent.keyboard('{ArrowLeft}');
+ await expect(period.getByRole('radio', { name: 'Annual' })).toBeChecked();
+ await expect(args.onBillingIntervalChange).toHaveBeenLastCalledWith(
+ SubscriptionInterval.Year,
+ );
+ await expect(
+ canvas.getByText('Save 25% when billed annually'),
+ ).toBeVisible();
+ },
+};
diff --git a/packages/twenty-ui/CHANGELOG.md b/packages/twenty-ui/CHANGELOG.md
index 7a1a1410148..7b19caaa42f 100644
--- a/packages/twenty-ui/CHANGELOG.md
+++ b/packages/twenty-ui/CHANGELOG.md
@@ -10,5 +10,6 @@
- Import shared compositions, including `JsonTree`, menu presets, and Toast components and hooks, from `twenty-ui/components`. Foundational controls retain `twenty-ui/primitives/<family>` imports. The optional code editor retains `twenty-ui/components/code-editor`.
- Field displays, application links, placeholders, and feature animations are no longer package exports. External applications must own these integrations or compose supported primitives. Internal implementation parts are private.
- `Info` uses `href` and `render` in place of `to`. Replace `AnimatedEaseInOut` with `AnimatedExpandableContainer`.
+- `SegmentedControl` is a radio group. Use `aria-label` or `aria-labelledby` (one is required), `value` or `defaultValue`, and `onValueChange(value, eventDetails)` in place of `ariaLabel`, `value`, and `onChange(value)`. Options take `startIcon` and `'aria-label'` in place of `Icon` and `ariaLabel`. `role` and `width` are removed: use `Tabs` for tab lists and `className` or `style` to size the control. Arrow keys select the next option, Enter no longer selects, and choosing the selected option again no longer calls `onValueChange`.
Keep `twenty-ui`, `twenty-sdk`, and `twenty-client-sdk` versions aligned when upgrading Twenty apps.
diff --git a/packages/twenty-ui/src/primitives/input/SegmentedControl/SegmentedControl.module.scss b/packages/twenty-ui/src/primitives/input/SegmentedControl/SegmentedControl.module.scss
index 6c902759bc5..87daf4ac0d2 100644
--- a/packages/twenty-ui/src/primitives/input/SegmentedControl/SegmentedControl.module.scss
+++ b/packages/twenty-ui/src/primitives/input/SegmentedControl/SegmentedControl.module.scss
@@ -5,15 +5,22 @@
border-radius: var(--t-border-radius-pill);
corner-shape: round;
box-sizing: border-box;
- display: inline-flex;
+ display: inline-grid;
flex-shrink: 0;
gap: 2px;
- height: var(--t-spacing-7);
+ grid-auto-columns: minmax(0, 1fr);
+ grid-auto-flow: column;
+ block-size: var(--t-spacing-7);
padding: 3px;
- width: var(--segmented-control-width, auto);
+
+ &[data-item-width='content'] {
+ grid-auto-columns: max-content;
+ }
}
.item {
+ @include focus-ring;
+
align-items: center;
background: transparent;
border: 0;
@@ -22,45 +29,41 @@
color: var(--t-font-color-secondary);
cursor: pointer;
display: flex;
- flex: 1;
font-family: var(--t-font-family);
font-size: var(--t-font-size-md);
font-weight: var(--t-font-weight-medium);
gap: var(--t-spacing-1);
- height: 100%;
+ block-size: 100%;
justify-content: center;
line-height: 1.4;
- min-width: 0;
+ min-inline-size: 0;
padding: 0 var(--t-spacing-2);
transition:
background 0.1s ease,
color 0.1s ease;
+ user-select: none;
white-space: nowrap;
- &:hover {
+ &:hover:not([data-checked]):not([data-disabled]):not([data-readonly]) {
background: var(--t-background-transparent-lighter);
}
- &:disabled {
- cursor: not-allowed;
- }
-
- &[data-active] {
+ &[data-checked] {
background: var(--t-background-transparent-light);
color: var(--t-font-color-primary);
+ }
- &:hover {
- background: var(--t-background-transparent-light);
- }
+ &[data-disabled] {
+ cursor: not-allowed;
}
-}
-.item[data-item-width='content'] {
- flex: 0 0 max-content;
+ &[data-readonly] {
+ cursor: default;
+ }
}
.iconOnly {
- min-width: var(--t-spacing-5);
+ min-inline-size: var(--t-spacing-5);
padding: 0;
}
@@ -68,13 +71,19 @@
align-items: center;
display: flex;
flex-shrink: 0;
- height: var(--t-spacing-5);
+ block-size: var(--t-spacing-5);
justify-content: center;
- width: var(--t-spacing-5);
+ inline-size: var(--t-spacing-5);
+
+ > svg,
+ > :only-child > svg:only-child {
+ block-size: calc(var(--t-icon-size-md) * 1px);
+ inline-size: calc(var(--t-icon-size-md) * 1px);
+ }
}
.label {
- min-width: 0;
+ min-inline-size: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
diff --git a/packages/twenty-ui/src/primitives/input/SegmentedControl/SegmentedControl.tsx b/packages/twenty-ui/src/primitives/input/SegmentedControl/SegmentedControl.tsx
index d3adb499901..8a37ff1d087 100644
--- a/packages/twenty-ui/src/primitives/input/SegmentedControl/SegmentedControl.tsx
+++ b/packages/twenty-ui/src/primitives/input/SegmentedControl/SegmentedControl.tsx
@@ -1,198 +1,46 @@
-import { type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
-
-import { type IconComponent } from '@ui/icon';
-import { useTheme } from '@ui/theme-constants';
-import { isDefined } from '@ui/utilities/utils/isDefined';
-
+import { Radio as RadioPrimitive } from '@base-ui/react/radio';
+import { RadioGroup as RadioGroupPrimitive } from '@base-ui/react/radio-group';
import { clsx } from 'clsx';
-import styles from './SegmentedControl.module.scss';
-
-type SegmentedControlOptionBase<Value extends string> = {
- disabled?: boolean;
- value: Value;
-};
-
-type SegmentedControlOptionWithLabel<Value extends string> =
- SegmentedControlOptionBase<Value> & {
- Icon?: IconComponent;
- ariaLabel?: string;
- label: NonNullable<ReactNode>;
- };
-
-type SegmentedControlOptionIconOnly<Value extends string> =
- SegmentedControlOptionBase<Value> & {
- Icon: IconComponent;
- ariaLabel: string;
- label?: never;
- };
+import { isRenderableSlot } from '@ui/primitives/navigation/ListItem/internal/isRenderableSlot';
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
-export type SegmentedControlOption<Value extends string> =
- | SegmentedControlOptionWithLabel<Value>
- | SegmentedControlOptionIconOnly<Value>;
-
-type SegmentedControlOptionButtonProps<Value extends string> = {
- Icon?: IconComponent;
- ariaLabel?: string;
- disabled?: boolean;
- label?: ReactNode;
- value: Value;
-};
-
-type SegmentedControlItemWidth = 'content' | 'equal';
-
-type SegmentedControlStyle = CSSProperties & {
- '--segmented-control-width'?: string;
-};
-
-export type SegmentedControlProps<Value extends string> = {
- ariaLabel: string;
- itemWidth?: SegmentedControlItemWidth;
- onChange: (value: Value) => void;
- options: SegmentedControlOption<Value>[];
- role?: 'group' | 'tablist';
- value: Value;
- width?: number | string;
-};
+import styles from './SegmentedControl.module.scss';
+import { type SegmentedControlProps } from './types/SegmentedControlProps';
-export const SegmentedControl = <Value extends string>({
- ariaLabel,
+export const SegmentedControl = <TValue extends string>({
+ className,
itemWidth = 'equal',
- onChange,
options,
- role = 'group',
- value,
- width,
-}: SegmentedControlProps<Value>) => {
- const theme = useTheme();
- const isTabList = role === 'tablist';
- const segmentedControlStyle: SegmentedControlStyle | undefined = isDefined(
- width,
- )
- ? {
- '--segmented-control-width':
- typeof width === 'number' ? `${width}px` : width,
- }
- : undefined;
-
- const focusAndSelectOption = ({
- event,
- optionIndex,
- optionValue,
- }: {
- event: KeyboardEvent<HTMLButtonElement>;
- optionIndex: number;
- optionValue: Value;
- }) => {
- onChange(optionValue);
-
- const enabledOptionButtons = Array.from(
- event.currentTarget.parentElement?.querySelectorAll<HTMLButtonElement>(
- 'button:not(:disabled)',
- ) ?? [],
- );
-
- enabledOptionButtons[optionIndex]?.focus();
- };
-
- const handleTabKeyDown = (
- event: KeyboardEvent<HTMLButtonElement>,
- optionValue: Value,
- ) => {
- if (!isTabList) {
- return;
- }
-
- const enabledOptions = options.filter((option) => !option.disabled);
- const currentOptionIndex = enabledOptions.findIndex(
- (option) => option.value === optionValue,
- );
-
- if (currentOptionIndex === -1 || enabledOptions.length === 0) {
- return;
- }
-
- const lastOptionIndex = enabledOptions.length - 1;
-
- const optionIndexByKey: Partial<Record<string, number>> = {
- ArrowDown: (currentOptionIndex + 1) % enabledOptions.length,
- ArrowLeft:
- currentOptionIndex === 0 ? lastOptionIndex : currentOptionIndex - 1,
- ArrowRight: (currentOptionIndex + 1) % enabledOptions.length,
- ArrowUp:
- currentOptionIndex === 0 ? lastOptionIndex : currentOptionIndex - 1,
- End: lastOptionIndex,
- Home: 0,
- };
-
- const nextOptionIndex = optionIndexByKey[event.key];
-
- if (!isDefined(nextOptionIndex)) {
- return;
- }
-
- event.preventDefault();
- focusAndSelectOption({
- event,
- optionIndex: nextOptionIndex,
- optionValue: enabledOptions[nextOptionIndex].value,
- });
- };
-
- return (
- <div
- className={styles.container}
- role={role}
- aria-label={ariaLabel}
- style={segmentedControlStyle}
- >
- {options.map(
- ({
- Icon,
- ariaLabel: itemAriaLabel,
- disabled,
- label,
- value: optionValue,
- }: SegmentedControlOptionButtonProps<Value>) => {
- const isSelected = optionValue === value;
- const inferredAriaLabel =
- itemAriaLabel ?? (typeof label === 'string' ? label : undefined);
- const hasLabel = isDefined(label);
-
- return (
- <button
- aria-label={inferredAriaLabel}
- aria-pressed={!isTabList ? isSelected : undefined}
- aria-selected={isTabList ? isSelected : undefined}
- className={clsx(styles.item, !hasLabel && styles.iconOnly)}
- data-active={isSelected || undefined}
- disabled={disabled}
- data-item-width={itemWidth}
- key={optionValue}
- onClick={() => onChange(optionValue)}
- onKeyDown={(event) => handleTabKeyDown(event, optionValue)}
- role={isTabList ? 'tab' : undefined}
- tabIndex={isTabList ? (isSelected ? 0 : -1) : undefined}
- type="button"
- >
- {Icon && (
- <span className={styles.icon}>
- <Icon
- aria-hidden={hasLabel || isDefined(inferredAriaLabel)}
- color={
- isSelected
- ? theme.font.color.primary
- : theme.font.color.secondary
- }
- size={theme.icon.size.md}
- />
- </span>
- )}
- {hasLabel && <span className={styles.label}>{label}</span>}
- </button>
- );
- },
- )}
- </div>
- );
-};
+ ...props
+}: SegmentedControlProps<TValue>) => (
+ <RadioGroupPrimitive
+ {...props}
+ className={mergeClassNames(styles.container, className)}
+ data-item-width={itemWidth}
+ >
+ {options.map(
+ ({ 'aria-label': ariaLabel, disabled, label, startIcon, value }) => (
+ <RadioPrimitive.Root
+ key={value}
+ value={value}
+ disabled={disabled}
+ aria-label={ariaLabel}
+ className={clsx(
+ styles.item,
+ !isRenderableSlot(label) && styles.iconOnly,
+ )}
+ >
+ {isRenderableSlot(startIcon) && (
+ <span className={styles.icon} aria-hidden>
+ {startIcon}
+ </span>
+ )}
+ {isRenderableSlot(label) && (
+ <span className={styles.label}>{label}</span>
+ )}
+ </RadioPrimitive.Root>
+ ),
+ )}
+ </RadioGroupPrimitive>
+);
diff --git a/packages/twenty-ui/src/primitives/input/SegmentedControl/__stories__/SegmentedControl.stories.tsx b/packages/twenty-ui/src/primitives/input/SegmentedControl/__stories__/SegmentedControl.stories.tsx
index 8356d0a7b43..58dd261b39b 100644
--- a/packages/twenty-ui/src/primitives/input/SegmentedControl/__stories__/SegmentedControl.stories.tsx
+++ b/packages/twenty-ui/src/primitives/input/SegmentedControl/__stories__/SegmentedControl.stories.tsx
@@ -1,76 +1,132 @@
import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
import { IconComment, IconHome } from '@ui/icon';
+import { TextDirectionProvider } from '@ui/primitives/layout/TextDirectionProvider/TextDirectionProvider';
import { ComponentDecorator } from '@ui/testing';
-import { useState } from 'react';
-import {
- SegmentedControl,
- type SegmentedControlOption,
-} from '@ui/primitives/input/SegmentedControl/SegmentedControl';
+import { SegmentedControl } from '../SegmentedControl';
-type InteractiveSegmentedControlProps = {
- initialValue: string;
- options: SegmentedControlOption<string>[];
- role?: 'group' | 'tablist';
+const meta: Meta<typeof SegmentedControl> = {
+ title: 'UI/Input/SegmentedControl',
+ component: SegmentedControl,
+ decorators: [ComponentDecorator],
+ args: {
+ 'aria-label': 'Billing period',
+ defaultValue: 'annual',
+ options: [
+ { label: 'Annual', value: 'annual' },
+ { label: 'Monthly', value: 'monthly' },
+ ],
+ },
};
-const InteractiveSegmentedControl = ({
- initialValue,
- options,
- role,
-}: InteractiveSegmentedControlProps) => {
- const [value, setValue] = useState(initialValue);
+export default meta;
+type Story = StoryObj<typeof SegmentedControl>;
- return (
- <SegmentedControl
- ariaLabel="Segmented control"
- onChange={setValue}
- options={options}
- role={role}
- value={value}
- />
- );
-};
+export const Default: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const monthlyLabel = canvas.getByText('Monthly');
-const meta: Meta<typeof InteractiveSegmentedControl> = {
- title: 'UI/Input/SegmentedControl',
- component: InteractiveSegmentedControl,
+ await expect(
+ canvas.getByRole('radio', { name: 'Annual' }).getBoundingClientRect()
+ .width,
+ ).toBe(
+ canvas.getByRole('radio', { name: 'Monthly' }).getBoundingClientRect()
+ .width,
+ );
+ await expect(monthlyLabel.scrollWidth).toBeLessThanOrEqual(
+ monthlyLabel.clientWidth,
+ );
+ },
};
-export default meta;
-type Story = StoryObj<typeof InteractiveSegmentedControl>;
+export const Dark: Story = {
+ globals: { colorScheme: 'dark' },
+};
-export const Default: Story = {
+export const WithDisabledOption: Story = {
args: {
- initialValue: 'annual',
options: [
{ label: 'Annual', value: 'annual' },
{ label: 'Monthly', value: 'monthly' },
+ { disabled: true, label: 'Weekly', value: 'weekly' },
],
},
- decorators: [ComponentDecorator],
};
-export const IconOnlyTabList: Story = {
+export const IconOnly: Story = {
args: {
- initialValue: 'home',
+ 'aria-label': 'Start page',
+ defaultValue: 'home',
options: [
- { Icon: IconHome, ariaLabel: 'Home', value: 'home' },
- { Icon: IconComment, ariaLabel: 'Chat', value: 'chat' },
+ {
+ startIcon: <IconHome data-testid="direct-icon" />,
+ 'aria-label': 'Home',
+ value: 'home',
+ },
+ {
+ startIcon: (
+ <span>
+ <IconComment data-testid="wrapped-icon" />
+ </span>
+ ),
+ 'aria-label': 'Chat',
+ value: 'chat',
+ },
],
- role: 'tablist',
},
- decorators: [ComponentDecorator],
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const home = canvas.getByRole('radio', { name: 'Home' });
+ const chat = canvas.getByRole('radio', { name: 'Chat' });
+ const directIcon = canvas.getByTestId('direct-icon');
+ const directIconBounds = directIcon.getBoundingClientRect();
+ const wrappedIconBounds = canvas
+ .getByTestId('wrapped-icon')
+ .getBoundingClientRect();
+
+ await expect(directIcon.parentElement).toHaveAttribute(
+ 'aria-hidden',
+ 'true',
+ );
+ await expect(directIconBounds.width).toBeGreaterThan(0);
+ await expect(wrappedIconBounds.width).toBe(directIconBounds.width);
+ await expect(wrappedIconBounds.height).toBe(directIconBounds.height);
+ await expect(home).toBeChecked();
+ await expect(chat).not.toBeChecked();
+ await userEvent.click(chat);
+ await expect(chat).toBeChecked();
+ await expect(home).not.toBeChecked();
+ },
};
-export const WithDisabledOption: Story = {
- args: {
- initialValue: 'annual',
- options: [
- { label: 'Annual', value: 'annual' },
- { label: 'Monthly', value: 'monthly' },
- { disabled: true, label: 'Weekly', value: 'weekly' },
- ],
+export const ContentWidth: Story = {
+ args: { itemWidth: 'content' },
+};
+
+export const EqualWidth: Story = {
+ args: { style: { width: 280 } },
+};
+
+export const RightToLeft: Story = {
+ render: (args) => (
+ <TextDirectionProvider direction="rtl">
+ <SegmentedControl {...args} dir="rtl" />
+ </TextDirectionProvider>
+ ),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const annual = canvas.getByRole('radio', { name: 'Annual' });
+ const monthly = canvas.getByRole('radio', { name: 'Monthly' });
+
+ await userEvent.tab();
+ await expect(annual).toHaveFocus();
+ await userEvent.keyboard('{ArrowLeft}');
+ await waitFor(() => expect(monthly).toHaveFocus());
+ await expect(monthly).toBeChecked();
+ await userEvent.keyboard('{ArrowRight}');
+ await waitFor(() => expect(annual).toBeChecked());
},
- decorators: [ComponentDecorator],
};
diff --git a/packages/twenty-ui/src/primitives/input/SegmentedControl/__stories__/SegmentedControlInteractions.stories.tsx b/packages/twenty-ui/src/primitives/input/SegmentedControl/__stories__/SegmentedControlInteractions.stories.tsx
new file mode 100644
index 00000000000..87099168d35
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/input/SegmentedControl/__stories__/SegmentedControlInteractions.stories.tsx
@@ -0,0 +1,196 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useState } from 'react';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+
+import { Button } from '@ui/primitives/input/Button/Button';
+import { ComponentDecorator } from '@ui/testing';
+
+import { SegmentedControl } from '../SegmentedControl';
+import { type SegmentedControlProps } from '../types/SegmentedControlProps';
+
+const PendingExample = (props: SegmentedControlProps<string>) => {
+ const [isPending, setIsPending] = useState(false);
+
+ return (
+ <>
+ <SegmentedControl
+ {...props}
+ disabled={isPending}
+ onValueChange={(value, eventDetails) => {
+ props.onValueChange?.(value, eventDetails);
+ setIsPending(true);
+ }}
+ />
+ <Button onClick={() => setIsPending(false)}>Finish saving</Button>
+ </>
+ );
+};
+
+const FormExample = (props: SegmentedControlProps<string>) => {
+ const [savedAppearance, setSavedAppearance] = useState('Not saved');
+
+ return (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ setSavedAppearance(
+ String(new FormData(event.currentTarget).get('appearance')),
+ );
+ }}
+ >
+ <SegmentedControl {...props} name="appearance" />
+ <Button type="submit">Save appearance</Button>
+ <output aria-label="Saved appearance">{savedAppearance}</output>
+ </form>
+ );
+};
+
+const meta: Meta<typeof SegmentedControl> = {
+ title: 'UI/Input/SegmentedControl/Interactions',
+ component: SegmentedControl,
+ decorators: [ComponentDecorator],
+ args: {
+ 'aria-label': 'Appearance',
+ defaultValue: 'system',
+ onValueChange: fn(),
+ options: [
+ { value: 'system', label: 'System' },
+ { value: 'light', label: 'Light', disabled: true },
+ { value: 'dark', label: 'Dark' },
+ { value: 'contrast', label: 'High contrast' },
+ ],
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof SegmentedControl>;
+
+export const Uncontrolled: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const dark = canvas.getByRole('radio', { name: 'Dark' });
+
+ await expect(
+ canvas.getByRole('radiogroup', { name: 'Appearance' }),
+ ).toBeVisible();
+ await expect(canvas.getByRole('radio', { name: 'System' })).toBeChecked();
+ await userEvent.click(dark);
+ await userEvent.click(dark);
+
+ await expect(dark).toBeChecked();
+ await expect(
+ canvas.getByRole('radio', { name: 'System' }),
+ ).not.toBeChecked();
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ await expect(args.onValueChange).toHaveBeenCalledWith(
+ 'dark',
+ expect.anything(),
+ );
+ },
+};
+
+export const DisabledOption: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const light = canvas.getByRole('radio', { name: 'Light' });
+
+ await expect(light).toHaveAttribute('aria-disabled', 'true');
+ await userEvent.click(light);
+ await expect(canvas.getByRole('radio', { name: 'System' })).toBeChecked();
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+ },
+};
+
+export const DisabledCheckedOption: Story = {
+ args: { defaultValue: 'light' },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const dark = canvas.getByRole('radio', { name: 'Dark' });
+
+ await userEvent.tab();
+ await expect(canvas.getByRole('radio', { name: 'Light' })).toHaveFocus();
+ await userEvent.keyboard('{ArrowRight}');
+ await waitFor(() => expect(dark).toHaveFocus());
+ await expect(dark).toBeChecked();
+ },
+};
+
+export const Pending: Story = {
+ render: (args) => <PendingExample {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const dark = canvas.getByRole('radio', { name: 'Dark' });
+ const contrast = canvas.getByRole('radio', { name: 'High contrast' });
+
+ await userEvent.tab();
+ await userEvent.keyboard('{ArrowRight}');
+ await waitFor(() => expect(dark).toBeChecked());
+ for (const choice of canvas.getAllByRole('radio')) {
+ await expect(choice).toHaveAttribute('aria-disabled', 'true');
+ }
+ await expect(dark).toHaveFocus();
+ await userEvent.keyboard('{ArrowRight}');
+ await expect(dark).toHaveFocus();
+ await userEvent.click(contrast);
+ await expect(contrast).not.toBeChecked();
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Finish saving' }),
+ );
+ await expect(contrast).not.toHaveAttribute('aria-disabled');
+ await userEvent.click(contrast);
+ await expect(contrast).toBeChecked();
+ await expect(args.onValueChange).toHaveBeenCalledTimes(2);
+ await expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'contrast',
+ expect.anything(),
+ );
+ },
+};
+
+export const FormSubmission: Story = {
+ render: (args) => <FormExample {...args} />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const savedAppearance = canvas.getByLabelText('Saved appearance');
+
+ await userEvent.click(canvas.getByRole('radio', { name: 'Dark' }));
+ await expect(savedAppearance).toHaveTextContent('Not saved');
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Save appearance' }),
+ );
+ await expect(savedAppearance).toHaveTextContent('dark');
+ },
+};
+
+export const Keyboard: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const system = canvas.getByRole('radio', { name: 'System' });
+ const dark = canvas.getByRole('radio', { name: 'Dark' });
+ const contrast = canvas.getByRole('radio', { name: 'High contrast' });
+
+ await userEvent.tab();
+ await expect(system).toHaveFocus();
+ await userEvent.keyboard('{ArrowRight}');
+ await waitFor(() => expect(dark).toHaveFocus());
+ await expect(dark).toBeChecked();
+ await expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'dark',
+ expect.anything(),
+ );
+ await userEvent.keyboard('{ArrowRight}');
+ await waitFor(() => expect(contrast).toBeChecked());
+ await userEvent.keyboard('{ArrowRight}');
+ await waitFor(() => expect(system).toHaveFocus());
+ await expect(system).toBeChecked();
+ await userEvent.keyboard('{ArrowLeft}');
+ await waitFor(() => expect(contrast).toBeChecked());
+ await userEvent.tab({ shift: true });
+ await expect(contrast).not.toHaveFocus();
+ await userEvent.tab();
+ await expect(contrast).toHaveFocus();
+ },
+};
diff --git a/packages/twenty-ui/src/primitives/input/SegmentedControl/__tests__/SegmentedControl.test.tsx b/packages/twenty-ui/src/primitives/input/SegmentedControl/__tests__/SegmentedControl.test.tsx
new file mode 100644
index 00000000000..edd8bdca97b
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/input/SegmentedControl/__tests__/SegmentedControl.test.tsx
@@ -0,0 +1,17 @@
+import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';
+
+import { SegmentedControl } from '../SegmentedControl';
+import styles from '../SegmentedControl.module.scss';
+
+const OPTIONS = [
+ { label: 'Annual', value: 'annual' },
+ { label: 'Weekly', value: 'weekly', disabled: true },
+ { label: 'Monthly', value: 'monthly' },
+];
+
+runComponentConformance({
+ name: 'SegmentedControl',
+ element: <SegmentedControl aria-label="Billing period" options={OPTIONS} />,
+ refInstanceOf: HTMLDivElement,
+ ownClassName: styles.container,
+});
diff --git a/packages/twenty-ui/src/primitives/input/SegmentedControl/types/SegmentedControlOption.ts b/packages/twenty-ui/src/primitives/input/SegmentedControl/types/SegmentedControlOption.ts
new file mode 100644
index 00000000000..02c50392ac9
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/input/SegmentedControl/types/SegmentedControlOption.ts
@@ -0,0 +1,17 @@
+import { type ReactNode } from 'react';
+
+export type SegmentedControlOption<TValue extends string = string> = {
+ disabled?: boolean;
+ value: TValue;
+} & (
+ | {
+ label: NonNullable<ReactNode>;
+ startIcon?: ReactNode;
+ 'aria-label'?: string;
+ }
+ | {
+ label?: never;
+ startIcon: NonNullable<ReactNode>;
+ 'aria-label': string;
+ }
+);
diff --git a/packages/twenty-ui/src/primitives/input/SegmentedControl/types/SegmentedControlProps.ts b/packages/twenty-ui/src/primitives/input/SegmentedControl/types/SegmentedControlProps.ts
new file mode 100644
index 00000000000..1f835460f4f
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/input/SegmentedControl/types/SegmentedControlProps.ts
@@ -0,0 +1,11 @@
+import { type RadioGroupProps } from '@ui/primitives/input/RadioGroup/types/RadioGroupProps';
+
+import { type SegmentedControlOption } from './SegmentedControlOption';
+
+export type SegmentedControlProps<TValue extends string = string> = Omit<
+ RadioGroupProps<TValue>,
+ 'aria-label' | 'aria-labelledby' | 'children' | 'role'
+> & {
+ itemWidth?: 'content' | 'equal';
+ options: readonly SegmentedControlOption<TValue>[];
+} & ({ 'aria-label': string } | { 'aria-labelledby': string });
diff --git a/packages/twenty-ui/src/primitives/input/index.ts b/packages/twenty-ui/src/primitives/input/index.ts
index 15aeadb0f00..4f76e45bdbd 100644
--- a/packages/twenty-ui/src/primitives/input/index.ts
+++ b/packages/twenty-ui/src/primitives/input/index.ts
@@ -29,11 +29,9 @@ export { Radio } from './Radio/Radio';
export type { RadioProps } from './Radio/types/RadioProps';
export { RadioGroup } from './RadioGroup/RadioGroup';
export type { RadioGroupProps } from './RadioGroup/types/RadioGroupProps';
-export type {
- SegmentedControlOption,
- SegmentedControlProps,
-} from './SegmentedControl/SegmentedControl';
export { SegmentedControl } from './SegmentedControl/SegmentedControl';
+export type { SegmentedControlOption } from './SegmentedControl/types/SegmentedControlOption';
+export type { SegmentedControlProps } from './SegmentedControl/types/SegmentedControlProps';
export { Select } from './Select/Select';
export type { SelectGroupLabelProps } from './Select/types/SelectGroupLabelProps';
export type { SelectGroupProps } from './Select/types/SelectGroupProps';
diff --git a/packages/twenty-ui/src/primitives/navigation/Tabs/__stories__/Tabs.stories.tsx b/packages/twenty-ui/src/primitives/navigation/Tabs/__stories__/Tabs.stories.tsx
index eca0d6a721b..d9a236637a5 100644
--- a/packages/twenty-ui/src/primitives/navigation/Tabs/__stories__/Tabs.stories.tsx
+++ b/packages/twenty-ui/src/primitives/navigation/Tabs/__stories__/Tabs.stories.tsx
@@ -173,6 +173,27 @@ export const Highlighted: Story = {
},
};
+export const IconOnly: Story = {
+ decorators: [ComponentDecorator],
+ parameters: { container: { width: 360 } },
+ args: {
+ 'aria-label': 'Overview',
+ children: undefined,
+ startIcon: <IconInfoCircle />,
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.getByRole('tab', { name: 'Overview' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await expect(
+ canvas.getByRole('tabpanel', { name: 'Overview' }),
+ ).toHaveTextContent('Record overview');
+ },
+};
+
export const Vertical: Story = {
decorators: [ComponentDecorator],
parameters: { container: { width: 360 } },