Skip to content

The open alternative to Salesforce, designed for AI.

Migrate twenty-ui Radio and RadioGroup (#25715)

Raphaël Bosifdec2d8bbdf0
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 9ab9634896d..6cb29a941d4 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
@@ -120,15 +120,15 @@ export const IconPreact: Story = createGalleryStory(
'preact',
);
-// KNOWN ISSUE (TDD): Base UI 1.8 radios require Element.matches(':disabled'),
-// which the sandbox DOM does not implement.
+// KNOWN ISSUE (TDD): The sandbox DOM lacks Element.matches(':disabled') for
+// unselected radios and Node.compareDocumentPosition() for React radio groups.
export const InputReact: Story = createKnownFailureGalleryStory(
'twenty-ui-input-gallery',
- ['CardPicker', 'Radio', 'RadioGroup'],
+ ['Radio', 'RadioGroup'],
);
export const InputPreact: Story = createKnownFailureGalleryStory(
'twenty-ui-input-gallery',
- ['CardPicker'],
+ ['Radio'],
'preact',
);
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 f1d38b598ff..9da777b8377 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
@@ -70,9 +70,9 @@ const INPUT_ENTRIES: GalleryEntry[] = [
{
name: 'CardPicker',
node: (
- <CardPicker checked={false} handleChange={() => {}}>
- Card
- </CardPicker>
+ <RadioGroup defaultValue="card" aria-label="Card selection">
+ <CardPicker value="card">Card</CardPicker>
+ </RadioGroup>
),
},
{
@@ -178,14 +178,18 @@ const INPUT_ENTRIES: GalleryEntry[] = [
},
{
name: 'Radio',
- node: <Radio checked={false} label="Radio" />,
+ node: (
+ <RadioGroup aria-label="Radio example">
+ <Radio value="radio">Radio</Radio>
+ </RadioGroup>
+ ),
},
{
name: 'RadioGroup',
node: (
- <RadioGroup value="a">
- <Radio value="a" label="A" />
- <Radio value="b" label="B" />
+ <RadioGroup defaultValue="a" aria-label="Letter">
+ <Radio value="a">A</Radio>
+ <Radio value="b">B</Radio>
</RadioGroup>
),
},
diff --git a/packages/twenty-front/src/modules/onboarding/components/upgrade-free-trial/OnboardingPlanCard.tsx b/packages/twenty-front/src/modules/onboarding/components/upgrade-free-trial/OnboardingPlanCard.tsx
index b6e61e06121..29b4f2ddd16 100644
--- a/packages/twenty-front/src/modules/onboarding/components/upgrade-free-trial/OnboardingPlanCard.tsx
+++ b/packages/twenty-front/src/modules/onboarding/components/upgrade-free-trial/OnboardingPlanCard.tsx
@@ -1,5 +1,5 @@
import { styled } from '@linaria/react';
-import { isValidElement, type ReactNode } from 'react';
+import { isValidElement, type ReactNode, useId } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { Radio } from 'twenty-ui/input';
import { themeCssVariables } from 'twenty-ui/theme-constants';
@@ -15,12 +15,13 @@ const StyledCard = styled.div`
width: 100%;
`;
-const StyledHeader = styled.button<{ hasBody: boolean; hasNote: boolean }>`
+const StyledHeader = styled.label<{ hasBody: boolean; hasNote: boolean }>`
align-items: center;
background-color: transparent;
border: none;
border-bottom: ${({ hasBody }) =>
hasBody ? `1px solid ${themeCssVariables.border.color.light}` : 'none'};
+ box-sizing: border-box;
cursor: pointer;
display: flex;
gap: ${themeCssVariables.spacing[1]};
@@ -122,8 +123,7 @@ type OnboardingPlanCardProps = {
titleSuffix?: string;
note?: string;
badge?: string;
- selected: boolean;
- onSelect: () => void;
+ value: boolean;
children?: ReactNode;
};
@@ -132,40 +132,40 @@ export const OnboardingPlanCard = ({
titleSuffix,
note,
badge,
- selected,
- onSelect,
+ value,
children,
}: OnboardingPlanCardProps) => {
+ const titleId = useId();
+ const noteId = useId();
const hasBody = isValidElement(children);
const hasNote = isDefined(note);
return (
<StyledCard>
- <StyledHeader
- type="button"
- hasBody={hasBody}
- hasNote={hasNote}
- onClick={onSelect}
- >
+ <StyledHeader hasBody={hasBody} hasNote={hasNote}>
<StyledHeaderLeft hasNote={hasNote}>
<StyledTitleRow>
- <StyledTitle>{title}</StyledTitle>
+ <StyledTitle id={titleId}>{title}</StyledTitle>
{isDefined(titleSuffix) && (
<StyledTitleSuffix isEmphasized={hasNote}>
{titleSuffix}
</StyledTitleSuffix>
)}
</StyledTitleRow>
- {hasNote && <StyledNote>{note}</StyledNote>}
+ {hasNote && <StyledNote id={noteId}>{note}</StyledNote>}
</StyledHeaderLeft>
{hasNote ? (
<StyledRadioContainer>
- <Radio checked={selected} />
+ <Radio
+ value={value}
+ aria-labelledby={titleId}
+ aria-describedby={noteId}
+ />
</StyledRadioContainer>
) : (
<StyledHeaderRight>
{isDefined(badge) && <StyledBadge>{badge}</StyledBadge>}
- <Radio checked={selected} />
+ <Radio value={value} aria-labelledby={titleId} />
</StyledHeaderRight>
)}
</StyledHeader>
diff --git a/packages/twenty-front/src/modules/onboarding/components/upgrade-free-trial/__stories__/OnboardingPlanCard.stories.tsx b/packages/twenty-front/src/modules/onboarding/components/upgrade-free-trial/__stories__/OnboardingPlanCard.stories.tsx
new file mode 100644
index 00000000000..20da99d756c
--- /dev/null
+++ b/packages/twenty-front/src/modules/onboarding/components/upgrade-free-trial/__stories__/OnboardingPlanCard.stories.tsx
@@ -0,0 +1,64 @@
+import { OnboardingPlanCard } from '@/onboarding/components/upgrade-free-trial/OnboardingPlanCard';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useState } from 'react';
+import { expect, fn, userEvent, within } from 'storybook/test';
+import { RadioGroup } from 'twenty-ui/input';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+const PlanChoices = ({
+ onValueChange,
+}: {
+ onValueChange: (value: boolean) => void;
+}) => {
+ const [value, setValue] = useState(false);
+
+ return (
+ <RadioGroup
+ aria-label="Trial plan"
+ value={value}
+ onValueChange={(nextValue) => {
+ setValue(nextValue);
+ onValueChange(nextValue);
+ }}
+ >
+ <OnboardingPlanCard
+ title="Upgraded"
+ note="Free trial with a payment method"
+ value={true}
+ >
+ {value && <input aria-label="Payment details" />}
+ </OnboardingPlanCard>
+ <OnboardingPlanCard title="Basic" badge="7 days" value={false} />
+ </RadioGroup>
+ );
+};
+
+const meta: Meta<typeof PlanChoices> = {
+ title: 'Modules/Onboarding/PlanChoices',
+ component: PlanChoices,
+ args: { onValueChange: fn() },
+ decorators: [ComponentDecorator],
+};
+
+export default meta;
+type Story = StoryObj<typeof PlanChoices>;
+
+export const SelectionAndPaymentDetails: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getByRole('radio', { name: 'Basic' })).toBeChecked();
+ await userEvent.click(canvas.getByText('Free trial with a payment method'));
+ await expect(canvas.getByRole('radio', { name: 'Upgraded' })).toBeChecked();
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ await expect(args.onValueChange).toHaveBeenCalledWith(true);
+ await userEvent.type(
+ canvas.getByRole('textbox', { name: 'Payment details' }),
+ 'Card',
+ );
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ await userEvent.click(canvas.getByRole('radio', { name: 'Upgraded' }));
+ await userEvent.keyboard('{ArrowDown}');
+ await expect(canvas.getByRole('radio', { name: 'Basic' })).toBeChecked();
+ await expect(args.onValueChange).toHaveBeenLastCalledWith(false);
+ },
+};
diff --git a/packages/twenty-front/src/modules/settings/components/SettingsRadioCard.tsx b/packages/twenty-front/src/modules/settings/components/SettingsRadioCard.tsx
index b39d151496d..ce70ae39041 100644
--- a/packages/twenty-front/src/modules/settings/components/SettingsRadioCard.tsx
+++ b/packages/twenty-front/src/modules/settings/components/SettingsRadioCard.tsx
@@ -1,11 +1,12 @@
import { styled } from '@linaria/react';
-import { useContext } from 'react';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useContext, useId } from 'react';
import { CardContent } from 'twenty-ui/surfaces';
import { type IconComponent } from 'twenty-ui/icon';
import { Radio } from 'twenty-ui/input';
import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';
-const StyledRadioCardContentContainer = styled.div`
+const StyledRadioCardContentContainer = styled.label`
> div {
align-items: center;
border: 1px solid ${themeCssVariables.border.color.medium};
@@ -42,36 +43,40 @@ const StyledDescription = styled.div`
type SettingsRadioCardProps = {
value: string;
- handleSelect: (value: string) => void;
- isSelected: boolean;
title: string;
description?: string;
Icon?: IconComponent;
- role?: string;
- ariaChecked?: boolean;
};
export const SettingsRadioCard = ({
value,
- handleSelect,
title,
description,
- isSelected,
Icon,
}: SettingsRadioCardProps) => {
+ const titleId = useId();
+ const descriptionId = useId();
const { theme } = useContext(ThemeContext);
- const onClick = () => handleSelect(value);
+ const hasDescription = isNonEmptyString(description);
return (
<StyledRadioCardContentContainer>
- <CardContent tabIndex={0} onClick={onClick}>
+ <CardContent>
{Icon && <Icon size={theme.icon.size.xl} color={theme.color.gray10} />}
<span>
- {title && <StyledTitle>{title}</StyledTitle>}
- {description && <StyledDescription>{description}</StyledDescription>}
+ {title && <StyledTitle id={titleId}>{title}</StyledTitle>}
+ {hasDescription && (
+ <StyledDescription id={descriptionId}>
+ {description}
+ </StyledDescription>
+ )}
</span>
<StyledRadioContainer>
- <Radio value={value} checked={isSelected} />
+ <Radio
+ value={value}
+ aria-labelledby={titleId}
+ aria-describedby={hasDescription ? descriptionId : undefined}
+ />
</StyledRadioContainer>
</CardContent>
</StyledRadioCardContentContainer>
diff --git a/packages/twenty-front/src/modules/settings/components/SettingsRadioCardContainer.tsx b/packages/twenty-front/src/modules/settings/components/SettingsRadioCardContainer.tsx
index 9aad0c000aa..5e8ae643974 100644
--- a/packages/twenty-front/src/modules/settings/components/SettingsRadioCardContainer.tsx
+++ b/packages/twenty-front/src/modules/settings/components/SettingsRadioCardContainer.tsx
@@ -1,10 +1,12 @@
import { styled } from '@linaria/react';
+import { RadioGroup } from 'twenty-ui/input';
import { SettingsRadioCard } from '@/settings/components/SettingsRadioCard';
import { type IconComponent } from 'twenty-ui/icon';
import { themeCssVariables } from 'twenty-ui/theme-constants';
const StyledRadioCardContainer = styled.div`
display: flex;
+ flex-direction: row;
flex-wrap: wrap;
gap: ${themeCssVariables.spacing[4]};
`;
@@ -26,20 +28,20 @@ export const SettingsRadioCardContainer = ({
onChange,
}: SettingsRadioCardContainerProps) => {
return (
- <StyledRadioCardContainer role="radiogroup">
+ <RadioGroup
+ value={value}
+ onValueChange={onChange}
+ render={<StyledRadioCardContainer />}
+ >
{options.map((option) => (
<SettingsRadioCard
key={option.value}
- role="radio"
value={option.value}
- isSelected={value === option.value}
- handleSelect={onChange}
title={option.title}
description={option.description}
Icon={option.Icon}
- ariaChecked={value === option.value}
/>
))}
- </StyledRadioCardContainer>
+ </RadioGroup>
);
};
diff --git a/packages/twenty-front/src/modules/settings/components/SettingsRadioSettingsCard.tsx b/packages/twenty-front/src/modules/settings/components/SettingsRadioSettingsCard.tsx
index 5cd3c939297..96a0c7131e0 100644
--- a/packages/twenty-front/src/modules/settings/components/SettingsRadioSettingsCard.tsx
+++ b/packages/twenty-front/src/modules/settings/components/SettingsRadioSettingsCard.tsx
@@ -1,9 +1,9 @@
import { styled } from '@linaria/react';
import { type MessageDescriptor } from '@lingui/core';
import { useLingui } from '@lingui/react/macro';
-import { type KeyboardEvent, type ReactNode } from 'react';
+import { type ReactNode, useId } from 'react';
import { isDefined } from 'twenty-shared/utils';
-import { Radio } from 'twenty-ui/input';
+import { Radio, RadioGroup } from 'twenty-ui/input';
import { Card, CardContent } from 'twenty-ui/surfaces';
import { themeCssVariables } from 'twenty-ui/theme-constants';
@@ -24,7 +24,7 @@ const StyledCardContentContainer = styled.div`
}
`;
-const StyledOptionHeader = styled.div`
+const StyledOptionHeader = styled.label`
align-items: center;
display: flex;
gap: ${themeCssVariables.spacing[4]};
@@ -70,63 +70,58 @@ export const SettingsRadioSettingsCard = <
options,
value,
}: SettingsRadioSettingsCardProps<Option>) => {
+ const groupId = useId();
const { i18n } = useLingui();
- const handleKeyDown = (
- event: KeyboardEvent<HTMLDivElement>,
- optionValue: Option['value'],
- ) => {
- if (event.key !== 'Enter' && event.key !== ' ') {
- return;
- }
-
- event.preventDefault();
- onChange(optionValue);
- };
-
return (
- <Card fullWidth rounded role="radiogroup">
- {options.map((option, index) => {
- const isSelected = value === option.value;
+ <RadioGroup
+ name={name}
+ value={value}
+ onValueChange={onChange}
+ onKeyDown={(event) => {
+ if (
+ !(event.target instanceof HTMLElement) ||
+ event.target.getAttribute('role') !== 'radio'
+ ) {
+ event.preventBaseUIHandler();
+ }
+ }}
+ >
+ <Card fullWidth rounded>
+ {options.map((option, index) => {
+ const isSelected = value === option.value;
- return (
- <StyledCardContentContainer key={option.value}>
- <CardContent
- aria-checked={isSelected}
- divider={index < options.length - 1}
- onClick={() => onChange(option.value)}
- onKeyDown={(event) => handleKeyDown(event, option.value)}
- role="radio"
- tabIndex={0}
- >
- <StyledOptionHeader>
- {option.cardMedia}
- <StyledTextContainer>
- <StyledTitle>{i18n._(option.title)}</StyledTitle>
- <StyledDescription>
- {i18n._(option.description)}
- </StyledDescription>
- </StyledTextContainer>
- <StyledRadioContainer
- onClick={(event) => event.stopPropagation()}
- >
- <Radio
- checked={isSelected}
- name={name}
- onCheckedChange={() => onChange(option.value)}
- value={option.value}
- />
- </StyledRadioContainer>
- </StyledOptionHeader>
- {isDefined(option.cardContentExpanded) && isSelected && (
- <StyledExpandedContent>
- {option.cardContentExpanded}
- </StyledExpandedContent>
- )}
- </CardContent>
- </StyledCardContentContainer>
- );
- })}
- </Card>
+ return (
+ <StyledCardContentContainer key={option.value}>
+ <CardContent divider={index < options.length - 1}>
+ <StyledOptionHeader>
+ {option.cardMedia}
+ <StyledTextContainer>
+ <StyledTitle id={`${groupId}-${index}-title`}>
+ {i18n._(option.title)}
+ </StyledTitle>
+ <StyledDescription id={`${groupId}-${index}-description`}>
+ {i18n._(option.description)}
+ </StyledDescription>
+ </StyledTextContainer>
+ <StyledRadioContainer>
+ <Radio
+ aria-labelledby={`${groupId}-${index}-title`}
+ aria-describedby={`${groupId}-${index}-description`}
+ value={option.value}
+ />
+ </StyledRadioContainer>
+ </StyledOptionHeader>
+ {isDefined(option.cardContentExpanded) && isSelected && (
+ <StyledExpandedContent>
+ {option.cardContentExpanded}
+ </StyledExpandedContent>
+ )}
+ </CardContent>
+ </StyledCardContentContainer>
+ );
+ })}
+ </Card>
+ </RadioGroup>
);
};
diff --git a/packages/twenty-front/src/modules/settings/components/__stories__/SettingsRadioCards.stories.tsx b/packages/twenty-front/src/modules/settings/components/__stories__/SettingsRadioCards.stories.tsx
new file mode 100644
index 00000000000..da2be83dede
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/components/__stories__/SettingsRadioCards.stories.tsx
@@ -0,0 +1,139 @@
+import { SettingsRadioCardContainer } from '@/settings/components/SettingsRadioCardContainer';
+import { SettingsRadioSettingsCard } from '@/settings/components/SettingsRadioSettingsCard';
+import { msg } from '@lingui/core/macro';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useState } from 'react';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+const SettingsRadioCardsExample = ({
+ onChange,
+}: {
+ onChange: (value: string) => void;
+}) => {
+ const [value, setValue] = useState('saml');
+
+ return (
+ <SettingsRadioCardContainer
+ options={[
+ {
+ value: 'saml',
+ title: 'SAML',
+ description: 'Enterprise authentication',
+ },
+ { value: 'oidc', title: 'OIDC', description: 'OpenID Connect' },
+ ]}
+ value={value}
+ onChange={(nextValue) => {
+ setValue(nextValue);
+ onChange(nextValue);
+ }}
+ />
+ );
+};
+
+const meta: Meta<typeof SettingsRadioCardsExample> = {
+ title: 'Modules/Settings/RadioCards',
+ component: SettingsRadioCardsExample,
+ args: { onChange: fn() },
+ decorators: [ComponentDecorator],
+};
+
+export default meta;
+type Story = StoryObj<typeof SettingsRadioCardsExample>;
+
+export const AuthenticationChoices: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByText('OpenID Connect'));
+ await expect(canvas.getByRole('radio', { name: 'OIDC' })).toBeChecked();
+ await expect(args.onChange).toHaveBeenCalledTimes(1);
+ await userEvent.keyboard('{ArrowLeft}');
+ await waitFor(() =>
+ expect(canvas.getByRole('radio', { name: 'SAML' })).toBeChecked(),
+ );
+ await expect(args.onChange).toHaveBeenCalledTimes(2);
+ },
+};
+
+const ExpandedCardExample = ({
+ onChange,
+}: {
+ onChange: (value: string) => void;
+}) => {
+ const [value, setValue] = useState('all');
+
+ return (
+ <SettingsRadioSettingsCard
+ name="sync"
+ options={[
+ {
+ value: 'all',
+ title: msg`All messages`,
+ description: msg`Sync every message`,
+ cardMedia: null,
+ },
+ {
+ value: 'selected',
+ title: msg`Selected folders`,
+ description: msg`Choose folders to sync`,
+ cardMedia: null,
+ cardContentExpanded: <input aria-label="Folder name" />,
+ },
+ ]}
+ value={value}
+ onChange={(nextValue) => {
+ setValue(nextValue);
+ onChange(nextValue);
+ }}
+ />
+ );
+};
+
+export const ExpandedContent: Story = {
+ render: (args) => <ExpandedCardExample onChange={args.onChange} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByText('Choose folders to sync'));
+ await expect(
+ canvas.getByRole('radio', { name: 'Selected folders' }),
+ ).toBeChecked();
+ await expect(args.onChange).toHaveBeenCalledTimes(1);
+ const folderNameInput = canvas.getByRole('textbox', {
+ name: 'Folder name',
+ });
+ await userEvent.type(folderNameInput, 'Inbox');
+ await expect(args.onChange).toHaveBeenCalledTimes(1);
+ await expect(folderNameInput).toHaveValue('Inbox');
+
+ for (const key of [
+ '{ArrowRight}',
+ '{ArrowDown}',
+ '{Home}',
+ '{ArrowLeft}',
+ '{ArrowUp}',
+ '{End}',
+ ]) {
+ await userEvent.keyboard(key);
+ await expect(
+ canvas.getByRole('radio', { name: 'Selected folders' }),
+ ).toBeChecked();
+ await expect(args.onChange).toHaveBeenCalledTimes(1);
+ await expect(folderNameInput).toHaveFocus();
+ }
+
+ await userEvent.keyboard('{ArrowLeft}X');
+ await expect(folderNameInput).toHaveValue('InboXx');
+ await userEvent.click(
+ canvas.getByRole('radio', { name: 'Selected folders' }),
+ );
+ await userEvent.keyboard('{ArrowUp}');
+ await waitFor(() =>
+ expect(canvas.getByRole('radio', { name: 'All messages' })).toBeChecked(),
+ );
+ await expect(args.onChange).toHaveBeenCalledTimes(2);
+ await expect(
+ canvas.queryByRole('textbox', { name: 'Folder name' }),
+ ).not.toBeInTheDocument();
+ },
+};
diff --git a/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx b/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx
index f69070989cf..5fe94a2afa7 100644
--- a/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx
+++ b/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx
@@ -10,7 +10,7 @@ import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
import { useState } from 'react';
import { Loader } from 'twenty-ui/feedback';
-import { CardPicker, MainButton } from 'twenty-ui/input';
+import { CardPicker, MainButton, RadioGroup } from 'twenty-ui/input';
import { ModalContent } from 'twenty-ui/surfaces';
import { themeCssVariables } from 'twenty-ui/theme-constants';
@@ -163,26 +163,25 @@ export const EnterprisePlanModal = () => {
</StyledBenefitsContainer>
</StyledSubscriptionContainer>
- <StyledIntervalContainer>
- <CardPicker
- checked={selectedInterval === 'monthly'}
- handleChange={() => setSelectedInterval('monthly')}
- >
+ <RadioGroup
+ render={<StyledIntervalContainer />}
+ aria-label={t`Billing interval`}
+ value={selectedInterval}
+ onValueChange={setSelectedInterval}
+ >
+ <CardPicker value="monthly">
<StyledIntervalCardContent>
<StyledIntervalTitle>{t`Monthly`}</StyledIntervalTitle>
<StyledIntervalSubtitle>{`$${MONTHLY_PRICE} / ${t`seat / month`}`}</StyledIntervalSubtitle>
</StyledIntervalCardContent>
</CardPicker>
- <CardPicker
- checked={selectedInterval === 'yearly'}
- handleChange={() => setSelectedInterval('yearly')}
- >
+ <CardPicker value="yearly">
<StyledIntervalCardContent>
<StyledIntervalTitle>{t`Yearly`}</StyledIntervalTitle>
<StyledIntervalSubtitle>{`$${YEARLY_PRICE} / ${t`seat / month`}`}</StyledIntervalSubtitle>
</StyledIntervalCardContent>
</CardPicker>
- </StyledIntervalContainer>
+ </RadioGroup>
<MainButton
title={t`Continue`}
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/components/SpreadsheetImportSingleSelectTable.tsx b/packages/twenty-front/src/modules/spreadsheet-import/components/SpreadsheetImportSingleSelectTable.tsx
new file mode 100644
index 00000000000..9cde50e414e
--- /dev/null
+++ b/packages/twenty-front/src/modules/spreadsheet-import/components/SpreadsheetImportSingleSelectTable.tsx
@@ -0,0 +1,82 @@
+import { SpreadsheetImportTable } from '@/spreadsheet-import/components/SpreadsheetImportTable';
+import { getSpreadsheetImportSingleSelectColumn } from '@/spreadsheet-import/components/internal/getSpreadsheetImportSingleSelectColumn';
+import { type SpreadsheetImportSingleSelectTableProps } from '@/spreadsheet-import/types/SpreadsheetImportSingleSelectTableProps';
+import { styled } from '@linaria/react';
+import { type Key, useMemo } from 'react';
+import { type DataGridProps } from 'react-data-grid';
+import { isDefined } from 'twenty-shared/utils';
+import { RadioGroup, type RadioGroupProps } from 'twenty-ui/input';
+
+const StyledRadioGroupContainer = styled.div`
+ flex: 1;
+ min-height: 0;
+`;
+
+// The grid owns keyboard navigation, including rows outside the viewport.
+const preventRadioGroupNavigation: RadioGroupProps['onKeyDown'] = (event) => {
+ event.preventBaseUIHandler();
+};
+
+export const SpreadsheetImportSingleSelectTable = <
+ TData,
+ TRowKey extends Key = Key,
+>({
+ className,
+ columns,
+ headerRowHeight,
+ rows,
+ rowKeyGetter,
+ selectedRowKey,
+ onSelectedRowChange,
+ selectionLabel,
+}: SpreadsheetImportSingleSelectTableProps<TData, TRowKey>) => {
+ const selectionColumns = useMemo(
+ () => [getSpreadsheetImportSingleSelectColumn(rowKeyGetter), ...columns],
+ [columns, rowKeyGetter],
+ );
+
+ const selectRow = (rowKey: TRowKey) => {
+ if (rowKey !== selectedRowKey) {
+ onSelectedRowChange(rowKey);
+ }
+ };
+
+ const handleCellClick: DataGridProps<TData>['onCellClick'] = (
+ { row },
+ event,
+ ) => {
+ if (!event.defaultPrevented) {
+ selectRow(rowKeyGetter(row));
+ }
+ };
+
+ const handleSelectedCellChange: DataGridProps<TData>['onSelectedCellChange'] =
+ ({ row }) => {
+ if (isDefined(row)) {
+ selectRow(rowKeyGetter(row));
+ }
+ };
+
+ if (!rows.length) return null;
+
+ return (
+ <RadioGroup
+ render={<StyledRadioGroupContainer />}
+ aria-label={selectionLabel}
+ value={selectedRowKey}
+ onValueChange={selectRow}
+ onKeyDownCapture={preventRadioGroupNavigation}
+ onKeyDown={preventRadioGroupNavigation}
+ >
+ <SpreadsheetImportTable
+ className={className}
+ headerRowHeight={headerRowHeight}
+ rows={rows}
+ columns={selectionColumns}
+ rowKeyGetter={rowKeyGetter}
+ onCellClick={handleCellClick}
+ onSelectedCellChange={handleSelectedCellChange}
+ />
+ </RadioGroup>
+ );
+};
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/components/SpreadsheetImportTable.tsx b/packages/twenty-front/src/modules/spreadsheet-import/components/SpreadsheetImportTable.tsx
index 920a3c4d9b9..98c22b4023d 100644
--- a/packages/twenty-front/src/modules/spreadsheet-import/components/SpreadsheetImportTable.tsx
+++ b/packages/twenty-front/src/modules/spreadsheet-import/components/SpreadsheetImportTable.tsx
@@ -1,6 +1,7 @@
import { styled } from '@linaria/react';
-import { useContext } from 'react';
-import { DataGrid, type DataGridProps } from 'react-data-grid';
+import { type Key, useContext } from 'react';
+import { type SpreadsheetImportTableProps } from '@/spreadsheet-import/types/SpreadsheetImportTableProps';
+import { DataGrid } from 'react-data-grid';
import 'react-data-grid/lib/styles.css';
import { useSpreadsheetImportInternal } from '@/spreadsheet-import/hooks/useSpreadsheetImportInternal';
import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';
@@ -105,59 +106,41 @@ const StyledDataGridContainer = styled.div<{ headerRowHeight?: number }>`
}
`;
-type SpreadsheetImportTableProps<Data> = Pick<
- DataGridProps<Data>,
- | 'selectedRows'
- | 'onSelectedRowsChange'
- | 'columns'
- | 'headerRowHeight'
- | 'rowKeyGetter'
- | 'rows'
-> &
- Partial<
- Pick<DataGridProps<Data>, 'onCellClick' | 'renderers' | 'onRowsChange'>
- > & {
- className?: string;
- rowHeight?: number;
- hiddenHeader?: boolean;
- };
-
-export const SpreadsheetImportTable = <Data,>({
+export const SpreadsheetImportTable = <TData, TRowKey extends Key = Key>({
className,
columns,
- renderers,
headerRowHeight,
- rowKeyGetter,
rows,
+ rowKeyGetter,
+ renderers,
onRowsChange,
onCellClick,
- onSelectedRowsChange,
+ onSelectedCellChange,
selectedRows,
-}: SpreadsheetImportTableProps<Data>) => {
+ onSelectedRowsChange,
+}: SpreadsheetImportTableProps<TData, TRowKey>) => {
const { colorScheme } = useContext(ThemeContext);
-
const { rtl } = useSpreadsheetImportInternal();
const themeClassName = colorScheme === 'dark' ? 'rdg-dark' : 'rdg-light';
- if (!rows?.length || !columns?.length) return null;
+ if (!rows.length || !columns.length) return null;
return (
<StyledDataGridContainer headerRowHeight={headerRowHeight ?? undefined}>
<DataGrid
direction={rtl ? 'rtl' : 'ltr'}
rowHeight={40}
- {...{
- className: `${className || ''} ${themeClassName}`,
- columns,
- headerRowHeight,
- rowKeyGetter,
- onRowsChange,
- rows,
- renderers,
- onCellClick,
- onSelectedRowsChange,
- selectedRows,
- }}
+ className={`${className || ''} ${themeClassName}`}
+ headerRowHeight={headerRowHeight}
+ columns={columns}
+ rows={rows}
+ rowKeyGetter={rowKeyGetter}
+ renderers={renderers}
+ onRowsChange={onRowsChange}
+ onCellClick={onCellClick}
+ onSelectedCellChange={onSelectedCellChange}
+ selectedRows={selectedRows}
+ onSelectedRowsChange={onSelectedRowsChange}
/>
</StyledDataGridContainer>
);
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/components/__stories__/SpreadsheetImportTable.stories.tsx b/packages/twenty-front/src/modules/spreadsheet-import/components/__stories__/SpreadsheetImportTable.stories.tsx
new file mode 100644
index 00000000000..e91f55ff7ac
--- /dev/null
+++ b/packages/twenty-front/src/modules/spreadsheet-import/components/__stories__/SpreadsheetImportTable.stories.tsx
@@ -0,0 +1,193 @@
+import { RsiContext } from '@/spreadsheet-import/components/ReactSpreadsheetImportContextProvider';
+import { SpreadsheetImportSingleSelectTable } from '@/spreadsheet-import/components/SpreadsheetImportSingleSelectTable';
+import { SpreadsheetImportTable } from '@/spreadsheet-import/components/SpreadsheetImportTable';
+import { styled } from '@linaria/react';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useState } from 'react';
+import { SelectColumn } from 'react-data-grid';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+const StyledContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ height: 240px;
+ width: 480px;
+`;
+
+const ROWS = Array.from({ length: 60 }, (_, index) => ({
+ id: `row-${index}`,
+ name: `Contact ${index + 1}`,
+}));
+const COLUMNS = [{ key: 'name', name: 'Name' }];
+const MULTIPLE_SELECTION_COLUMNS = [SelectColumn, ...COLUMNS];
+const rowKeyGetter = (row: (typeof ROWS)[number]) => row.id;
+
+const SingleSelectionExample = ({
+ onSelectedRowChange,
+}: {
+ onSelectedRowChange: (rowKey: string) => void;
+}) => {
+ const [selectedRowKey, setSelectedRowKey] = useState('row-0');
+ const [rows, setRows] = useState(ROWS);
+
+ return (
+ <>
+ <button onClick={() => setRows([...rows].reverse())}>Reverse rows</button>
+ <SpreadsheetImportSingleSelectTable
+ columns={COLUMNS}
+ rows={rows}
+ rowKeyGetter={rowKeyGetter}
+ selectionLabel="Select a contact"
+ selectedRowKey={selectedRowKey}
+ onSelectedRowChange={(rowKey) => {
+ setSelectedRowKey(rowKey);
+ onSelectedRowChange(rowKey);
+ }}
+ />
+ </>
+ );
+};
+
+const MultipleSelectionExample = () => {
+ const [selectedRows, setSelectedRows] = useState<ReadonlySet<string>>(
+ new Set(),
+ );
+
+ return (
+ <SpreadsheetImportTable
+ columns={MULTIPLE_SELECTION_COLUMNS}
+ rows={ROWS}
+ rowKeyGetter={rowKeyGetter}
+ selectedRows={selectedRows}
+ onSelectedRowsChange={setSelectedRows}
+ />
+ );
+};
+
+const meta: Meta<typeof SingleSelectionExample> = {
+ title: 'Modules/SpreadsheetImport/SpreadsheetImportTable',
+ component: SingleSelectionExample,
+ decorators: [
+ (Story) => (
+ <RsiContext.Provider value={{ rtl: false }}>
+ <StyledContainer>
+ <Story />
+ </StyledContainer>
+ </RsiContext.Provider>
+ ),
+ ComponentDecorator,
+ ],
+ args: { onSelectedRowChange: fn() },
+};
+
+export default meta;
+type Story = StoryObj<typeof SingleSelectionExample>;
+
+export const SingleSelection: Story = {
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ const grid = canvas.getByRole('grid');
+ await expect(grid).not.toHaveAttribute('aria-multiselectable', 'true');
+ await expect(
+ canvas.getByRole('radiogroup', { name: 'Select a contact' }),
+ ).toBeVisible();
+
+ await userEvent.click(canvas.getByRole('gridcell', { name: 'Contact 2' }));
+ await expect(args.onSelectedRowChange).toHaveBeenCalledTimes(1);
+ await expect(args.onSelectedRowChange).toHaveBeenLastCalledWith('row-1');
+
+ const radios = canvas.getAllByRole('radio', { name: 'Select' });
+ await expect(radios[1]).toBeChecked();
+ await expect(radios[0]).not.toBeChecked();
+ await userEvent.click(radios[2]);
+ await expect(args.onSelectedRowChange).toHaveBeenCalledTimes(2);
+ await expect(args.onSelectedRowChange).toHaveBeenLastCalledWith('row-2');
+
+ await userEvent.keyboard('{ArrowRight}{ArrowDown}');
+ await expect(
+ canvas.getByRole('gridcell', { name: 'Contact 4' }),
+ ).toHaveFocus();
+ await expect(radios[3]).toBeChecked();
+ await expect(radios[2]).not.toBeChecked();
+ await expect(args.onSelectedRowChange).toHaveBeenCalledTimes(3);
+ await expect(args.onSelectedRowChange).toHaveBeenLastCalledWith('row-3');
+ },
+};
+
+export const VirtualizedSelection: Story = {
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole('gridcell', { name: 'Contact 1' }));
+ await userEvent.keyboard('{Control>}{End}{/Control}');
+ const lastCell = await canvas.findByRole('gridcell', {
+ name: 'Contact 60',
+ });
+ await waitFor(() => expect(lastCell).toHaveFocus());
+ await expect(
+ within(canvas.getByRole('row', { name: /Contact 60/ })).getByRole(
+ 'radio',
+ ),
+ ).toBeChecked();
+ await expect(args.onSelectedRowChange).toHaveBeenLastCalledWith('row-59');
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Reverse rows' }));
+ await userEvent.tab();
+ await userEvent.keyboard('{Control>}{Home}{/Control}{ArrowDown}');
+ await canvas.findByRole('gridcell', { name: 'Contact 60' });
+ await expect(
+ within(canvas.getByRole('row', { name: /Contact 60/ })).getByRole(
+ 'radio',
+ ),
+ ).toBeChecked();
+ await expect(args.onSelectedRowChange).toHaveBeenCalledTimes(1);
+ },
+};
+
+export const VirtualizedArrowNavigation: Story = {
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.queryByRole('gridcell', { name: 'Contact 60' }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(canvas.getAllByRole('radio', { name: 'Select' })[0]);
+ await userEvent.keyboard('{ArrowDown>59/}');
+ await expect(
+ within(canvas.getByRole('row', { name: /Contact 60/ })).getByRole(
+ 'radio',
+ ),
+ ).toBeChecked();
+ await expect(args.onSelectedRowChange).toHaveBeenCalledTimes(59);
+ await expect(args.onSelectedRowChange).toHaveBeenLastCalledWith('row-59');
+
+ await userEvent.keyboard('{ArrowDown}');
+ await expect(args.onSelectedRowChange).toHaveBeenCalledTimes(59);
+ await userEvent.keyboard('{ArrowUp}');
+ await expect(
+ within(canvas.getByRole('row', { name: /Contact 59/ })).getByRole(
+ 'radio',
+ ),
+ ).toBeChecked();
+ await expect(args.onSelectedRowChange).toHaveBeenLastCalledWith('row-58');
+ },
+};
+
+export const MultipleSelection: Story = {
+ render: () => <MultipleSelectionExample />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.queryByRole('radiogroup')).not.toBeInTheDocument();
+ await expect(canvas.getByRole('grid')).toHaveAttribute(
+ 'aria-multiselectable',
+ 'true',
+ );
+ const checkboxes = canvas.getAllByRole('checkbox', { name: 'Select' });
+ await userEvent.click(checkboxes[0]);
+ await userEvent.click(checkboxes[1]);
+ await expect(checkboxes[0]).toBeChecked();
+ await expect(checkboxes[1]).toBeChecked();
+ await userEvent.click(checkboxes[0]);
+ await expect(checkboxes[0]).not.toBeChecked();
+ await expect(checkboxes[1]).toBeChecked();
+ },
+};
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/components/internal/getSpreadsheetImportSingleSelectColumn.tsx b/packages/twenty-front/src/modules/spreadsheet-import/components/internal/getSpreadsheetImportSingleSelectColumn.tsx
new file mode 100644
index 00000000000..c054561a6a4
--- /dev/null
+++ b/packages/twenty-front/src/modules/spreadsheet-import/components/internal/getSpreadsheetImportSingleSelectColumn.tsx
@@ -0,0 +1,28 @@
+import { t } from '@lingui/core/macro';
+import { type Key } from 'react';
+import { type Column } from 'react-data-grid';
+import { Radio } from 'twenty-ui/input';
+
+export const getSpreadsheetImportSingleSelectColumn = <
+ TData,
+ TRowKey extends Key,
+>(
+ rowKeyGetter: (row: TData) => TRowKey,
+): Column<TData> => ({
+ key: 'select-row',
+ name: '',
+ width: 35,
+ minWidth: 35,
+ maxWidth: 35,
+ resizable: false,
+ sortable: false,
+ frozen: true,
+ cellClass: 'rdg-radio',
+ renderCell: ({ row, tabIndex }) => (
+ <Radio
+ aria-label={t`Select`}
+ value={rowKeyGetter(row)}
+ tabIndex={tabIndex}
+ />
+ ),
+});
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/SelectHeaderStep.tsx b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/SelectHeaderStep.tsx
index 70f5d3be703..a97fd44010d 100644
--- a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/SelectHeaderStep.tsx
+++ b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/SelectHeaderStep.tsx
@@ -44,9 +44,7 @@ export const SelectHeaderStep = ({
onBack,
currentStepState,
}: SelectHeaderStepProps) => {
- const [selectedRowIndexes, setSelectedRowIndexes] = useState<
- ReadonlySet<number>
- >(new Set([0]));
+ const [selectedRowIndex, setSelectedRowIndex] = useState(0);
const [isLoading, setIsLoading] = useState(false);
@@ -89,7 +87,6 @@ export const SelectHeaderStep = ({
);
const handleOnContinue = useCallback(async () => {
- const [selectedRowIndex] = Array.from(new Set(selectedRowIndexes));
// We consider data above header to be redundant
const trimmedData = importedRows.slice(selectedRowIndex + 1);
@@ -98,7 +95,7 @@ export const SelectHeaderStep = ({
await handleContinue(importedRows[selectedRowIndex], trimmedData);
setIsLoading(false);
- }, [handleContinue, importedRows, selectedRowIndexes]);
+ }, [handleContinue, importedRows, selectedRowIndex]);
const { t } = useLingui();
@@ -111,8 +108,8 @@ export const SelectHeaderStep = ({
<StyledTableContainer>
<SelectHeaderTable
importedRows={importedRows}
- selectedRowIndexes={selectedRowIndexes}
- setSelectedRowIndexes={setSelectedRowIndexes}
+ selectedRowIndex={selectedRowIndex}
+ onSelectedRowChange={setSelectedRowIndex}
/>
</StyledTableContainer>
</ModalContent>
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/components/SelectColumn.tsx b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/components/SelectColumn.tsx
deleted file mode 100644
index b5f2ec34cbc..00000000000
--- a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/components/SelectColumn.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-// prettier-ignore
-import { useRowSelection, type Column, type RenderCellProps } from 'react-data-grid';
-
-import { t } from '@lingui/core/macro';
-import { type ImportedRow } from '@/spreadsheet-import/types';
-import { Radio } from 'twenty-ui/input';
-
-const SELECT_COLUMN_KEY = 'select-row';
-
-type SelectFormatterProps = RenderCellProps<unknown>;
-
-const SelectFormatter = (props: SelectFormatterProps) => {
- const { isRowSelected, onRowSelectionChange } = useRowSelection();
-
- return (
- <Radio
- aria-label={t`Select`}
- checked={isRowSelected}
- onChange={(event) => {
- onRowSelectionChange({
- row: props.row,
- checked: Boolean(event.target.checked),
- isShiftClick: (event.nativeEvent as MouseEvent).shiftKey,
- });
- }}
- />
- );
-};
-
-export const SelectColumn: Column<any, any> = {
- key: SELECT_COLUMN_KEY,
- name: '',
- width: 35,
- minWidth: 35,
- maxWidth: 35,
- resizable: false,
- sortable: false,
- frozen: true,
- cellClass: 'rdg-radio',
- renderCell: SelectFormatter,
-};
-
-export const generateSelectionColumns = (data: ImportedRow[]) => {
- const longestRowLength = data.reduce(
- (acc, curr) => (acc > curr.length ? acc : curr.length),
- 0,
- );
- return [
- SelectColumn,
- ...Array.from(Array(longestRowLength), (_, index) => ({
- key: index.toString(),
- name: '',
- })),
- ];
-};
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/components/SelectHeaderTable.tsx b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/components/SelectHeaderTable.tsx
index 2aafa3773d9..6c21c70f48d 100644
--- a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/components/SelectHeaderTable.tsx
+++ b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectHeaderStep/components/SelectHeaderTable.tsx
@@ -1,45 +1,45 @@
-import { useMemo } from 'react';
+import { useCallback, useMemo } from 'react';
+import { t } from '@lingui/core/macro';
-import { SpreadsheetImportTable } from '@/spreadsheet-import/components/SpreadsheetImportTable';
+import { SpreadsheetImportSingleSelectTable } from '@/spreadsheet-import/components/SpreadsheetImportSingleSelectTable';
import { type ImportedRow } from '@/spreadsheet-import/types';
-import { generateSelectionColumns } from './SelectColumn';
-
type SelectHeaderTableProps = {
importedRows: ImportedRow[];
- selectedRowIndexes: ReadonlySet<number>;
- setSelectedRowIndexes: (rowIndexes: ReadonlySet<number>) => void;
+ selectedRowIndex: number;
+ onSelectedRowChange: (rowIndex: number) => void;
};
export const SelectHeaderTable = ({
importedRows,
- selectedRowIndexes,
- setSelectedRowIndexes,
+ selectedRowIndex,
+ onSelectedRowChange,
}: SelectHeaderTableProps) => {
- const columns = useMemo(
- () => generateSelectionColumns(importedRows),
+ const rowKeyGetter = useCallback(
+ (row: ImportedRow) => importedRows.indexOf(row),
[importedRows],
);
+ const columns = useMemo(() => {
+ const longestRowLength = importedRows.reduce(
+ (length, row) => Math.max(length, row.length),
+ 0,
+ );
+
+ return Array.from({ length: longestRowLength }, (_, index) => ({
+ key: index.toString(),
+ name: '',
+ }));
+ }, [importedRows]);
+
return (
- <SpreadsheetImportTable
- // Todo: remove usage of react-data-grid
- rowKeyGetter={(row: any) => importedRows.indexOf(row)}
+ <SpreadsheetImportSingleSelectTable
+ rowKeyGetter={rowKeyGetter}
rows={importedRows}
columns={columns}
- selectedRows={selectedRowIndexes}
- onSelectedRowsChange={(newSelectedRows) => {
- for (const value of newSelectedRows) {
- const rowIndex = Number(value);
- if (!selectedRowIndexes.has(rowIndex)) {
- setSelectedRowIndexes(new Set([rowIndex]));
- return;
- }
- }
- }}
- onCellClick={(args) => {
- setSelectedRowIndexes(new Set([importedRows.indexOf(args.row)]));
- }}
+ selectionLabel={t`Select header row`}
+ selectedRowKey={selectedRowIndex}
+ onSelectedRowChange={onSelectedRowChange}
headerRowHeight={0}
/>
);
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectSheetStep/SelectSheetStep.tsx b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectSheetStep/SelectSheetStep.tsx
index 55f4f9408e9..d7b89501e88 100644
--- a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectSheetStep/SelectSheetStep.tsx
+++ b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/SelectSheetStep/SelectSheetStep.tsx
@@ -11,7 +11,7 @@ import { mapWorkbook } from '@/spreadsheet-import/utils/mapWorkbook';
import { ModalContent } from 'twenty-ui/surfaces';
import { useLingui } from '@lingui/react/macro';
-import { Radio } from 'twenty-ui/input';
+import { Radio, RadioGroup } from 'twenty-ui/input';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { type WorkBook } from 'xlsx-ugnis';
@@ -101,20 +101,18 @@ export const SelectSheetStep = ({
<>
<ModalContent isVerticallyCentered isHorizontallyCentered gap={8}>
<Heading title={t`Select the sheet to use`} />
- <StyledRadioContainer>
+ <RadioGroup
+ render={<StyledRadioContainer />}
+ aria-label={t`Select the sheet to use`}
+ value={value}
+ onValueChange={setValue}
+ >
{sheetNames.map((sheetName) => (
<StyledRadioItemContainer key={sheetName}>
- <Radio
- value={sheetName}
- label={sheetName}
- checked={value === sheetName}
- onCheckedChange={(checked) => {
- if (checked) setValue(sheetName);
- }}
- />
+ <Radio value={sheetName}>{sheetName}</Radio>
</StyledRadioItemContainer>
))}
- </StyledRadioContainer>
+ </RadioGroup>
</ModalContent>
<StepNavigationButton
onContinue={() => handleOnContinue(value)}
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/steps/components/__stories__/SelectHeaderTable.stories.tsx b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/__stories__/SelectHeaderTable.stories.tsx
new file mode 100644
index 00000000000..fabb5b3d398
--- /dev/null
+++ b/packages/twenty-front/src/modules/spreadsheet-import/steps/components/__stories__/SelectHeaderTable.stories.tsx
@@ -0,0 +1,59 @@
+import { RsiContext } from '@/spreadsheet-import/components/ReactSpreadsheetImportContextProvider';
+import { SelectHeaderTable } from '@/spreadsheet-import/steps/components/SelectHeaderStep/components/SelectHeaderTable';
+import { styled } from '@linaria/react';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useState } from 'react';
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+const StyledContainer = styled.div`
+ display: flex;
+ height: 240px;
+ width: 480px;
+`;
+
+const SelectHeaderTableExample = () => {
+ const [selectedRowIndex, setSelectedRowIndex] = useState(0);
+
+ return (
+ <RsiContext.Provider value={{ rtl: false }}>
+ <StyledContainer>
+ <SelectHeaderTable
+ importedRows={[
+ ['Report', 'September'],
+ ['Name', 'Email'],
+ ['Ada', '[email protected]'],
+ ]}
+ selectedRowIndex={selectedRowIndex}
+ onSelectedRowChange={setSelectedRowIndex}
+ />
+ </StyledContainer>
+ </RsiContext.Provider>
+ );
+};
+
+const meta: Meta<typeof SelectHeaderTableExample> = {
+ title: 'Modules/SpreadsheetImport/SelectHeaderTable',
+ component: SelectHeaderTableExample,
+ decorators: [ComponentDecorator],
+};
+
+export default meta;
+type Story = StoryObj<typeof SelectHeaderTableExample>;
+
+export const SingleRowSelection: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const radios = canvas.getAllByRole('radio', { name: 'Select' });
+ await expect(radios[0]).toBeChecked();
+ await userEvent.click(radios[1]);
+ await expect(radios[1]).toBeChecked();
+ await expect(radios[0]).not.toBeChecked();
+ await userEvent.keyboard('{ArrowDown}');
+ await waitFor(() => expect(radios[2]).toBeChecked());
+ await expect(radios[1]).not.toBeChecked();
+ await userEvent.click(canvas.getByRole('gridcell', { name: 'Report' }));
+ await expect(radios[0]).toBeChecked();
+ await expect(radios[2]).not.toBeChecked();
+ },
+};
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/types/SpreadsheetImportSingleSelectTableProps.ts b/packages/twenty-front/src/modules/spreadsheet-import/types/SpreadsheetImportSingleSelectTableProps.ts
new file mode 100644
index 00000000000..51a9708477a
--- /dev/null
+++ b/packages/twenty-front/src/modules/spreadsheet-import/types/SpreadsheetImportSingleSelectTableProps.ts
@@ -0,0 +1,15 @@
+import { type SpreadsheetImportTableProps } from '@/spreadsheet-import/types/SpreadsheetImportTableProps';
+import { type Key } from 'react';
+
+export type SpreadsheetImportSingleSelectTableProps<
+ TData,
+ TRowKey extends Key = Key,
+> = Pick<
+ SpreadsheetImportTableProps<TData, TRowKey>,
+ 'className' | 'columns' | 'headerRowHeight' | 'rows'
+> & {
+ selectionLabel: string;
+ rowKeyGetter: (row: TData) => TRowKey;
+ selectedRowKey: TRowKey;
+ onSelectedRowChange: (rowKey: TRowKey) => void;
+};
diff --git a/packages/twenty-front/src/modules/spreadsheet-import/types/SpreadsheetImportTableProps.ts b/packages/twenty-front/src/modules/spreadsheet-import/types/SpreadsheetImportTableProps.ts
new file mode 100644
index 00000000000..3684495c2ce
--- /dev/null
+++ b/packages/twenty-front/src/modules/spreadsheet-import/types/SpreadsheetImportTableProps.ts
@@ -0,0 +1,20 @@
+import { type Key } from 'react';
+import { type DataGridProps } from 'react-data-grid';
+
+export type SpreadsheetImportTableProps<
+ TData,
+ TRowKey extends Key = Key,
+> = Pick<
+ DataGridProps<TData, unknown, TRowKey>,
+ | 'className'
+ | 'columns'
+ | 'headerRowHeight'
+ | 'rows'
+ | 'rowKeyGetter'
+ | 'onCellClick'
+ | 'onSelectedCellChange'
+ | 'renderers'
+ | 'onRowsChange'
+ | 'selectedRows'
+ | 'onSelectedRowsChange'
+>;
diff --git a/packages/twenty-front/src/pages/onboarding/UpgradeFreeTrial.tsx b/packages/twenty-front/src/pages/onboarding/UpgradeFreeTrial.tsx
index 7118917cbb6..6c53d3da716 100644
--- a/packages/twenty-front/src/pages/onboarding/UpgradeFreeTrial.tsx
+++ b/packages/twenty-front/src/pages/onboarding/UpgradeFreeTrial.tsx
@@ -28,7 +28,7 @@ import { Elements, PaymentElement } from '@stripe/react-stripe-js';
import { AppPath } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { Info, Loader } from 'twenty-ui/feedback';
-import { MainButton } from 'twenty-ui/input';
+import { MainButton, RadioGroup } from 'twenty-ui/input';
import { CAL_LINK, ClickToActionLink } from 'twenty-ui/navigation';
import { MOBILE_VIEWPORT, themeCssVariables } from 'twenty-ui/theme-constants';
import {
@@ -162,7 +162,7 @@ const UpgradeFreeTrialContent = ({
void handleCheckoutSession();
};
- const selectTrialPeriod = (withCreditCard: boolean) => () => {
+ const selectTrialPeriod = (withCreditCard: boolean) => {
if (
isDefined(baseProductPrice) &&
billingCheckoutSession.requirePaymentMethod !== withCreditCard
@@ -180,13 +180,17 @@ const UpgradeFreeTrialContent = ({
return (
<>
<OnboardingStepAnimatedItem index={3}>
- <StyledCards>
+ <RadioGroup
+ render={<StyledCards />}
+ aria-label={t`Trial plan`}
+ value={requirePaymentMethod}
+ onValueChange={selectTrialPeriod}
+ >
<OnboardingPlanCard
title={t`Upgraded`}
titleSuffix={t`· FREE`}
note={t`No charge will be made. You'll receive an email reminder 7 days before it ends.`}
- selected={requirePaymentMethod}
- onSelect={selectTrialPeriod(true)}
+ value={true}
>
{requirePaymentMethod &&
(isPaymentAvailable ? (
@@ -212,11 +216,10 @@ const UpgradeFreeTrialContent = ({
title={t`Basic`}
titleSuffix={t`without credit card`}
badge={t`${withoutCreditCardTrialPeriod.duration} days`}
- selected={!requirePaymentMethod}
- onSelect={selectTrialPeriod(false)}
+ value={false}
/>
)}
- </StyledCards>
+ </RadioGroup>
</OnboardingStepAnimatedItem>
<OnboardingStepAnimatedItem index={4}>
diff --git a/packages/twenty-ui/src/input/CardPicker/CardPicker.module.scss b/packages/twenty-ui/src/input/CardPicker/CardPicker.module.scss
index 1fa0d2ed92f..706e4030199 100644
--- a/packages/twenty-ui/src/input/CardPicker/CardPicker.module.scss
+++ b/packages/twenty-ui/src/input/CardPicker/CardPicker.module.scss
@@ -14,10 +14,10 @@
background: var(--t-background-tertiary);
}
-.radioContainer {
+.container > :first-child {
+ inset-block-start: var(--t-spacing-2);
+ inset-inline-end: var(--t-spacing-2);
position: absolute;
- right: var(--t-spacing-2);
- top: var(--t-spacing-2);
}
.cardInner {
diff --git a/packages/twenty-ui/src/input/CardPicker/CardPicker.module.scss.d.ts b/packages/twenty-ui/src/input/CardPicker/CardPicker.module.scss.d.ts
index 4ccb2001c0e..1523e9a77d6 100644
--- a/packages/twenty-ui/src/input/CardPicker/CardPicker.module.scss.d.ts
+++ b/packages/twenty-ui/src/input/CardPicker/CardPicker.module.scss.d.ts
@@ -1,6 +1,5 @@
declare const classNames: {
readonly container: 'container';
- readonly radioContainer: 'radioContainer';
readonly cardInner: 'cardInner';
};
export default classNames;
diff --git a/packages/twenty-ui/src/input/CardPicker/CardPicker.tsx b/packages/twenty-ui/src/input/CardPicker/CardPicker.tsx
index 49207e26956..c860934c849 100644
--- a/packages/twenty-ui/src/input/CardPicker/CardPicker.tsx
+++ b/packages/twenty-ui/src/input/CardPicker/CardPicker.tsx
@@ -1,25 +1,19 @@
-import React from 'react';
-
-import styles from './CardPicker.module.scss';
import { Radio } from '@ui/input/Radio/Radio';
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
-type CardPickerProps = {
- children: React.ReactNode;
- handleChange?: () => void;
- checked?: boolean;
-};
+import styles from './CardPicker.module.scss';
+import { type CardPickerProps } from './types/CardPickerProps';
-export const CardPicker = ({
+export const CardPicker = <TValue,>({
children,
- checked,
- handleChange,
-}: CardPickerProps) => {
- return (
- <button className={styles.container} onClick={handleChange}>
- <div className={styles.radioContainer}>
- <Radio checked={checked} />
- </div>
- <div className={styles.cardInner}>{children}</div>
- </button>
- );
-};
+ className,
+ ...props
+}: CardPickerProps<TValue>) => (
+ <Radio
+ render={<div />}
+ {...props}
+ className={mergeClassNames(styles.container, className)}
+ >
+ <div className={styles.cardInner}>{children}</div>
+ </Radio>
+);
diff --git a/packages/twenty-ui/src/input/CardPicker/types/CardPickerProps.ts b/packages/twenty-ui/src/input/CardPicker/types/CardPickerProps.ts
new file mode 100644
index 00000000000..4b8cb4e30d5
--- /dev/null
+++ b/packages/twenty-ui/src/input/CardPicker/types/CardPickerProps.ts
@@ -0,0 +1,3 @@
+import { type RadioProps } from '@ui/input/Radio/types/RadioProps';
+
+export type CardPickerProps<TValue = string> = RadioProps<TValue>;
diff --git a/packages/twenty-ui/src/input/Radio/Radio.module.scss b/packages/twenty-ui/src/input/Radio/Radio.module.scss
index 8cbde886e3c..996a166fa8e 100644
--- a/packages/twenty-ui/src/input/Radio/Radio.module.scss
+++ b/packages/twenty-ui/src/input/Radio/Radio.module.scss
@@ -1,91 +1,89 @@
-.container {
+.root {
align-items: center;
+ color: var(--t-font-color-primary);
+ cursor: pointer;
display: inline-flex;
- flex-direction: row;
-}
+ font-family: inherit;
+ font-size: var(--t-font-size-sm);
+ font-weight: var(--t-font-weight-regular);
+ gap: var(--t-spacing-2);
+ vertical-align: middle;
+ width: fit-content;
-.containerLabelLeft {
- flex-direction: row-reverse;
+ @include focus-ring;
}
-.radio {
+.control {
+ align-items: center;
background-color: transparent;
border: 1px solid var(--t-font-color-secondary);
border-radius: var(--t-border-radius-rounded);
- corner-shape: round;
- // The border sits outside the declared size, matching the legacy input rendering.
box-sizing: content-box;
- display: block;
- margin: 0 0 0 3px;
- position: relative;
- // Replaces the legacy framer-motion spring scale micro-animation.
+ corner-shape: round;
+ display: inline-flex;
+ flex-shrink: 0;
+ justify-content: center;
+ margin-inline-start: 3px;
transform: scale(0.95);
transition: transform duration(normal) ease;
}
-.small {
- height: 16px;
- width: 16px;
-}
-
-.large {
- height: 18px;
- width: 18px;
+.sm .control {
+ block-size: 16px;
+ inline-size: 16px;
}
-.radio:hover {
- background-color: var(--t-background-tertiary);
- outline: 4px solid var(--t-background-tertiary);
+.md .control {
+ block-size: 18px;
+ inline-size: 18px;
}
-.radio[data-checked] {
+.root[data-checked] .control {
background-color: var(--t-color-blue);
border: none;
transform: scale(1.05);
}
-.radio[data-checked]:hover {
- outline-color: var(--t-color-transparent-blue2);
-}
-
-.radio[data-checked]::after {
+.indicator {
background-color: var(--t-gray-scale-gray1);
+ block-size: 6px;
border-radius: 50%;
corner-shape: round;
- content: '';
- height: 6px;
- left: 50%;
- position: absolute;
- top: 50%;
- transform: translate(-50%, -50%);
- width: 6px;
+ inline-size: 6px;
}
-.large[data-checked]::after {
- height: 8px;
- width: 8px;
+.md .indicator {
+ block-size: 8px;
+ inline-size: 8px;
}
-.radio[data-disabled] {
- cursor: not-allowed;
- opacity: 0.12;
+@include hover-capable {
+ .root:not([data-disabled]):not([data-readonly]):hover .control {
+ background-color: var(--t-background-tertiary);
+ outline: 4px solid var(--t-background-tertiary);
+ }
+
+ .root[data-checked]:not([data-disabled]):not([data-readonly]):hover .control {
+ background-color: var(--t-color-blue);
+ outline-color: var(--t-color-transparent-blue2);
+ }
}
-.label {
- color: var(--t-font-color-primary);
- cursor: pointer;
- font-size: var(--t-font-size-sm);
- font-weight: var(--t-font-weight-regular);
+.root[data-disabled] {
+ cursor: not-allowed;
+ opacity: 0.32;
}
-.labelRight {
- margin-left: var(--t-spacing-2);
+.root[data-disabled] .control {
+ opacity: 0.375;
}
-.labelLeft {
- margin-right: var(--t-spacing-2);
+.root[data-readonly] {
+ cursor: default;
}
-.label[data-disabled] {
- opacity: 0.32;
+@media (prefers-reduced-motion: reduce) {
+ .control {
+ transition: none;
+ }
}
diff --git a/packages/twenty-ui/src/input/Radio/Radio.module.scss.d.ts b/packages/twenty-ui/src/input/Radio/Radio.module.scss.d.ts
index 52e585117d8..c2855ce5d47 100644
--- a/packages/twenty-ui/src/input/Radio/Radio.module.scss.d.ts
+++ b/packages/twenty-ui/src/input/Radio/Radio.module.scss.d.ts
@@ -1,11 +1,8 @@
declare const classNames: {
- readonly container: 'container';
- readonly containerLabelLeft: 'containerLabelLeft';
- readonly radio: 'radio';
- readonly small: 'small';
- readonly large: 'large';
- readonly label: 'label';
- readonly labelRight: 'labelRight';
- readonly labelLeft: 'labelLeft';
+ readonly root: 'root';
+ readonly control: 'control';
+ readonly sm: 'sm';
+ readonly md: 'md';
+ readonly indicator: 'indicator';
};
export default classNames;
diff --git a/packages/twenty-ui/src/input/Radio/Radio.tsx b/packages/twenty-ui/src/input/Radio/Radio.tsx
index ed652dc1458..0a2a907512d 100644
--- a/packages/twenty-ui/src/input/Radio/Radio.tsx
+++ b/packages/twenty-ui/src/input/Radio/Radio.tsx
@@ -1,93 +1,24 @@
import { Radio as RadioPrimitive } from '@base-ui/react/radio';
-import { RadioGroup as RadioGroupPrimitive } from '@base-ui/react/radio-group';
import { clsx } from 'clsx';
-import * as React from 'react';
-import styles from './Radio.module.scss';
-import { RadioGroup } from '@ui/input/RadioGroup/RadioGroup';
-
-export enum RadioSize {
- Large = 'large',
- Small = 'small',
-}
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
-export enum LabelPosition {
- Left = 'left',
- Right = 'right',
-}
-
-export type RadioProps = {
- checked?: boolean;
- className?: string;
- name?: string;
- disabled?: boolean;
- label?: string;
- labelPosition?: LabelPosition;
- onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
- onCheckedChange?: (checked: boolean) => void;
- size?: RadioSize;
- style?: React.CSSProperties;
- value?: string;
-};
+import styles from './Radio.module.scss';
+import { type RadioProps } from './types/RadioProps';
-export const Radio = ({
- checked,
+export const Radio = <TValue,>({
+ children,
className,
- name = 'input-radio',
- disabled = false,
- label,
- labelPosition = LabelPosition.Right,
- onChange,
- onCheckedChange,
- size = RadioSize.Small,
- value,
-}: RadioProps) => {
- const optionId = React.useId();
-
- // 'on' mimics the native input value default when neither value nor label is set.
- const radioValue = value || label || 'on';
-
- return (
- <RadioGroupPrimitive
- className={clsx(
- styles.container,
- labelPosition === LabelPosition.Left && styles.containerLabelLeft,
- className,
- )}
- name={name}
- value={checked === undefined ? undefined : checked ? radioValue : ''}
- onValueChange={(_newValue, eventDetails) => {
- const inputElement = eventDetails.event
- .target as HTMLInputElement | null;
- onChange?.(
- eventDetails.event as unknown as React.ChangeEvent<HTMLInputElement>,
- );
- onCheckedChange?.(inputElement?.checked ?? true);
- }}
- >
- <RadioPrimitive.Root
- id={optionId}
- value={radioValue}
- disabled={disabled}
- data-testid="input-radio"
- className={clsx(styles.radio, styles[size])}
- />
- {label && (
- <label
- htmlFor={optionId}
- className={clsx(
- styles.label,
- labelPosition === LabelPosition.Left
- ? styles.labelLeft
- : styles.labelRight,
- )}
- data-disabled={disabled || undefined}
- >
- {label}
- </label>
- )}
- </RadioGroupPrimitive>
- );
-};
-
-Radio.Group = RadioGroup;
+ size = 'sm',
+ ...props
+}: RadioProps<TValue>) => (
+ <RadioPrimitive.Root
+ {...props}
+ className={mergeClassNames(clsx(styles.root, styles[size]), className)}
+ >
+ <span className={styles.control} aria-hidden>
+ <RadioPrimitive.Indicator className={styles.indicator} />
+ </span>
+ {children}
+ </RadioPrimitive.Root>
+);
diff --git a/packages/twenty-ui/src/input/Radio/__stories__/Radio.interactions.stories.tsx b/packages/twenty-ui/src/input/Radio/__stories__/Radio.interactions.stories.tsx
new file mode 100644
index 00000000000..47555da8bfe
--- /dev/null
+++ b/packages/twenty-ui/src/input/Radio/__stories__/Radio.interactions.stories.tsx
@@ -0,0 +1,362 @@
+import { Field as FieldPrimitive } from '@base-ui/react/field';
+import { DirectionProvider } from '@base-ui/react/direction-provider';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useRef, useState } from 'react';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+
+import { CardPicker } from '@ui/input/CardPicker/CardPicker';
+import { Field } from '@ui/input/Field/Field';
+import { RadioGroup } from '@ui/input/RadioGroup/RadioGroup';
+import { type RadioGroupProps } from '@ui/input/RadioGroup/types/RadioGroupProps';
+import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';
+
+import { Radio } from '../Radio';
+
+const RadioExample = (props: RadioGroupProps) => (
+ <RadioGroup aria-label="Fruit" {...props}>
+ <Radio value="apple">Apple</Radio>
+ <div>
+ <Radio value="banana" disabled>
+ Banana
+ </Radio>
+ </div>
+ <div>
+ <Radio value="cherry">Cherry</Radio>
+ </div>
+ </RadioGroup>
+);
+
+const meta: Meta<typeof RadioExample> = {
+ title: 'UI/Input/Radio/Interactions',
+ component: RadioExample,
+ args: { onValueChange: fn() },
+};
+
+export default meta;
+type Story = StoryObj<typeof RadioExample>;
+
+export const Keyboard: Story = {
+ decorators: [ComponentDecorator],
+ args: { defaultValue: 'apple' },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const apple = canvas.getByRole('radio', { name: 'Apple' });
+ const cherry = canvas.getByRole('radio', { name: 'Cherry' });
+ await userEvent.tab();
+ await expect(apple).toHaveFocus();
+ await userEvent.keyboard('{ArrowDown}');
+ await waitFor(() => expect(cherry).toHaveFocus());
+ await expect(cherry).toBeChecked();
+ await expect(apple).not.toBeChecked();
+ await expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'cherry',
+ expect.anything(),
+ );
+ await userEvent.keyboard('{ArrowDown}');
+ await waitFor(() => expect(apple).toHaveFocus());
+ await expect(apple).toBeChecked();
+ await userEvent.keyboard('{ArrowUp}');
+ await waitFor(() => expect(cherry).toBeChecked());
+ },
+};
+
+export const UnselectedAndSpace: Story = {
+ decorators: [ComponentDecorator],
+ play: async ({ canvasElement, args }) => {
+ const apple = within(canvasElement).getByRole('radio', { name: 'Apple' });
+ await userEvent.tab();
+ await expect(apple).toHaveFocus();
+ await expect(apple).not.toBeChecked();
+ await userEvent.keyboard(' ');
+ await expect(apple).toBeChecked();
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ await userEvent.keyboard(' ');
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ },
+};
+
+export const LabelAndDisabledOption: Story = {
+ decorators: [ComponentDecorator],
+ args: { defaultValue: 'apple' },
+ render: (args) => (
+ <RadioGroup {...args} aria-label="Fruit">
+ <label htmlFor="radio-label-apple">
+ <Radio id="radio-label-apple" value="apple" />
+ Apple label
+ </label>
+ <label htmlFor="radio-label-banana">
+ <Radio id="radio-label-banana" value="banana" disabled />
+ Banana label
+ </label>
+ <label htmlFor="radio-label-cherry">
+ <Radio id="radio-label-cherry" value="cherry" />
+ Cherry label
+ </label>
+ </RadioGroup>
+ ),
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByText('Banana label'));
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+ await userEvent.click(canvas.getByText('Cherry label'));
+ await expect(
+ canvas.getByRole('radio', { name: 'Cherry label' }),
+ ).toBeChecked();
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ },
+};
+
+export const DisabledGroup: Story = {
+ decorators: [ComponentDecorator],
+ args: { defaultValue: 'apple', disabled: true },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const cherry = canvas.getByRole('radio', { name: 'Cherry' });
+ await expect(cherry).toHaveAttribute('aria-disabled', 'true');
+ await userEvent.click(cherry);
+ await userEvent.tab();
+ await expect(cherry).not.toHaveFocus();
+ await expect(canvas.getByRole('radio', { name: 'Apple' })).toBeChecked();
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+ },
+};
+
+export const ReadOnlyGroup: Story = {
+ decorators: [ComponentDecorator],
+ args: { defaultValue: 'apple', readOnly: true },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole('radio', { name: 'Cherry' }));
+ await userEvent.keyboard('{ArrowUp} ');
+ await expect(canvas.getByRole('radio', { name: 'Apple' })).toBeChecked();
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+ },
+};
+
+export const CanceledChange: Story = {
+ decorators: [ComponentDecorator],
+ args: {
+ defaultValue: 'apple',
+ onValueChange: fn((_value, details) => details.cancel()),
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole('radio', { name: 'Cherry' }));
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ await expect(canvas.getByRole('radio', { name: 'Apple' })).toBeChecked();
+ await expect(
+ canvas.getByRole('radio', { name: 'Cherry' }),
+ ).not.toBeChecked();
+ },
+};
+
+const ControlledExample = ({ onValueChange }: RadioGroupProps) => {
+ const [value, setValue] = useState('apple');
+
+ return (
+ <>
+ <RadioExample value={value} onValueChange={onValueChange} />
+ <button type="button" onClick={() => setValue('cherry')}>
+ Apply Cherry
+ </button>
+ </>
+ );
+};
+
+export const Controlled: Story = {
+ decorators: [ComponentDecorator],
+ render: (args) => <ControlledExample {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole('radio', { name: 'Cherry' }));
+ await expect(args.onValueChange).toHaveBeenCalledWith(
+ 'cherry',
+ expect.anything(),
+ );
+ await expect(canvas.getByRole('radio', { name: 'Apple' })).toBeChecked();
+ await userEvent.click(canvas.getByRole('button', { name: 'Apply Cherry' }));
+ await expect(canvas.getByRole('radio', { name: 'Cherry' })).toBeChecked();
+ },
+};
+
+const FormExample = () => {
+ const [value, setValue] = useState('apple');
+ const [submitted, setSubmitted] = useState('');
+
+ return (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ setSubmitted(
+ new FormData(event.currentTarget).getAll('fruit').join(', '),
+ );
+ }}
+ onReset={() => setValue('apple')}
+ >
+ <Field.Root name="fruit">
+ <Field.Label>Fruit</Field.Label>
+ <RadioGroup value={value} onValueChange={setValue} required>
+ <FieldPrimitive.Item>
+ <Radio value="apple">Apple</Radio>
+ </FieldPrimitive.Item>
+ <FieldPrimitive.Item>
+ <Radio value="cherry">Cherry</Radio>
+ </FieldPrimitive.Item>
+ </RadioGroup>
+ <Field.Description>Choose one fruit</Field.Description>
+ </Field.Root>
+ <button type="submit">Submit</button>
+ <button type="reset">Reset</button>
+ <output aria-label="Submitted fruit">{submitted}</output>
+ </form>
+ );
+};
+
+export const Form: Story = {
+ decorators: [ComponentDecorator],
+ parameters: { a11y: A11Y_DEFER_COLOR_CONTRAST },
+ render: () => <FormExample />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.getByRole('radiogroup', { name: 'Fruit' }),
+ ).toHaveAttribute('aria-required', 'true');
+ await userEvent.click(canvas.getByRole('radio', { name: 'Cherry' }));
+ await userEvent.click(canvas.getByRole('button', { name: 'Submit' }));
+ await expect(
+ canvas.getByRole('status', { name: 'Submitted fruit' }),
+ ).toHaveTextContent(/^cherry$/);
+ await userEvent.click(canvas.getByRole('button', { name: 'Reset' }));
+ await expect(canvas.getByRole('radio', { name: 'Apple' })).toBeChecked();
+ },
+};
+
+const InputRefExample = () => {
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ return (
+ <>
+ <RadioGroup defaultValue={0} aria-label="Number">
+ <Radio value={0}>Zero</Radio>
+ <Radio value={1} inputRef={inputRef}>
+ One
+ </Radio>
+ </RadioGroup>
+ <button type="button" onClick={() => inputRef.current?.focus()}>
+ Focus One
+ </button>
+ </>
+ );
+};
+
+export const NumericValuesAndInputRef: Story = {
+ decorators: [ComponentDecorator],
+ render: () => <InputRefExample />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getByRole('radio', { name: 'Zero' })).toBeChecked();
+ await userEvent.click(canvas.getByRole('button', { name: 'Focus One' }));
+ await expect(canvas.getByRole('radio', { name: 'One' })).toHaveFocus();
+ await userEvent.keyboard(' ');
+ await expect(canvas.getByRole('radio', { name: 'One' })).toBeChecked();
+ },
+};
+
+export const PolymorphismAndState: Story = {
+ decorators: [ComponentDecorator],
+ args: { defaultValue: 'apple' },
+ render: (args) => (
+ <RadioGroup {...args} aria-label="Fruit" render={<fieldset />}>
+ <Radio value="apple" nativeButton render={<button type="button" />}>
+ Apple
+ </Radio>
+ <Radio
+ value="cherry"
+ className={({ checked }) =>
+ checked ? 'selected-consumer' : 'consumer'
+ }
+ style={({ checked }) => ({ marginTop: checked ? 7 : 3 })}
+ render={(props, state) => (
+ <div {...props} data-checked-state={state.checked} />
+ )}
+ >
+ Cherry
+ </Radio>
+ </RadioGroup>
+ ),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getByRole('radiogroup').tagName).toBe('FIELDSET');
+ await expect(canvas.getByRole('radio', { name: 'Apple' }).tagName).toBe(
+ 'BUTTON',
+ );
+ const cherry = canvas.getByRole('radio', { name: 'Cherry' });
+ await expect(cherry).toHaveClass('consumer');
+ await userEvent.click(cherry);
+ await expect(cherry).toHaveClass('selected-consumer');
+ await expect(cherry).toHaveStyle({ marginTop: '7px' });
+ await expect(cherry).toHaveAttribute('data-checked-state', 'true');
+ },
+};
+
+export const RightToLeft: Story = {
+ decorators: [ComponentDecorator],
+ args: { defaultValue: 'apple' },
+ render: (args) => (
+ <DirectionProvider direction="rtl">
+ <div dir="rtl">
+ <RadioExample {...args} />
+ </div>
+ </DirectionProvider>
+ ),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.tab();
+ await userEvent.keyboard('{ArrowLeft}');
+ await waitFor(() =>
+ expect(canvas.getByRole('radio', { name: 'Cherry' })).toBeChecked(),
+ );
+ await userEvent.keyboard('{ArrowRight}');
+ await waitFor(() =>
+ expect(canvas.getByRole('radio', { name: 'Apple' })).toBeChecked(),
+ );
+ },
+};
+
+const CardsExample = ({ onValueChange }: RadioGroupProps) => {
+ const [value, setValue] = useState('monthly');
+
+ return (
+ <RadioGroup
+ aria-label="Billing interval"
+ value={value}
+ onValueChange={(nextValue, details) => {
+ setValue(nextValue);
+ onValueChange?.(nextValue, details);
+ }}
+ >
+ <CardPicker value="monthly">Monthly</CardPicker>
+ <CardPicker value="yearly">Yearly</CardPicker>
+ {value === 'yearly' && <input aria-label="Purchase order" />}
+ </RadioGroup>
+ );
+};
+
+export const Cards: Story = {
+ decorators: [ComponentDecorator],
+ render: (args) => <CardsExample {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByText('Yearly'));
+ await expect(canvas.getByRole('radio', { name: 'Yearly' })).toBeChecked();
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ await userEvent.type(
+ canvas.getByRole('textbox', { name: 'Purchase order' }),
+ 'PO-42',
+ );
+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ await userEvent.click(canvas.getByRole('radio', { name: 'Monthly' }));
+ await userEvent.keyboard('{ArrowDown}');
+ await expect(canvas.getByRole('radio', { name: 'Yearly' })).toBeChecked();
+ },
+};
diff --git a/packages/twenty-ui/src/input/Radio/__stories__/Radio.stories.tsx b/packages/twenty-ui/src/input/Radio/__stories__/Radio.stories.tsx
index 886d51b9afb..2d3a7bb74b7 100644
--- a/packages/twenty-ui/src/input/Radio/__stories__/Radio.stories.tsx
+++ b/packages/twenty-ui/src/input/Radio/__stories__/Radio.stories.tsx
@@ -1,4 +1,6 @@
import { type Meta, type StoryObj } from '@storybook/react-vite';
+
+import { RadioGroup } from '@ui/input/RadioGroup/RadioGroup';
import {
A11Y_DEFER_COLOR_CONTRAST,
CatalogDecorator,
@@ -6,61 +8,69 @@ import {
ComponentDecorator,
} from '@ui/testing';
-import { LabelPosition, Radio, RadioSize } from '@ui/input/Radio/Radio';
+import { Radio } from '../Radio';
+import { type RadioProps } from '../types/RadioProps';
+
+const RadioExample = ({
+ selected = false,
+ ...props
+}: RadioProps & { selected?: boolean }) => (
+ <RadioGroup value={selected ? props.value : ''}>
+ <Radio {...props} />
+ </RadioGroup>
+);
-const meta: Meta<typeof Radio> = {
- title: 'UI/Input/Radio/Radio',
- component: Radio,
+const meta: Meta<typeof RadioExample> = {
+ title: 'UI/Input/Radio',
+ component: RadioExample,
+ args: { value: 'radio', children: 'Radio' },
};
export default meta;
-type Story = StoryObj<typeof Radio>;
+type Story = StoryObj<typeof RadioExample>;
-export const Default: Story = {
- args: {
- label: 'Radio',
- checked: false,
- disabled: false,
- size: RadioSize.Small,
- },
- decorators: [ComponentDecorator],
+type RadioState = 'default' | 'hover' | 'focus' | 'disabled' | 'readOnly';
+
+const STATE_PROPS: Record<RadioState, Partial<RadioProps>> = {
+ default: {},
+ hover: { className: 'hover' },
+ focus: { className: 'focus' },
+ disabled: { disabled: true },
+ readOnly: { readOnly: true },
};
-export const Catalog: CatalogStory<Story, typeof Radio> = {
- args: {
- label: 'Radio',
- },
- argTypes: {
- size: { control: false },
- },
+export const Default: Story = { decorators: [ComponentDecorator] };
+
+export const Catalog: CatalogStory<Story, typeof RadioExample> = {
parameters: {
a11y: A11Y_DEFER_COLOR_CONTRAST,
+ pseudo: { hover: ['.hover'], focusVisible: ['.focus'] },
catalog: {
dimensions: [
{
- name: 'checked',
+ name: 'selected',
values: [false, true],
- props: (checked: boolean) => ({ checked }),
+ props: (selected: boolean) => ({ selected }),
},
{
- name: 'disabled',
- values: [false, true],
- props: (disabled: boolean) => ({ disabled }),
+ name: 'state',
+ values: Object.keys(STATE_PROPS),
+ props: (state: RadioState) => STATE_PROPS[state],
},
{
name: 'size',
- values: Object.values(RadioSize),
- props: (size: RadioSize) => ({ size }),
- },
- {
- name: 'labelPosition',
- values: Object.values(LabelPosition),
- props: (labelPosition: LabelPosition) => ({
- labelPosition,
- }),
+ values: ['sm', 'md'],
+ props: (size: RadioProps['size']) => ({ size }),
},
],
+ options: { elementContainer: { style: { width: 160 } } },
},
},
decorators: [CatalogDecorator],
};
+
+export const CatalogDark: typeof Catalog = {
+ ...Catalog,
+ tags: ['!autodocs'],
+ globals: { colorScheme: 'dark' },
+};
diff --git a/packages/twenty-ui/src/input/Radio/__tests__/Radio.test.tsx b/packages/twenty-ui/src/input/Radio/__tests__/Radio.test.tsx
new file mode 100644
index 00000000000..9422ab604d2
--- /dev/null
+++ b/packages/twenty-ui/src/input/Radio/__tests__/Radio.test.tsx
@@ -0,0 +1,38 @@
+import { type ReactNode } from 'react';
+
+import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';
+import { CardPicker } from '@ui/input/CardPicker/CardPicker';
+import cardPickerStyles from '@ui/input/CardPicker/CardPicker.module.scss';
+import { RadioGroup } from '@ui/input/RadioGroup/RadioGroup';
+import groupStyles from '@ui/input/RadioGroup/RadioGroup.module.scss';
+
+import { Radio } from '../Radio';
+import styles from '../Radio.module.scss';
+
+const RadioGroupWrapper = ({ children }: { children: ReactNode }) => (
+ <RadioGroup>{children}</RadioGroup>
+);
+
+runComponentConformance({
+ name: 'Radio',
+ element: <Radio value="option">Option</Radio>,
+ wrapper: RadioGroupWrapper,
+ refInstanceOf: HTMLSpanElement,
+ ownClassName: styles.root,
+});
+
+runComponentConformance({
+ name: 'RadioGroup',
+ element: <RadioGroup />,
+ refInstanceOf: HTMLDivElement,
+ ownClassName: groupStyles.root,
+});
+
+runComponentConformance({
+ name: 'CardPicker',
+ element: <CardPicker value="option">Option</CardPicker>,
+ wrapper: RadioGroupWrapper,
+ refInstanceOf: HTMLDivElement,
+ ownClassName: cardPickerStyles.container,
+ renderPropTagName: 'div',
+});
diff --git a/packages/twenty-ui/src/input/Radio/types/RadioProps.ts b/packages/twenty-ui/src/input/Radio/types/RadioProps.ts
new file mode 100644
index 00000000000..8938c2f5e52
--- /dev/null
+++ b/packages/twenty-ui/src/input/Radio/types/RadioProps.ts
@@ -0,0 +1,5 @@
+import { type Radio as RadioPrimitive } from '@base-ui/react/radio';
+
+export type RadioProps<TValue = string> = RadioPrimitive.Root.Props<TValue> & {
+ size?: 'sm' | 'md';
+};
diff --git a/packages/twenty-ui/src/input/RadioGroup/RadioGroup.module.scss b/packages/twenty-ui/src/input/RadioGroup/RadioGroup.module.scss
new file mode 100644
index 00000000000..15113ab9af9
--- /dev/null
+++ b/packages/twenty-ui/src/input/RadioGroup/RadioGroup.module.scss
@@ -0,0 +1,5 @@
+.root {
+ display: flex;
+ flex-direction: column;
+ gap: var(--t-spacing-2);
+}
diff --git a/packages/twenty-ui/src/input/RadioGroup/RadioGroup.module.scss.d.ts b/packages/twenty-ui/src/input/RadioGroup/RadioGroup.module.scss.d.ts
new file mode 100644
index 00000000000..4d6743c3dcd
--- /dev/null
+++ b/packages/twenty-ui/src/input/RadioGroup/RadioGroup.module.scss.d.ts
@@ -0,0 +1,4 @@
+declare const classNames: {
+ readonly root: 'root';
+};
+export default classNames;
diff --git a/packages/twenty-ui/src/input/RadioGroup/RadioGroup.tsx b/packages/twenty-ui/src/input/RadioGroup/RadioGroup.tsx
index 4c2f021d5c0..69870bf3dab 100644
--- a/packages/twenty-ui/src/input/RadioGroup/RadioGroup.tsx
+++ b/packages/twenty-ui/src/input/RadioGroup/RadioGroup.tsx
@@ -1,37 +1,16 @@
-import React from 'react';
+import { RadioGroup as RadioGroupPrimitive } from '@base-ui/react/radio-group';
-import { themeCssVariables } from '@ui/theme-constants';
-import { type RadioProps } from '@ui/input/Radio/Radio';
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
-type RadioGroupProps = React.PropsWithChildren & {
- value?: string;
- onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
- onValueChange?: (value: string) => void;
-};
+import styles from './RadioGroup.module.scss';
+import { type RadioGroupProps } from './types/RadioGroupProps';
-export const RadioGroup = ({
- value,
- onChange,
- onValueChange,
- children,
-}: RadioGroupProps) => {
- const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
- onChange?.(event);
- onValueChange?.(event.target.value);
- };
-
- return (
- <>
- {React.Children.map(children, (child) => {
- if (React.isValidElement<RadioProps>(child)) {
- return React.cloneElement(child, {
- style: { marginBottom: themeCssVariables.spacing[2] },
- checked: child.props.value === value,
- onChange: handleChange,
- });
- }
- return child;
- })}
- </>
- );
-};
+export const RadioGroup = <TValue,>({
+ className,
+ ...props
+}: RadioGroupProps<TValue>) => (
+ <RadioGroupPrimitive
+ {...props}
+ className={mergeClassNames(styles.root, className)}
+ />
+);
diff --git a/packages/twenty-ui/src/input/RadioGroup/types/RadioGroupProps.ts b/packages/twenty-ui/src/input/RadioGroup/types/RadioGroupProps.ts
new file mode 100644
index 00000000000..0edaf9e96b5
--- /dev/null
+++ b/packages/twenty-ui/src/input/RadioGroup/types/RadioGroupProps.ts
@@ -0,0 +1,4 @@
+import { type RadioGroup as RadioGroupPrimitive } from '@base-ui/react/radio-group';
+
+export type RadioGroupProps<TValue = string> =
+ RadioGroupPrimitive.Props<TValue>;
diff --git a/packages/twenty-ui/src/input/index.ts b/packages/twenty-ui/src/input/index.ts
index e437cc14311..fdf4c4518b8 100644
--- a/packages/twenty-ui/src/input/index.ts
+++ b/packages/twenty-ui/src/input/index.ts
@@ -23,6 +23,7 @@ export { baseTransitionTiming } from './Button/constant';
export type { ButtonGroupProps } from './ButtonGroup/ButtonGroup';
export { ButtonGroup } from './ButtonGroup/ButtonGroup';
export { CardPicker } from './CardPicker/CardPicker';
+export type { CardPickerProps } from './CardPicker/types/CardPickerProps';
export { Checkbox } from './Checkbox/Checkbox';
export type { CheckboxColor } from './Checkbox/types/CheckboxColor';
export type { CheckboxProps } from './Checkbox/types/CheckboxProps';
@@ -95,9 +96,10 @@ export type { LightIconButtonGroupProps } from './LightIconButtonGroup/LightIcon
export { LightIconButtonGroup } from './LightIconButtonGroup/LightIconButtonGroup';
export type { MainButtonVariant } from './MainButton/MainButton';
export { MainButton } from './MainButton/MainButton';
-export type { RadioProps } from './Radio/Radio';
-export { RadioSize, LabelPosition, Radio } from './Radio/Radio';
+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 { RoundedIconButtonSize } from './RoundedIconButton/RoundedIconButton';
export { RoundedIconButton } from './RoundedIconButton/RoundedIconButton';
export type { SearchInputProps } from './SearchInput/SearchInput';