Skip to content

The open alternative to Salesforce, designed for AI.

Migrate sort and editor toolbar dropdowns (#26599)

Raphaël Bosi1d6361ff9560
diff --git a/packages/twenty-docs/snippets/ui/generated/components/dropdown.mdx b/packages/twenty-docs/snippets/ui/generated/components/dropdown.mdx
index 5a589772f1c..b5380b54b7d 100644
--- a/packages/twenty-docs/snippets/ui/generated/components/dropdown.mdx
+++ b/packages/twenty-docs/snippets/ui/generated/components/dropdown.mdx
@@ -329,6 +329,63 @@
The value of the input. Use when controlled.
</ParamField>
+### Dropdown.Header
+
+<ParamField body="Header.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, {}&gt;">
+ Allows you to replace the component's HTML element
+ with a different tag, or compose it with another component.
+
+ Accepts a `ReactElement` or a function that returns the element to render.
+</ParamField>
+
+### Dropdown.Title
+
+<ParamField body="Title.className" type="string | ((state: PopoverTitleState) =&gt; string | undefined)">
+ CSS class applied to the element, or a function that
+ returns a class based on the component's state.
+</ParamField>
+
+<ParamField body="Title.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, PopoverTitleState&gt;">
+ Allows you to replace the component's HTML element
+ with a different tag, or compose it with another component.
+
+ Accepts a `ReactElement` or a function that returns the element to render.
+</ParamField>
+
+<ParamField body="Title.style" type="CSSProperties | ((state: PopoverTitleState) =&gt; CSSProperties | undefined)">
+ Style applied to the element, or a function that
+ returns a style object based on the component's state.
+</ParamField>
+
+### Dropdown.Close
+
+<ParamField body="Close.aria-label" type="string" required>
+
+</ParamField>
+
+<ParamField body="Close.className" type="string | ((state: PopoverCloseState) =&gt; string | undefined)">
+ CSS class applied to the element, or a function that
+ returns a class based on the component's state.
+</ParamField>
+
+<ParamField body="Close.nativeButton" type="boolean" default="true">
+ Whether the component renders a native `<button>` element when replacing it
+ via the `render` prop.
+ Set to `false` if the rendered element is not a button (for example, `<div>`).
+</ParamField>
+
+<ParamField body="Close.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, PopoverCloseState&gt;">
+ Allows you to replace the component's HTML element
+ with a different tag, or compose it with another component.
+
+ Accepts a `ReactElement` or a function that returns the element to render.
+</ParamField>
+
+<ParamField body="Close.style" type="CSSProperties | ((state: PopoverCloseState) =&gt; CSSProperties | undefined)">
+ Style applied to the element, or a function that
+ returns a style object based on the component's state.
+</ParamField>
+
### Dropdown.Page
<ParamField body="Page.id" type="string" required>
diff --git a/packages/twenty-docs/ui/components/dropdown.mdx b/packages/twenty-docs/ui/components/dropdown.mdx
index 0bce362ed96..bd2472215f1 100644
--- a/packages/twenty-docs/ui/components/dropdown.mdx
+++ b/packages/twenty-docs/ui/components/dropdown.mdx
@@ -24,7 +24,7 @@ Set `type` on `Dropdown.Root` to match the popup's contents.
| `picker` | Search, selectable values, and optional commands | A dialog containing a search field and selectable toggle buttons. Arrow keys navigate result rows. |
| `panel` | Inputs, forms, and supporting actions | A dialog with native input behavior and Tab navigation. |
-Pickers allow creation actions and selectable values in the same list, in any order. Options expose their selected state with `aria-pressed`; commands keep their button semantics. Use a descriptive accessible name on `Content` and `Search`.
+Pickers allow creation actions and selectable values in the same list, in any order. Options expose their selected state with `aria-pressed`; commands keep their button semantics. Name `Content` with `aria-label`, or with a `Title` inside a `Header`, and give `Search` an accessible name.
The underlying [Menu](/ui/primitives/surfaces/menu), [Select](/ui/primitives/input/select), and [Popover](/ui/primitives/surfaces/popover) remain available for direct composition.
@@ -34,6 +34,9 @@ The underlying [Menu](/ui/primitives/surfaces/menu), [Select](/ui/primitives/inp
Dropdown.Root
├── Dropdown.Trigger
└── Dropdown.Content
+ ├── Dropdown.Header
+ │ ├── Dropdown.Close
+ │ └── Dropdown.Title
├── Dropdown.Search
└── Dropdown.Section
├── Dropdown.ActionItem
@@ -63,6 +66,10 @@ export const RecordActions = ({ onDuplicate }: { onDuplicate: () => void }) => (
Pass custom trigger elements through `render` so the trigger remains one interactive element. Custom components must forward the supplied props and ref. `ActionItem` also accepts `render` for links.
+## Headers
+
+`Header` lays out a row at the top of the popup. Put a `Title` in it to name the popup: the title labels `Content` for assistive technology, so `Content` no longer needs `aria-label`. `Close` closes the popup the same way an outside press does. It renders an icon button with an X by default, so give it an `aria-label`, or pass `render` and children for another control. Other controls, such as a button that returns to a previous step, can sit in the same row. Use `Dropdown.Back` when navigating the root's page history.
+
## Search and selection
`Search` provides the input and navigation into the result rows. Pass `value` and `onValueChange`; compute or fetch matching results in your application. Render `Loading` while a request is pending and `Empty` when no results match. Both accept caller-provided status text.
@@ -111,6 +118,8 @@ export const PersonPicker = () => {
};
```
+While `Search` holds text, the first enabled `OptionItem` is highlighted and Enter activates it. Action rows are never picked this way. With an empty search, Enter does nothing; ArrowDown moves focus into the results. When rows are pinned above the matches, such as the current value or a "none" row, render them only when they match the search text, so Enter picks the first real match. The popup stays open when no option matches. Filtering remains caller-owned.
+
Actions and single selection close by default. Set `multiple` on the root to keep option selection open. The application still owns the selected values. `closeOnClick` on actions and `closeOnSelect` on options override those defaults, including repeated actions or asynchronous progress. Use `disabled` to prevent activation while retaining the row's appearance.
<StoryEmbed
@@ -166,6 +175,16 @@ Dropdown.Content
└── Dropdown.ActionItem
```
+## Independent nested pickers
+
+Place another `Dropdown.Root` inside `Content` when a control opens its own picker, such as a sort direction selector. Selecting an inner option closes only that picker and restores focus to its trigger. Escape and outside presses dismiss one layer at a time. Use `Submenu` for commands that should close the entire menu tree when selected.
+
+<StoryEmbed
+ storyId="ui-components-dropdown--nested"
+ title="Sort picker with a nested direction picker"
+ height={420}
+/>
+
## Panels and controlled state
Use `type="panel"` for form inputs. Input interaction keeps the panel open; a save action can close it. Own `open` and `onOpenChange` when another component or a shortcut needs to open the dropdown. Keep that state with the feature that coordinates the interaction.
diff --git a/packages/twenty-e2e-testing/tests/create-kanban-view.spec.ts b/packages/twenty-e2e-testing/tests/create-kanban-view.spec.ts
index adde31a779a..6f218dddc05 100644
--- a/packages/twenty-e2e-testing/tests/create-kanban-view.spec.ts
+++ b/packages/twenty-e2e-testing/tests/create-kanban-view.spec.ts
@@ -33,8 +33,12 @@ test('Create Kanban View from Industry Select Field', async ({ page }) => {
await page.getByRole('textbox').fill('By industry');
await page.getByRole('button', { name: 'Table', exact: true }).click();
await page.getByText('Kanban').click();
- await page.locator('[aria-controls="view-picker-kanban-field-options"]').click();
- await page.getByRole('option', { name: industryLabel }).click();
+ await page
+ .getByText('Stages', { exact: true })
+ .locator('xpath=..')
+ .getByRole('button')
+ .click();
+ await page.getByRole('button', { name: industryLabel }).click();
await page.getByRole('button', { name: 'Create new view' }).click();
await expect(page.getByText('Food')).toBeVisible({ timeout: 30000 });
await expect(page.getByText('Tech')).toBeVisible();
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/EditLinkDropdown.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/EditLinkDropdown.tsx
index 279f3b6a28d..6ebf70c12d3 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/EditLinkDropdown.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/EditLinkDropdown.tsx
@@ -1,5 +1,6 @@
import { EditLinkDropdownForm } from '@/advanced-text-editor/components/EditLinkDropdownForm';
import { type EditLinkEditor } from '@/advanced-text-editor/types/EditLinkEditor';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
import { useLingui } from '@lingui/react/macro';
import { isNonEmptyString } from '@sniptt/guards';
@@ -34,7 +35,7 @@ export const EditLinkDropdown = ({
</LightIconButton>
}
/>
- <Dropdown.Content
+ <DropdownContent
sideOffset={0}
align="end"
finalFocus={(interaction) =>
@@ -45,7 +46,7 @@ export const EditLinkDropdown = ({
<Dropdown.Section>
<EditLinkDropdownForm defaultValue={defaultValue} editor={editor} />
</Dropdown.Section>
- </Dropdown.Content>
+ </DropdownContent>
</DropdownRoot>
);
};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/TurnIntoBlockDropdown.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/TurnIntoBlockDropdown.tsx
index 1092fa47085..3b161bffd7d 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/TurnIntoBlockDropdown.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/TurnIntoBlockDropdown.tsx
@@ -1,10 +1,8 @@
-import { ListItem } from 'twenty-ui/primitives/navigation';
import { SelectOptionIcon } from '@/ui/input/components/SelectOptionIcon';
import { useTurnIntoBlockOptions } from '@/advanced-text-editor/hooks/useTurnIntoBlockOptions';
-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';
-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
-import { useToggleDropdown } from '@/ui/layout/dropdown/hooks/useToggleDropdown';
+import { Dropdown } from 'twenty-ui/components';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { type Editor } from '@tiptap/react';
@@ -47,7 +45,6 @@ export const TurnIntoBlockDropdown = ({
const theme = useTheme();
const instanceId = useId();
const dropdownId = `turn-into-block-dropdown-${instanceId}`;
- const { toggleDropdown } = useToggleDropdown();
const options = useTurnIntoBlockOptions(editor);
const activeItem = options.find((option) => option.isActive());
@@ -55,37 +52,34 @@ export const TurnIntoBlockDropdown = ({
activeItem ?? {};
return (
- <Dropdown
- dropdownComponents={
- <LegacyDropdownContent>
- <DropdownMenuItemsContainer>
- {options.map(({ id, title, icon, onClick }) => (
- <ListItem
- key={id}
- startIcon={<SelectOptionIcon Icon={icon} />}
- onClick={() => {
- onClick();
- toggleDropdown({
- dropdownComponentInstanceIdFromProps: dropdownId,
- });
- }}
- >
- {title}
- </ListItem>
- ))}
- </DropdownMenuItemsContainer>
- </LegacyDropdownContent>
- }
- dropdownId={dropdownId}
- clickableComponent={
- <StyledMenuItem>
- <ActiveIcon size={theme.icon.size.md} />
- {activeTitle}
- </StyledMenuItem>
- }
- dropdownOffset={{
- y: parseInt(theme.spacing[1], 10),
- }}
- />
+ <DropdownRoot dropdownId={dropdownId} type="picker">
+ <Dropdown.Trigger
+ render={
+ <StyledMenuItem>
+ <ActiveIcon size={theme.icon.size.md} />
+ {activeTitle}
+ </StyledMenuItem>
+ }
+ />
+ <DropdownContent
+ align="end"
+ sideOffset={parseInt(theme.spacing[1], 10)}
+ finalFocus={() => editor.view.dom}
+ aria-label={t`Turn into`}
+ >
+ <Dropdown.Section>
+ {options.map(({ id, title, icon, onClick, isActive }) => (
+ <Dropdown.OptionItem
+ key={id}
+ selected={isActive()}
+ startIcon={<SelectOptionIcon Icon={icon} />}
+ onSelect={onClick}
+ >
+ {title}
+ </Dropdown.OptionItem>
+ ))}
+ </Dropdown.Section>
+ </DropdownContent>
+ </DropdownRoot>
);
};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
index 79a99015b01..a5f505ae48e 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
@@ -3,7 +3,7 @@ import { useAdvancedTextEditor } from '@/advanced-text-editor/hooks/useAdvancedT
import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
import { buildFullRichTextWithVariableTagExtensions } from '@/advanced-text-editor/utils/buildFullRichTextExtensions';
import { type Meta, type StoryObj } from '@storybook/react-vite';
-import { expect, fn, userEvent, waitFor } from 'storybook/test';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
import { TIPTAP_DOCUMENT_SCHEMA_VERSION, isDefined } from 'twenty-shared/utils';
import { ComponentDecorator } from 'twenty-ui/testing';
import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
@@ -494,3 +494,35 @@ export const WithLists: Story = {
});
},
};
+
+export const TurnIntoHeading: Story = {
+ args: WithContent.args,
+ play: async ({ canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ await waitFor(() =>
+ expect(canvasElement.querySelector('.tiptap')).toBeInTheDocument(),
+ );
+ const editor = canvasElement.querySelector<HTMLElement>('.tiptap')!;
+ await userEvent.tripleClick(within(editor).getByText('World'));
+ const trigger = await body.findByRole('button', { name: 'Paragraph' });
+ await userEvent.click(trigger);
+ await userEvent.click(
+ await body.findByRole('button', { name: 'Heading 1' }),
+ );
+ await waitFor(() =>
+ expect(
+ body.queryByRole('dialog', { name: 'Turn into' }),
+ ).not.toBeInTheDocument(),
+ );
+ await waitFor(() => expect(editor).toHaveFocus());
+ await expect(
+ within(editor).getByRole('heading', { level: 1, name: /Hello.*World/ }),
+ ).toBeVisible();
+ await expect(
+ await body.findByRole('button', { name: 'Heading 1' }),
+ ).toBeVisible();
+ await expect(canvasElement.ownerDocument.getSelection()?.toString()).toBe(
+ 'World',
+ );
+ },
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiModelTierBars.tsx b/packages/twenty-front/src/modules/ai/components/AiModelTierBars.tsx
index b70d782bae4..e1fe01ffe32 100644
--- a/packages/twenty-front/src/modules/ai/components/AiModelTierBars.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiModelTierBars.tsx
@@ -1,3 +1,5 @@
+import { useRender } from '@base-ui/react/use-render';
+import { type ComponentProps } from 'react';
import { styled } from '@linaria/react';
import { type AiModelTier } from 'twenty-shared/ai';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -23,18 +25,27 @@ const StyledButton = styled.button<{ disabled: boolean }>`
}
`;
-type AiModelTierBarsProps = {
+type AiModelTierBarsProps = ComponentProps<'button'> & {
selectedTier: AiModelTier;
label: string;
- disabled?: boolean;
};
export const AiModelTierBars = ({
selectedTier,
label,
disabled = false,
-}: AiModelTierBarsProps) => (
- <StyledButton type="button" aria-label={label} disabled={disabled}>
- <AiModelTierIndicator tier={selectedTier} />
- </StyledButton>
-);
+ ref,
+ ...props
+}: AiModelTierBarsProps) =>
+ useRender({
+ defaultTagName: 'button',
+ render: <StyledButton disabled={disabled} />,
+ ref,
+ props: {
+ ...props,
+ type: 'button',
+ 'aria-label': label,
+ disabled,
+ children: <AiModelTierIndicator tier={selectedTier} />,
+ },
+ });
diff --git a/packages/twenty-front/src/modules/ai/components/AiModelTierDropdown.tsx b/packages/twenty-front/src/modules/ai/components/AiModelTierDropdown.tsx
index c8b5635f55f..fcd99ab5798 100644
--- a/packages/twenty-front/src/modules/ai/components/AiModelTierDropdown.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiModelTierDropdown.tsx
@@ -10,8 +10,9 @@ import { useAiModelTiers } from '@/ai/hooks/useAiModelTiers';
import { useIsWorkspaceSetupChat } from '@/ai/hooks/useIsWorkspaceSetupChat';
import { useWorkspaceAiModelTiers } from '@/ai/hooks/useWorkspaceAiModelTiers';
import { agentChatUserSelectedModelTierState } from '@/ai/states/agentChatUserSelectedModelTierState';
-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';
+import { Dropdown } from 'twenty-ui/components';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
const SLIDER_DROPDOWN_WIDTH_PX = 240;
@@ -48,35 +49,36 @@ export const AiModelTierDropdown = ({
};
return (
- <Dropdown
- dropdownId={dropdownId}
- dropdownPlacement="top-end"
- dropdownOffset={{ x: 0, y: 8 }}
- clickableComponent={
- <AiModelTierBars
- selectedTier={selectedTier}
- label={
- isDefined(selectedResolvedTier.model)
- ? t`${selectedResolvedTier.label}: ${selectedResolvedTier.model.label}`
- : selectedResolvedTier.label
- }
- disabled={disabled}
- />
- }
- dropdownComponents={
- <LegacyDropdownContent widthInPixels={SLIDER_DROPDOWN_WIDTH_PX}>
- <StyledSliderContainer
- role="group"
- aria-label={t`Choose a model mode`}
- >
- <AiModelTierSlider
- selectedTier={selectedTier}
- onTierChange={handleTierChange}
- disabled={disabled}
- />
- </StyledSliderContainer>
- </LegacyDropdownContent>
- }
- />
+ <DropdownRoot dropdownId={dropdownId} type="panel">
+ <Dropdown.Trigger
+ disabled={disabled}
+ render={
+ <AiModelTierBars
+ selectedTier={selectedTier}
+ label={
+ isDefined(selectedResolvedTier.model)
+ ? t`${selectedResolvedTier.label}: ${selectedResolvedTier.model.label}`
+ : selectedResolvedTier.label
+ }
+ disabled={disabled}
+ />
+ }
+ />
+ <DropdownContent
+ width={SLIDER_DROPDOWN_WIDTH_PX}
+ side="top"
+ align="end"
+ sideOffset={8}
+ aria-label={t`Choose a model mode`}
+ >
+ <StyledSliderContainer role="group" aria-label={t`Choose a model mode`}>
+ <AiModelTierSlider
+ selectedTier={selectedTier}
+ onTierChange={handleTierChange}
+ disabled={disabled}
+ />
+ </StyledSliderContainer>
+ </DropdownContent>
+ </DropdownRoot>
);
};
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiModelTierDropdown.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiModelTierDropdown.stories.tsx
new file mode 100644
index 00000000000..6793da3699b
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiModelTierDropdown.stories.tsx
@@ -0,0 +1,93 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { styled } from '@linaria/react';
+import { useStore } from 'jotai';
+import { useEffect } from 'react';
+import { expect, fireEvent, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { AiModelTierDropdown } from '@/ai/components/AiModelTierDropdown';
+import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';
+import { agentChatUserSelectedModelTierState } from '@/ai/states/agentChatUserSelectedModelTierState';
+import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
+
+const StyledTriggerContainer = styled.div`
+ margin-top: 200px;
+ margin-left: 200px;
+`;
+
+const meta: Meta<typeof AiModelTierDropdown> = {
+ title: 'Modules/AiChat/AiModelTierDropdown',
+ component: AiModelTierDropdown,
+ args: { dropdownId: 'model-tier-story' },
+ decorators: [
+ (Story, { parameters }) => {
+ const store = useStore();
+ const setupChat = parameters.setupChat === true;
+ useEffect(() => {
+ store.set(agentChatUserSelectedModelTierState.atom, null);
+ store.set(shouldOpenAiChatAfterOnboardingState.atom, setupChat);
+ return () =>
+ store.set(shouldOpenAiChatAfterOnboardingState.atom, false);
+ }, [store, setupChat]);
+ return (
+ <AiChatSurfaceContext.Provider value="side-panel">
+ <StyledTriggerContainer>
+ <Story />
+ </StyledTriggerContainer>
+ </AiChatSurfaceContext.Provider>
+ );
+ },
+ ComponentDecorator,
+ ],
+ parameters: { container: { height: 300 } },
+};
+export default meta;
+type Story = StoryObj<typeof AiModelTierDropdown>;
+
+export const ChangeTier: Story = {
+ play: async ({ canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ await userEvent.click(within(canvasElement).getByRole('button'));
+ const popup = await body.findByRole('dialog', {
+ name: 'Choose a model mode',
+ });
+ await expect(popup.getBoundingClientRect().width).toBe(240);
+ await waitFor(() => expect(popup).toHaveAttribute('data-side', 'top'));
+ await expect(popup).toHaveAttribute('data-align', 'end');
+ const slider = within(popup).getByRole('slider', { name: 'Model' });
+ slider.focus();
+ await expect(fireEvent.keyDown(slider, { key: 'ArrowRight' })).toBe(true);
+ fireEvent.change(slider, { target: { value: '1' } });
+ await expect(slider).toHaveValue('1');
+ await expect(popup).toBeVisible();
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ await expect(within(canvasElement).getByRole('button')).toHaveFocus();
+ },
+};
+
+export const Disabled: Story = {
+ args: { disabled: true },
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button');
+ await expect(trigger).toBeDisabled();
+ await userEvent.click(trigger);
+ await expect(
+ within(canvasElement.ownerDocument.body).queryByRole('dialog'),
+ ).not.toBeInTheDocument();
+ },
+};
+
+export const SetupChat: Story = {
+ parameters: { setupChat: true },
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button');
+ await expect(trigger).toHaveAccessibleName(/Fast/);
+ await userEvent.click(trigger);
+ await expect(
+ await within(canvasElement.ownerDocument.body).findByRole('slider'),
+ ).toHaveAttribute('aria-valuetext', 'Fast');
+ },
+};
diff --git a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/components/ObjectSortDropdownButton.tsx b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/components/ObjectSortDropdownButton.tsx
index e8af2f32c74..598e105bc68 100644
--- a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/components/ObjectSortDropdownButton.tsx
+++ b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/components/ObjectSortDropdownButton.tsx
@@ -1,40 +1,30 @@
-import { ListItem } from 'twenty-ui/primitives/navigation';
import { SelectOptionIcon } from '@/ui/input/components/SelectOptionIcon';
import { availableFieldMetadataItemsForSortFamilySelector } from '@/object-metadata/states/availableFieldMetadataItemsForSortFamilySelector';
import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
import { useCloseSortDropdown } from '@/object-record/object-sort-dropdown/hooks/useCloseSortDropdown';
import { useResetRecordSortDropdownSearchInput } from '@/object-record/object-sort-dropdown/hooks/useResetRecordSortDropdownSearchInput';
import { useResetSortDropdown } from '@/object-record/object-sort-dropdown/hooks/useResetSortDropdown';
-import { isRecordSortDirectionDropdownMenuUnfoldedComponentState } from '@/object-record/object-sort-dropdown/states/isRecordSortDirectionDropdownMenuUnfoldedComponentState';
import { objectSortDropdownSearchInputComponentState } from '@/object-record/object-sort-dropdown/states/objectSortDropdownSearchInputComponentState';
import { selectedRecordSortDirectionComponentState } from '@/object-record/object-sort-dropdown/states/selectedRecordSortDirectionComponentState';
import { getObjectSortDropdownId } from '@/object-record/object-sort-dropdown/utils/getObjectSortDropdownId';
import { visibleRecordFieldsComponentSelector } from '@/object-record/record-field/states/visibleRecordFieldsComponentSelector';
import { useRecordIndexContextOrThrow } from '@/object-record/record-index/contexts/RecordIndexContext';
import { useUpsertRecordSort } from '@/object-record/record-sort/hooks/useUpsertRecordSort';
-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';
-import { DropdownMenuHeader } from '@/ui/layout/dropdown/components/DropdownMenuHeader/DropdownMenuHeader';
-import { DropdownMenuHeaderLeftComponent } from '@/ui/layout/dropdown/components/DropdownMenuHeader/internal/DropdownMenuHeaderLeftComponent';
+import { Dropdown } from 'twenty-ui/components';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
import { DropdownMenuInnerSelect } from '@/ui/layout/dropdown/components/DropdownMenuInnerSelect';
-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
-import { DropdownMenuSearchInput } from '@/ui/layout/dropdown/components/DropdownMenuSearchInput';
-import { DropdownMenuSectionLabel } from '@/ui/layout/dropdown/components/DropdownMenuSectionLabel';
-import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';
import { StyledHeaderDropdownButton } from '@/ui/layout/dropdown/components/StyledHeaderDropdownButton';
import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';
-import { SelectableList } from '@/ui/layout/selectable-list/components/SelectableList';
-import { SelectableListItem } from '@/ui/layout/selectable-list/components/SelectableListItem';
-import { selectedItemIdComponentState } from '@/ui/layout/selectable-list/states/selectedItemIdComponentState';
import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
import { useAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentState';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
import { Trans, useLingui } from '@lingui/react/macro';
-import { findByProperty } from 'twenty-shared/utils';
-import { IconX, useIcons } from 'twenty-ui/icon';
+import { findByProperty, isNonEmptyArray } from 'twenty-shared/utils';
+import { useIcons } from 'twenty-ui/icon';
import { v4 } from 'uuid';
import { ViewSortDirection } from '~/generated-metadata/graphql';
@@ -103,16 +93,14 @@ export const ObjectSortDropdownButton = () => {
);
const shouldShowSeparator =
- visibleFieldMetadataItems.length > 0 &&
- hiddenFieldMetadataItemsSorted.length > 0;
+ isNonEmptyArray(visibleFieldMetadataItems) &&
+ isNonEmptyArray(hiddenFieldMetadataItemsSorted);
- const handleDropdownButtonClose = () => {
- resetRecordSortDropdownSearchInput();
- resetSortDropdown();
- };
-
- const handleDropdownOpen = () => {
+ const handleOpenChange = (open: boolean) => {
resetSortDropdown();
+ if (!open) {
+ resetRecordSortDropdownSearchInput();
+ }
};
const { closeSortDropdown } = useCloseSortDropdown();
@@ -132,15 +120,6 @@ export const ObjectSortDropdownButton = () => {
const [selectedRecordSortDirection, setSelectedRecordSortDirection] =
useAtomComponentState(selectedRecordSortDirectionComponentState);
- const setIsRecordSortDirectionDropdownMenuUnfolded = useSetAtomComponentState(
- isRecordSortDirectionDropdownMenuUnfoldedComponentState,
- );
-
- const handleSortDirectionClick = (sortDirection: ViewSortDirection) => {
- setSelectedRecordSortDirection(sortDirection);
- setIsRecordSortDirectionDropdownMenuUnfolded(false);
- };
-
const isDropdownOpen = useAtomComponentStateValue(
isDropdownOpenComponentState,
dropdownId,
@@ -148,149 +127,101 @@ export const ObjectSortDropdownButton = () => {
const { t } = useLingui();
- const selectableItemIdArray = [
- ...visibleFieldMetadataItems.map((item) => item.id),
- ...hiddenFieldMetadataItemsSorted.map((item) => item.id),
- ];
-
- const selectedItemId = useAtomComponentStateValue(
- selectedItemIdComponentState,
- dropdownId,
+ const shouldShowHiddenFields = isNonEmptyArray(
+ hiddenFieldMetadataItemsSorted,
);
-
- const shouldShowHiddenFields = hiddenFieldMetadataItemsSorted.length > 0;
- const shouldShowVisibleFields = visibleFieldMetadataItems.length > 0;
+ const shouldShowVisibleFields = isNonEmptyArray(visibleFieldMetadataItems);
return (
- <Dropdown
+ <DropdownRoot
dropdownId={dropdownId}
- dropdownOffset={{ y: 8 }}
- onOpen={handleDropdownOpen}
- clickableComponent={
- <StyledHeaderDropdownButton isUnfolded={isDropdownOpen}>
- <Trans>Sort</Trans>
- </StyledHeaderDropdownButton>
- }
- dropdownComponents={
- <LegacyDropdownContent
- widthInPixels={GenericDropdownContentWidth.ExtraLarge}
- >
- <DropdownMenuHeader
- StartComponent={
- <DropdownMenuHeaderLeftComponent
- onClick={() => closeSortDropdown()}
- Icon={IconX}
- />
- }
- >
- {t`Sort`}
- </DropdownMenuHeader>
- <DropdownMenuInnerSelect
- dropdownId={`${dropdownId}-direction`}
- options={[ViewSortDirection.ASC, ViewSortDirection.DESC].map(
- (sortDirection) => ({
- value: sortDirection,
- label:
- sortDirection === ViewSortDirection.ASC
- ? t`Ascending`
- : t`Descending`,
- }),
- )}
- selectedOption={{
- value: selectedRecordSortDirection,
+ type="picker"
+ onOpenChange={handleOpenChange}
+ >
+ <Dropdown.Trigger
+ render={
+ <StyledHeaderDropdownButton isUnfolded={isDropdownOpen}>
+ <Trans>Sort</Trans>
+ </StyledHeaderDropdownButton>
+ }
+ />
+ <DropdownContent
+ width={GenericDropdownContentWidth.ExtraLarge}
+ align="end"
+ sideOffset={8}
+ >
+ <Dropdown.Header>
+ <Dropdown.Close aria-label={t`Close`} />
+ <Dropdown.Title>{t`Sort`}</Dropdown.Title>
+ </Dropdown.Header>
+ <DropdownMenuInnerSelect
+ dropdownId={`${dropdownId}-direction`}
+ options={[ViewSortDirection.ASC, ViewSortDirection.DESC].map(
+ (sortDirection) => ({
+ value: sortDirection,
label:
- selectedRecordSortDirection === ViewSortDirection.ASC
+ sortDirection === ViewSortDirection.ASC
? t`Ascending`
: t`Descending`,
- }}
- onChange={(sortDirection) =>
- handleSortDirectionClick(sortDirection.value as ViewSortDirection)
- }
- widthInPixels={GenericDropdownContentWidth.ExtraLarge}
- />
- <DropdownMenuSeparator />
- <DropdownMenuSearchInput
- autoFocus
- value={objectSortDropdownSearchInput}
- placeholder={t`Search fields`}
- onChange={(event) =>
- setObjectSortDropdownSearchInput(event.target.value)
- }
- />
- <SelectableList
- selectableListInstanceId={dropdownId}
- selectableItemIdArray={selectableItemIdArray}
- focusId={dropdownId}
- >
- {shouldShowVisibleFields && (
- <>
- <DropdownMenuSectionLabel label={t`Visible fields`} />
- <DropdownMenuItemsContainer>
- {visibleFieldMetadataItems.map(
- (visibleFieldMetadataItem, index) => (
- <SelectableListItem
- key={visibleFieldMetadataItem.id}
- itemId={visibleFieldMetadataItem.id}
- onEnter={() => handleAddSort(visibleFieldMetadataItem)}
- >
- <ListItem
- focused={
- selectedItemId === visibleFieldMetadataItem.id
- }
- data-testid={`visible-select-sort-${index}`}
- onClick={() =>
- handleAddSort(visibleFieldMetadataItem)
- }
- startIcon={
- <SelectOptionIcon
- Icon={getIcon(visibleFieldMetadataItem.icon)}
- />
- }
- >
- {visibleFieldMetadataItem.label}
- </ListItem>
- </SelectableListItem>
- ),
- )}
- </DropdownMenuItemsContainer>
- </>
- )}
- {shouldShowSeparator && <DropdownMenuSeparator />}
- {shouldShowHiddenFields && (
- <>
- <DropdownMenuSectionLabel label={t`Hidden fields`} />
- <DropdownMenuItemsContainer>
- {hiddenFieldMetadataItemsSorted.map(
- (hiddenFieldMetadataItem, index) => (
- <SelectableListItem
- key={hiddenFieldMetadataItem.id}
- itemId={hiddenFieldMetadataItem.id}
- onEnter={() => handleAddSort(hiddenFieldMetadataItem)}
- >
- <ListItem
- focused={
- selectedItemId === hiddenFieldMetadataItem.id
- }
- data-testid={`hidden-select-sort-${index}`}
- onClick={() => handleAddSort(hiddenFieldMetadataItem)}
- startIcon={
- <SelectOptionIcon
- Icon={getIcon(hiddenFieldMetadataItem.icon)}
- />
- }
- >
- {hiddenFieldMetadataItem.label}
- </ListItem>
- </SelectableListItem>
- ),
- )}
- </DropdownMenuItemsContainer>
- </>
- )}
- </SelectableList>
- </LegacyDropdownContent>
- }
- onClose={handleDropdownButtonClose}
- />
+ }),
+ )}
+ selectedOption={{
+ value: selectedRecordSortDirection,
+ label:
+ selectedRecordSortDirection === ViewSortDirection.ASC
+ ? t`Ascending`
+ : t`Descending`,
+ }}
+ onChange={(sortDirection) =>
+ setSelectedRecordSortDirection(
+ sortDirection.value as ViewSortDirection,
+ )
+ }
+ widthInPixels={GenericDropdownContentWidth.ExtraLarge}
+ />
+ <Dropdown.Separator />
+ <Dropdown.Search
+ value={objectSortDropdownSearchInput}
+ placeholder={t`Search fields`}
+ aria-label={t`Search fields`}
+ onValueChange={setObjectSortDropdownSearchInput}
+ />
+ {shouldShowVisibleFields && (
+ <Dropdown.Section label={t`Visible fields`}>
+ {visibleFieldMetadataItems.map((fieldMetadataItem, index) => (
+ <Dropdown.OptionItem
+ key={fieldMetadataItem.id}
+ selected={false}
+ data-testid={`visible-select-sort-${index}`}
+ onSelect={() => handleAddSort(fieldMetadataItem)}
+ startIcon={
+ <SelectOptionIcon Icon={getIcon(fieldMetadataItem.icon)} />
+ }
+ >
+ {fieldMetadataItem.label}
+ </Dropdown.OptionItem>
+ ))}
+ </Dropdown.Section>
+ )}
+ {shouldShowSeparator && <Dropdown.Separator />}
+ {shouldShowHiddenFields && (
+ <Dropdown.Section label={t`Hidden fields`}>
+ {hiddenFieldMetadataItemsSorted.map((fieldMetadataItem, index) => (
+ <Dropdown.OptionItem
+ key={fieldMetadataItem.id}
+ selected={false}
+ data-testid={`hidden-select-sort-${index}`}
+ onSelect={() => handleAddSort(fieldMetadataItem)}
+ startIcon={
+ <SelectOptionIcon Icon={getIcon(fieldMetadataItem.icon)} />
+ }
+ >
+ {fieldMetadataItem.label}
+ </Dropdown.OptionItem>
+ ))}
+ </Dropdown.Section>
+ )}
+ </DropdownContent>
+ </DropdownRoot>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/components/__stories__/ObjectSortDropdownButton.stories.tsx b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/components/__stories__/ObjectSortDropdownButton.stories.tsx
new file mode 100644
index 00000000000..17438c804b1
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/components/__stories__/ObjectSortDropdownButton.stories.tsx
@@ -0,0 +1,72 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+import { ContextStoreDecorator } from '~/testing/decorators/ContextStoreDecorator';
+import { IconsProviderDecorator } from '~/testing/decorators/IconsProviderDecorator';
+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
+import { SortViewDecorator } from '~/testing/decorators/SortViewDecorator';
+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';
+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
+import { ObjectSortDropdownButton } from '@/object-record/object-sort-dropdown/components/ObjectSortDropdownButton';
+
+const meta: Meta<typeof ObjectSortDropdownButton> = {
+ title: 'Modules/ObjectSortDropdown/ObjectSortDropdownButton',
+ component: ObjectSortDropdownButton,
+ decorators: [
+ SortViewDecorator,
+ ContextStoreDecorator,
+ ObjectMetadataItemsDecorator,
+ ToastDecorator,
+ ComponentDecorator,
+ IconsProviderDecorator,
+ MemoryRouterDecorator,
+ ],
+};
+export default meta;
+type Story = StoryObj<typeof ObjectSortDropdownButton>;
+
+export const SearchAndDirection: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const trigger = await canvas.findByRole('button', { name: 'Sort' });
+ await userEvent.click(trigger);
+ await waitFor(() => expect(body.getByText('Visible fields')).toBeVisible());
+ await expect(body.getByText('Hidden fields')).toBeVisible();
+ await expect(body.getByTestId('visible-select-sort-0')).toBeVisible();
+ await expect(body.getByTestId('hidden-select-sort-0')).toBeVisible();
+ await userEvent.click(body.getByRole('button', { name: 'Ascending' }));
+ await userEvent.click(
+ await body.findByRole('button', { name: 'Descending' }),
+ );
+ await expect(body.getByRole('dialog', { name: 'Sort' })).toBeVisible();
+ const direction = body.getByRole('button', { name: 'Descending' });
+ await userEvent.click(direction);
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(direction).toHaveFocus());
+ await waitFor(() => expect(body.getAllByRole('dialog')).toHaveLength(1));
+ await userEvent.click(direction);
+ await waitFor(() => expect(body.getAllByRole('dialog')).toHaveLength(2));
+ await userEvent.click(canvasElement);
+ await waitFor(() => expect(body.getAllByRole('dialog')).toHaveLength(1));
+ const search = body.getByRole('searchbox', { name: 'Search fields' });
+ await userEvent.type(search, 'Tagline');
+ await expect(body.queryByText('Visible fields')).not.toBeInTheDocument();
+ await userEvent.keyboard('{Enter}');
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ await userEvent.click(trigger);
+ await expect(
+ await body.findByRole('button', { name: 'Ascending' }),
+ ).toBeVisible();
+ await expect(body.getByRole('searchbox')).toHaveValue('');
+ await userEvent.type(body.getByRole('searchbox'), 'Name');
+ await userEvent.click(body.getByRole('button', { name: 'Close' }));
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ await userEvent.click(trigger);
+ await expect(await body.findByRole('searchbox')).toHaveValue('');
+ },
+};
diff --git a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/hooks/useResetSortDropdown.ts b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/hooks/useResetSortDropdown.ts
index a41a76194e0..499487c34ec 100644
--- a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/hooks/useResetSortDropdown.ts
+++ b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/hooks/useResetSortDropdown.ts
@@ -1,19 +1,13 @@
-import { isRecordSortDirectionDropdownMenuUnfoldedComponentState } from '@/object-record/object-sort-dropdown/states/isRecordSortDirectionDropdownMenuUnfoldedComponentState';
import { selectedRecordSortDirectionComponentState } from '@/object-record/object-sort-dropdown/states/selectedRecordSortDirectionComponentState';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
import { ViewSortDirection } from '~/generated-metadata/graphql';
export const useResetSortDropdown = () => {
- const setIsRecordSortDirectionDropdownMenuUnfolded = useSetAtomComponentState(
- isRecordSortDirectionDropdownMenuUnfoldedComponentState,
- );
-
const setSelectedRecordSortDirection = useSetAtomComponentState(
selectedRecordSortDirectionComponentState,
);
const resetSortDropdown = () => {
- setIsRecordSortDirectionDropdownMenuUnfolded(false);
setSelectedRecordSortDirection(ViewSortDirection.ASC);
};
diff --git a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/states/isRecordSortDirectionDropdownMenuUnfoldedComponentState.ts b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/states/isRecordSortDirectionDropdownMenuUnfoldedComponentState.ts
deleted file mode 100644
index 35390a791b9..00000000000
--- a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/states/isRecordSortDirectionDropdownMenuUnfoldedComponentState.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { ObjectSortDropdownComponentInstanceContext } from '@/object-record/object-sort-dropdown/states/context/ObjectSortDropdownComponentInstanceContext';
-import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';
-
-export const isRecordSortDirectionDropdownMenuUnfoldedComponentState =
- createAtomComponentState<boolean>({
- key: 'isRecordSortDirectionDropdownMenuUnfoldedComponentState',
- defaultValue: false,
- componentInstanceContext: ObjectSortDropdownComponentInstanceContext,
- });
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingDropdown.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingDropdown.tsx
index 7222da8ad62..c77b92a4cf4 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingDropdown.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingDropdown.tsx
@@ -8,6 +8,7 @@ import { RecordSharingDropdownContent } from '@/object-record/record-sharing/com
import { useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
import { Dropdown } from 'twenty-ui/components';
import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
@@ -55,13 +56,13 @@ export const RecordSharingDropdown = ({
>{t`Share`}</Button>
}
/>
- <Dropdown.Content width={320} align="end" aria-label={title}>
+ <DropdownContent width={320} align="end">
<RecordSharingDropdownContent
title={title}
recordUrl={recordUrl}
sharingState={sharingState}
/>
- </Dropdown.Content>
+ </DropdownContent>
</DropdownRoot>
)}
</>
diff --git a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingDropdownContent.tsx b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingDropdownContent.tsx
index dbb4f1c6c05..45ed5d37d05 100644
--- a/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingDropdownContent.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-sharing/components/RecordSharingDropdownContent.tsx
@@ -16,7 +16,6 @@ import { RecordSharingAccessSelect } from '@/object-record/record-sharing/compon
import { RECORD_SHARE_ACCESS_LEVEL_OPTIONS } from '@/object-record/record-sharing/constants/RecordShareAccessLevelOptions';
import { type useRecordSharing } from '@/object-record/record-sharing/hooks/useRecordSharing';
import { getRecordShareLabel } from '@/object-record/record-sharing/utils/getRecordShareLabel';
-import { DropdownMenuHeader } from '@/ui/layout/dropdown/components/DropdownMenuHeader/DropdownMenuHeader';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { RecordShareAccessLevel } from '~/generated-metadata/graphql';
import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
@@ -91,7 +90,9 @@ export const RecordSharingDropdownContent = ({
return (
<>
- <DropdownMenuHeader>{title}</DropdownMenuHeader>
+ <Dropdown.Header>
+ <Dropdown.Title>{title}</Dropdown.Title>
+ </Dropdown.Header>
{loading ? (
<Dropdown.Loading>{t`Loading…`}</Dropdown.Loading>
) : error ? (
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/DashboardColorSelectionMenu.tsx b/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/DashboardColorSelectionMenu.tsx
index ed8ac9baf8b..53ee57910ef 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/DashboardColorSelectionMenu.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/DashboardColorSelectionMenu.tsx
@@ -1,45 +1,10 @@
-import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { IconCheck } from 'twenty-ui/icon';
+import { Dropdown } from 'twenty-ui/components';
import { DashboardColorIcon } from '@/page-layout/widgets/standalone-rich-text/components/DashboardColorIcon';
import { BLOCKNOTE_COLOR_DISPLAY_NAMES } from '@/page-layout/widgets/standalone-rich-text/constants/BlockNoteColorDisplayNames';
import { BLOCKNOTE_COLORS } from '@/page-layout/widgets/standalone-rich-text/constants/BlockNoteColors';
import { type BlockNoteColor } from '@/page-layout/widgets/standalone-rich-text/types/BlockNoteColor';
-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';
-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
-import { DropdownMenuSectionLabel } from '@/ui/layout/dropdown/components/DropdownMenuSectionLabel';
-import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';
-import { themeCssVariables, useTheme } from 'twenty-ui/theme';
-
-const StyledColorMenuItem = styled.div`
- align-items: center;
- border-radius: ${themeCssVariables.border.radius.sm};
- cursor: pointer;
- display: flex;
- gap: ${themeCssVariables.spacing[2]};
- min-height: ${themeCssVariables.spacing[6]};
- padding: ${themeCssVariables.spacing[1]} ${themeCssVariables.spacing[2]};
-
- &:hover {
- background: ${themeCssVariables.background.transparent.light};
- }
-`;
-
-const StyledColorName = styled.span`
- color: ${themeCssVariables.font.color.primary};
- flex: 1;
- font-size: ${themeCssVariables.font.size.sm};
-`;
-
-const StyledCheckIcon = styled.div`
- align-items: center;
- color: ${themeCssVariables.font.color.primary};
- display: flex;
- height: ${themeCssVariables.spacing[4]};
- justify-content: center;
- width: ${themeCssVariables.spacing[4]};
-`;
type DashboardColorSelectionMenuProps = {
currentTextColor: string;
@@ -55,49 +20,36 @@ export const DashboardColorSelectionMenu = ({
onBackgroundColorSelect,
}: DashboardColorSelectionMenuProps) => {
const { t } = useLingui();
- const theme = useTheme();
- return (
- <LegacyDropdownContent>
- <DropdownMenuItemsContainer hasMaxHeight>
- <DropdownMenuSectionLabel label={t`Text Colors`} />
+ return (
+ <>
+ <Dropdown.Section label={t`Text Colors`}>
{BLOCKNOTE_COLORS.map((colorName) => (
- <StyledColorMenuItem
- key={`text-${colorName}`}
- onClick={() => onTextColorSelect(colorName)}
+ <Dropdown.OptionItem
+ key={colorName}
+ aria-label={BLOCKNOTE_COLOR_DISPLAY_NAMES[colorName]}
+ selected={currentTextColor === colorName}
+ startIcon={<DashboardColorIcon textColor={colorName} />}
+ onSelect={() => onTextColorSelect(colorName)}
>
- <DashboardColorIcon textColor={colorName} />
- <StyledColorName>
- {BLOCKNOTE_COLOR_DISPLAY_NAMES[colorName]}
- </StyledColorName>
- {currentTextColor === colorName && (
- <StyledCheckIcon>
- <IconCheck size={theme.icon.size.sm} />
- </StyledCheckIcon>
- )}
- </StyledColorMenuItem>
+ {BLOCKNOTE_COLOR_DISPLAY_NAMES[colorName]}
+ </Dropdown.OptionItem>
))}
-
- <DropdownMenuSeparator />
-
- <DropdownMenuSectionLabel label={t`Background Colors`} />
+ </Dropdown.Section>
+ <Dropdown.Separator />
+ <Dropdown.Section label={t`Background Colors`}>
{BLOCKNOTE_COLORS.map((colorName) => (
- <StyledColorMenuItem
- key={`bg-${colorName}`}
- onClick={() => onBackgroundColorSelect(colorName)}
+ <Dropdown.OptionItem
+ key={colorName}
+ aria-label={BLOCKNOTE_COLOR_DISPLAY_NAMES[colorName]}
+ selected={currentBackgroundColor === colorName}
+ startIcon={<DashboardColorIcon backgroundColor={colorName} />}
+ onSelect={() => onBackgroundColorSelect(colorName)}
>
- <DashboardColorIcon backgroundColor={colorName} />
- <StyledColorName>
- {BLOCKNOTE_COLOR_DISPLAY_NAMES[colorName]}
- </StyledColorName>
- {currentBackgroundColor === colorName && (
- <StyledCheckIcon>
- <IconCheck size={theme.icon.size.sm} />
- </StyledCheckIcon>
- )}
- </StyledColorMenuItem>
+ {BLOCKNOTE_COLOR_DISPLAY_NAMES[colorName]}
+ </Dropdown.OptionItem>
))}
- </DropdownMenuItemsContainer>
- </LegacyDropdownContent>
+ </Dropdown.Section>
+ </>
);
};
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/DashboardFormattingToolbarColorButton.tsx b/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/DashboardFormattingToolbarColorButton.tsx
index af2ee0e80f3..4fdef34d208 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/DashboardFormattingToolbarColorButton.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/DashboardFormattingToolbarColorButton.tsx
@@ -1,24 +1,16 @@
import { useActiveStyles, useBlockNoteEditor } from '@blocknote/react';
import { styled } from '@linaria/react';
-import {
- autoUpdate,
- flip,
- offset,
- shift,
- useFloating,
-} from '@floating-ui/react';
-import { useRef, useState } from 'react';
-import { createPortal } from 'react-dom';
+import { useLingui } from '@lingui/react/macro';
+import { useId } from 'react';
+import { Dropdown } from 'twenty-ui/components';
+import { themeCssVariables } from 'twenty-ui/theme';
import { DashboardColorIcon } from '@/page-layout/widgets/standalone-rich-text/components/DashboardColorIcon';
import { DashboardColorSelectionMenu } from '@/page-layout/widgets/standalone-rich-text/components/DashboardColorSelectionMenu';
-import { COLOR_DROPDOWN_FLOATING_CONFIG } from '@/page-layout/widgets/standalone-rich-text/constants/ColorDropdownFloatingConfig';
import { type BlockNoteColor } from '@/page-layout/widgets/standalone-rich-text/types/BlockNoteColor';
import { extractColorFromProps } from '@/page-layout/widgets/standalone-rich-text/utils/extractColorFromProps';
-import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContainer';
-import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
-import { isDefined } from 'twenty-shared/utils';
-import { themeCssVariables } from 'twenty-ui/theme';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
const StyledColorButton = styled.button`
align-items: center;
@@ -37,14 +29,10 @@ const StyledColorButton = styled.button`
}
`;
-const COLOR_BUTTON_CLICK_OUTSIDE_ID = 'color-button-click-outside';
-
export const DashboardFormattingToolbarColorButton = () => {
const editor = useBlockNoteEditor();
- const buttonRef = useRef<HTMLButtonElement>(null);
- const menuRef = useRef<HTMLDivElement>(null);
- const [isOpen, setIsOpen] = useState(false);
-
+ const { t } = useLingui();
+ const instanceId = useId();
const activeStyles = useActiveStyles(editor);
const currentTextColor = extractColorFromProps(activeStyles, 'text');
const currentBackgroundColor = extractColorFromProps(
@@ -52,97 +40,50 @@ export const DashboardFormattingToolbarColorButton = () => {
'background',
);
- const { refs, floatingStyles } = useFloating({
- strategy: 'fixed',
- placement: 'bottom-start',
- whileElementsMounted: autoUpdate,
- middleware: [
- offset(COLOR_DROPDOWN_FLOATING_CONFIG.offsetFromButton),
- flip(),
- shift({ padding: COLOR_DROPDOWN_FLOATING_CONFIG.boundaryPadding }),
- ],
- });
-
- useListenClickOutside({
- refs: [menuRef],
- excludedClickOutsideIds: [COLOR_BUTTON_CLICK_OUTSIDE_ID],
- callback: () => setIsOpen(false),
- listenerId: 'custom-color-style-button',
- });
-
- const handleButtonClick = () => {
- if (isDefined(buttonRef.current)) {
- refs.setReference(buttonRef.current);
- }
- setIsOpen(!isOpen);
- };
-
- const applyTextColor = (color: string) => {
+ const handleTextColorSelect = (color: BlockNoteColor) => {
if (color === 'default') {
editor.removeStyles({ textColor: color });
- } else {
- editor.addStyles({ textColor: color });
+ return;
}
- setTimeout(() => editor.focus());
+ editor.addStyles({ textColor: color });
};
- const applyBackgroundColor = (color: string) => {
+ const handleBackgroundColorSelect = (color: BlockNoteColor) => {
if (color === 'default') {
editor.removeStyles({ backgroundColor: color });
- } else {
- editor.addStyles({ backgroundColor: color });
+ return;
}
- setTimeout(() => editor.focus());
- };
-
- const handleTextColorSelect = (color: BlockNoteColor) => {
- applyTextColor(color);
- setIsOpen(false);
- };
-
- const handleBackgroundColorSelect = (color: BlockNoteColor) => {
- applyBackgroundColor(color);
- setIsOpen(false);
+ editor.addStyles({ backgroundColor: color });
};
return (
- <>
- <StyledColorButton
- ref={buttonRef}
- onClick={handleButtonClick}
- data-click-outside-id={COLOR_BUTTON_CLICK_OUTSIDE_ID}
+ <DropdownRoot dropdownId={`dashboard-color-${instanceId}`} type="picker">
+ <Dropdown.Trigger
+ render={
+ <StyledColorButton aria-label={t`Text and background colors`}>
+ <DashboardColorIcon
+ textColor={currentTextColor}
+ backgroundColor={currentBackgroundColor}
+ />
+ </StyledColorButton>
+ }
+ />
+ <DropdownContent
+ sideOffset={8}
+ className="bn-ui-container"
+ aria-label={t`Text and background colors`}
+ finalFocus={() => {
+ editor.focus();
+ return false;
+ }}
>
- <DashboardColorIcon
- textColor={currentTextColor}
- backgroundColor={currentBackgroundColor}
+ <DashboardColorSelectionMenu
+ currentTextColor={currentTextColor}
+ currentBackgroundColor={currentBackgroundColor}
+ onTextColorSelect={handleTextColorSelect}
+ onBackgroundColorSelect={handleBackgroundColorSelect}
/>
- </StyledColorButton>
-
- {isOpen &&
- createPortal(
- <OverlayContainer
- ref={(node) => {
- refs.setFloating(node);
- (
- menuRef as React.MutableRefObject<HTMLDivElement | null>
- ).current = node;
- }}
- style={{
- ...floatingStyles,
- zIndex: COLOR_DROPDOWN_FLOATING_CONFIG.zIndex,
- }}
- className="bn-ui-container"
- data-click-outside-id={COLOR_BUTTON_CLICK_OUTSIDE_ID}
- >
- <DashboardColorSelectionMenu
- currentTextColor={currentTextColor}
- currentBackgroundColor={currentBackgroundColor}
- onTextColorSelect={handleTextColorSelect}
- onBackgroundColorSelect={handleBackgroundColorSelect}
- />
- </OverlayContainer>,
- document.body,
- )}
- </>
+ </DropdownContent>
+ </DropdownRoot>
);
};
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/__stories__/DashboardFormattingToolbarColorButton.stories.tsx b/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/__stories__/DashboardFormattingToolbarColorButton.stories.tsx
new file mode 100644
index 00000000000..24c7bf54276
--- /dev/null
+++ b/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/components/__stories__/DashboardFormattingToolbarColorButton.stories.tsx
@@ -0,0 +1,76 @@
+import { useCreateBlockNote } from '@blocknote/react';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { DashboardsBlockEditor } from '@/page-layout/widgets/standalone-rich-text/components/DashboardsBlockEditor';
+import { DASHBOARD_BLOCK_SCHEMA } from '@/page-layout/widgets/standalone-rich-text/constants/DashboardBlockSchema';
+
+const ColorToolbarExample = () => {
+ const editor = useCreateBlockNote({
+ schema: DASHBOARD_BLOCK_SCHEMA,
+ initialContent: [{ type: 'paragraph', content: 'Color this text' }],
+ });
+ return <DashboardsBlockEditor editor={editor} />;
+};
+
+const meta: Meta<typeof ColorToolbarExample> = {
+ title: 'Modules/PageLayout/DashboardFormattingToolbarColorButton',
+ component: ColorToolbarExample,
+ decorators: [ComponentDecorator],
+};
+export default meta;
+type Story = StoryObj<typeof ColorToolbarExample>;
+
+export const ApplyColors: Story = {
+ play: async ({ canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ const editor = canvasElement.querySelector<HTMLElement>(
+ '[contenteditable="true"]',
+ )!;
+ await userEvent.tripleClick(within(editor).getByText('Color this text'));
+ const selectedText = canvasElement.ownerDocument.getSelection()?.toString();
+ await expect(selectedText).not.toBe('');
+ await userEvent.click(
+ await body.findByRole('button', { name: 'Text and background colors' }),
+ );
+ const popup = await body.findByRole('dialog', {
+ name: 'Text and background colors',
+ });
+ await expect(popup).toHaveClass('bn-ui-container');
+ await expect(within(popup).getByText('Text Colors')).toBeVisible();
+ await expect(within(popup).getByText('Background Colors')).toBeVisible();
+ await expect(
+ within(popup).getAllByRole('button', { name: 'Default' })[0],
+ ).toHaveAttribute('aria-pressed', 'true');
+ await userEvent.click(
+ within(popup).getAllByRole('button', { name: 'Red' })[0],
+ );
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ await waitFor(() => expect(editor).toHaveFocus());
+ await expect(
+ editor.querySelector('[data-style-type="textColor"][data-value="red"]'),
+ ).toHaveTextContent(selectedText!);
+ await userEvent.click(
+ await body.findByRole('button', { name: 'Text and background colors' }),
+ );
+ const reopened = await body.findByRole('dialog');
+ await expect(
+ within(reopened).getAllByRole('button', { name: 'Red' })[0],
+ ).toHaveAttribute('aria-pressed', 'true');
+ await userEvent.click(
+ within(reopened).getAllByRole('button', { name: 'Blue' })[1],
+ );
+ await waitFor(() => expect(editor).toHaveFocus());
+ await expect(
+ editor.querySelector(
+ '[data-style-type="backgroundColor"][data-value="blue"]',
+ ),
+ ).toHaveTextContent(selectedText!);
+ await expect(
+ await body.findByRole('button', { name: 'Text and background colors' }),
+ ).toBeVisible();
+ },
+};
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/constants/ColorDropdownFloatingConfig.ts b/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/constants/ColorDropdownFloatingConfig.ts
deleted file mode 100644
index 4c2a07db36a..00000000000
--- a/packages/twenty-front/src/modules/page-layout/widgets/standalone-rich-text/constants/ColorDropdownFloatingConfig.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const COLOR_DROPDOWN_FLOATING_CONFIG = {
- offsetFromButton: 8,
- boundaryPadding: 8,
- // BlockNote's formatting toolbar uses z-index 40.
- zIndex: 41,
-};
diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelObjectFilterDropdownContent.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelObjectFilterDropdownContent.tsx
index d16d72955f0..49079ac91a7 100644
--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelObjectFilterDropdownContent.tsx
+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelObjectFilterDropdownContent.tsx
@@ -51,6 +51,12 @@ export const SidePanelObjectFilterDropdownContent = ({
return item.labelPlural.toLowerCase().includes(searchFilter);
});
+ const allObjectsLabel = t`All objects`;
+
+ const isAllObjectsOptionMatchingSearch = allObjectsLabel
+ .toLowerCase()
+ .includes(searchFilter);
+
return (
<>
<StyledHeader>{t`Object`}</StyledHeader>
@@ -62,11 +68,15 @@ export const SidePanelObjectFilterDropdownContent = ({
/>
<Dropdown.Separator />
<Dropdown.Section scrollable>
- <Dropdown.OptionItem
- onSelect={() => onSelectObject(null)}
- selected={selectedObjectNameSingular === null}
- startIcon={<TintedIconTile Icon={IconCube} />}
- >{t`All objects`}</Dropdown.OptionItem>
+ {isAllObjectsOptionMatchingSearch && (
+ <Dropdown.OptionItem
+ onSelect={() => onSelectObject(null)}
+ selected={selectedObjectNameSingular === null}
+ startIcon={<TintedIconTile Icon={IconCube} />}
+ >
+ {allObjectsLabel}
+ </Dropdown.OptionItem>
+ )}
{displayedObjects.map((objectMetadataItem) => (
<Dropdown.OptionItem
key={objectMetadataItem.id}
diff --git a/packages/twenty-front/src/modules/side-panel/components/__stories__/SidePanelObjectFilterDropdown.stories.tsx b/packages/twenty-front/src/modules/side-panel/components/__stories__/SidePanelObjectFilterDropdown.stories.tsx
index 281217bb4d6..4013372e089 100644
--- a/packages/twenty-front/src/modules/side-panel/components/__stories__/SidePanelObjectFilterDropdown.stories.tsx
+++ b/packages/twenty-front/src/modules/side-panel/components/__stories__/SidePanelObjectFilterDropdown.stories.tsx
@@ -39,21 +39,31 @@ export const SearchAndHiddenObjects: Story = {
within(popup).getByRole('searchbox', { name: 'Search' }),
'compan',
);
- await userEvent.click(
- await within(popup).findByRole('button', { name: 'Companies' }),
- );
+ const companies = await within(popup).findByRole('button', {
+ name: 'Companies',
+ });
+ expect(
+ within(popup).queryByRole('button', { name: 'All objects' }),
+ ).not.toBeInTheDocument();
+ await waitFor(() => expect(companies).toHaveAttribute('data-highlighted'));
+ await userEvent.keyboard('{Enter}');
await waitFor(() => expect(popup).not.toBeInTheDocument());
await userEvent.click(trigger);
const reopened = await body.findByRole('dialog');
- expect(
- within(reopened).getByRole('searchbox', { name: 'Search' }),
- ).toHaveValue('');
+ const reopenedSearch = within(reopened).getByRole('searchbox', {
+ name: 'Search',
+ });
+ expect(reopenedSearch).toHaveValue('');
expect(
within(reopened).getByRole('button', { name: 'Companies' }),
).toHaveAttribute('aria-pressed', 'true');
- await userEvent.click(
- within(reopened).getByRole('button', { name: 'All objects' }),
+ await userEvent.type(reopenedSearch, 'all');
+ await waitFor(() =>
+ expect(
+ within(reopened).getByRole('button', { name: 'All objects' }),
+ ).toHaveAttribute('data-highlighted'),
);
+ await userEvent.keyboard('{Enter}');
await waitFor(() => expect(reopened).not.toBeInTheDocument());
},
};
diff --git a/packages/twenty-front/src/modules/ui/input/components/Select.tsx b/packages/twenty-front/src/modules/ui/input/components/Select.tsx
index 7cdf364e43d..b1af61a1351 100644
--- a/packages/twenty-front/src/modules/ui/input/components/Select.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/Select.tsx
@@ -10,6 +10,7 @@ import { Dropdown } from 'twenty-ui/components';
import { Tag } from 'twenty-ui/primitives/data-display';
import { type SelectValue } from '@/ui/input/components/internal/select/types';
+import { isSelectOptionMatchingSearch } from '@/ui/input/components/internal/select/utils/isSelectOptionMatchingSearch';
import { SelectControl } from '@/ui/input/components/SelectControl';
import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
@@ -88,20 +89,15 @@ export const Select = <TValue extends SelectValue>({
return null;
}, [emptyOption, options, pinnedOption, value]);
- const filteredOptions = useMemo(() => {
- if (!isNonEmptyString(searchInputValue)) {
- return options;
- }
-
- const normalizedSearch = normalizeSearchText(searchInputValue);
+ const normalizedSearchInputValue = normalizeSearchText(searchInputValue);
- return options.filter(
- ({ label, searchKeywords }) =>
- normalizeSearchText(label).includes(normalizedSearch) ||
- (isDefined(searchKeywords) &&
- normalizeSearchText(searchKeywords).includes(normalizedSearch)),
- );
- }, [options, searchInputValue]);
+ const filteredOptions = useMemo(
+ () =>
+ options.filter((option) =>
+ isSelectOptionMatchingSearch({ option, normalizedSearchInputValue }),
+ ),
+ [options, normalizedSearchInputValue],
+ );
const isDisabled =
disabledFromProps ||
@@ -110,6 +106,13 @@ export const Select = <TValue extends SelectValue>({
!isDefined(callToActionButton) &&
(!isDefined(emptyOption) || selectedOption !== emptyOption));
+ const shouldShowPinnedOption =
+ isDefined(pinnedOption) &&
+ isSelectOptionMatchingSearch({
+ option: pinnedOption,
+ normalizedSearchInputValue,
+ });
+
const dropDownMenuWidth =
dropdownWidthAuto && selectContainerRef.current?.clientWidth
? selectContainerRef.current?.clientWidth
@@ -137,7 +140,6 @@ export const Select = <TValue extends SelectValue>({
<StyledContainer
className={className}
fullWidth={fullWidth}
- tabIndex={0}
onBlur={(event) => {
const nextFocus = event.relatedTarget;
const isFocusWithinSelect =
@@ -193,6 +195,7 @@ export const Select = <TValue extends SelectValue>({
align="start"
sideOffset={dropdownOffset?.y ?? 0}
alignOffset={dropdownOffset?.x ?? 0}
+ aria-label={isNonEmptyString(label) ? label : undefined}
>
{withSearchInput === true && (
<Dropdown.Search
@@ -205,7 +208,7 @@ export const Select = <TValue extends SelectValue>({
{withSearchInput === true && isNonEmptyArray(filteredOptions) && (
<Dropdown.Separator />
)}
- {isDefined(pinnedOption) && (
+ {shouldShowPinnedOption && (
<Dropdown.Section>
<Dropdown.OptionItem
onSelect={() => {
@@ -230,7 +233,7 @@ export const Select = <TValue extends SelectValue>({
</Dropdown.OptionItem>
</Dropdown.Section>
)}
- {isDefined(pinnedOption) && isNonEmptyArray(filteredOptions) && (
+ {shouldShowPinnedOption && isNonEmptyArray(filteredOptions) && (
<Dropdown.Separator />
)}
{isNonEmptyArray(filteredOptions) && (
diff --git a/packages/twenty-front/src/modules/ui/input/components/__stories__/OptionPickers.stories.tsx b/packages/twenty-front/src/modules/ui/input/components/__stories__/OptionPickers.stories.tsx
index 705a0549dd1..53ed39bba7e 100644
--- a/packages/twenty-front/src/modules/ui/input/components/__stories__/OptionPickers.stories.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/__stories__/OptionPickers.stories.tsx
@@ -76,8 +76,10 @@ export const CurrencySearchAndKeyboard: Story = {
await userEvent.clear(search);
await userEvent.type(search, 'euro');
const euro = await body.findByRole('button', { name: /Euro \(EUR\)/ });
- await userEvent.keyboard('{ArrowDown}{ArrowDown}');
- await expect(euro).toHaveFocus();
+ expect(
+ body.queryByRole('button', { pressed: true }),
+ ).not.toBeInTheDocument();
+ await waitFor(() => expect(euro).toHaveAttribute('data-highlighted'));
await userEvent.keyboard('{Enter}');
await waitFor(() =>
expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
@@ -102,9 +104,14 @@ export const PhoneSearchAndSelection: Story = {
await body.findByRole('searchbox', { name: 'Search' }),
'france',
);
- await userEvent.click(
- await body.findByRole('button', { name: /France \(\+33\)/ }),
- );
+ const france = await body.findByRole('button', {
+ name: /France \(\+33\)/,
+ });
+ expect(
+ body.queryByRole('button', { pressed: true }),
+ ).not.toBeInTheDocument();
+ await waitFor(() => expect(france).toHaveAttribute('data-highlighted'));
+ await userEvent.keyboard('{Enter}');
await waitFor(() =>
expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
);
diff --git a/packages/twenty-front/src/modules/ui/input/components/__stories__/Select.stories.tsx b/packages/twenty-front/src/modules/ui/input/components/__stories__/Select.stories.tsx
index b2b63292340..b00ac24f0c2 100644
--- a/packages/twenty-front/src/modules/ui/input/components/__stories__/Select.stories.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/__stories__/Select.stories.tsx
@@ -138,11 +138,26 @@ export const SearchWithPinnedDisabledAndAction: Story = {
expect(args.callToActionButton?.onClick).toHaveBeenCalledTimes(1);
expect(popup).toBeVisible();
const search = within(popup).getByRole('searchbox', { name: 'Search' });
+ await userEvent.type(search, 'default');
+ await waitFor(() =>
+ expect(
+ within(popup).getByRole('button', { name: 'Use default' }),
+ ).toHaveAttribute('data-highlighted'),
+ );
+ await userEvent.clear(search);
await userEvent.type(search, 'pastry');
expect(
within(popup).queryByRole('button', { name: 'Option C' }),
).not.toBeInTheDocument();
- await userEvent.keyboard('{ArrowDown}{ArrowDown}{Enter}');
+ expect(
+ within(popup).queryByRole('button', { name: 'Use default' }),
+ ).not.toBeInTheDocument();
+ await waitFor(() =>
+ expect(
+ within(popup).getByRole('button', { name: 'Éclair' }),
+ ).toHaveAttribute('data-highlighted'),
+ );
+ await userEvent.keyboard('{Enter}');
expect(args.onChange).toHaveBeenCalledWith('a');
await waitFor(() => expect(popup).not.toBeInTheDocument());
await waitFor(() => expect(trigger).toHaveFocus());
@@ -172,6 +187,20 @@ export const KeyboardStartsAtSelection: Story = {
},
};
+export const SingleTabStopAndLabelledPopup: Story = {
+ args: { label: 'Status' },
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button');
+ await userEvent.tab();
+ await expect(trigger).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ const body = within(canvasElement.ownerDocument.body);
+ await expect(
+ await body.findByRole('dialog', { name: 'Status' }),
+ ).toBeVisible();
+ },
+};
+
const onParentClick = fn();
const onParentClickOutside = fn();
const onExcludedClickOutside = fn();
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/currency/components/CurrencyPickerDropdownSelect.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/currency/components/CurrencyPickerDropdownSelect.tsx
index eead936cd28..4fcf25e0cc7 100644
--- a/packages/twenty-front/src/modules/ui/input/components/internal/currency/components/CurrencyPickerDropdownSelect.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/currency/components/CurrencyPickerDropdownSelect.tsx
@@ -27,6 +27,10 @@ export const CurrencyPickerDropdownSelect = ({
[searchFilter],
);
+ const isSelectedCurrencyMatchingSearch =
+ isDefined(selectedCurrency) &&
+ filteredCurrencies.some(({ value }) => value === selectedCurrency.value);
+
return (
<>
<Dropdown.Search
@@ -41,7 +45,7 @@ export const CurrencyPickerDropdownSelect = ({
<Dropdown.Empty>{t`No results`}</Dropdown.Empty>
) : (
<>
- {isDefined(selectedCurrency) && (
+ {isSelectedCurrencyMatchingSearch && (
<Dropdown.OptionItem
key={selectedCurrency.value}
onSelect={() => onChange(selectedCurrency)}
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownSelect.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownSelect.tsx
index 16db54bec0c..ac741b86d87 100644
--- a/packages/twenty-front/src/modules/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownSelect.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownSelect.tsx
@@ -44,6 +44,12 @@ export const PhoneCountryPickerDropdownSelect = ({
[countries, searchFilter],
);
+ const isSelectedCountryMatchingSearch =
+ isDefined(selectedCountry) &&
+ filteredCountries.some(
+ ({ countryCode }) => countryCode === selectedCountry.countryCode,
+ );
+
return (
<>
<Dropdown.Search
@@ -58,7 +64,7 @@ export const PhoneCountryPickerDropdownSelect = ({
<Dropdown.Empty>{t`No results`}</Dropdown.Empty>
) : (
<>
- {isDefined(selectedCountry) && (
+ {isSelectedCountryMatchingSearch && (
<Dropdown.OptionItem
key={selectedCountry.countryCode}
onSelect={() => onChange(selectedCountry.countryCode)}
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/select/utils/isSelectOptionMatchingSearch.ts b/packages/twenty-front/src/modules/ui/input/components/internal/select/utils/isSelectOptionMatchingSearch.ts
new file mode 100644
index 00000000000..6890187028b
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/select/utils/isSelectOptionMatchingSearch.ts
@@ -0,0 +1,22 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+import { type SelectOption } from 'twenty-ui/primitives/input';
+import { normalizeSearchText } from '~/utils/normalizeSearchText';
+
+export const isSelectOptionMatchingSearch = ({
+ option: { label, searchKeywords },
+ normalizedSearchInputValue,
+}: {
+ option: Pick<SelectOption, 'label' | 'searchKeywords'>;
+ normalizedSearchInputValue: string;
+}) => {
+ if (!isNonEmptyString(normalizedSearchInputValue)) {
+ return true;
+ }
+
+ return (
+ normalizeSearchText(label).includes(normalizedSearchInputValue) ||
+ (isDefined(searchKeywords) &&
+ normalizeSearchText(searchKeywords).includes(normalizedSearchInputValue))
+ );
+};
diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx
index b3a5b42e2f8..4f75c27fb96 100644
--- a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx
@@ -19,6 +19,8 @@ type DropdownContentProps = Pick<
| 'alignOffset'
| 'width'
| 'initialFocus'
+ | 'finalFocus'
+ | 'className'
| 'aria-label'
| 'ref'
>;
@@ -31,6 +33,8 @@ export const DropdownContent = ({
alignOffset,
width,
initialFocus,
+ finalFocus,
+ className,
'aria-label': ariaLabel,
ref,
}: DropdownContentProps) => {
@@ -47,6 +51,8 @@ export const DropdownContent = ({
alignOffset={alignOffset}
width={width}
initialFocus={initialFocus}
+ finalFocus={finalFocus}
+ className={className}
aria-label={ariaLabel}
>
{isDefined(excludedClickOutsideId) ? (
diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/StyledHeaderDropdownButton.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/StyledHeaderDropdownButton.tsx
index 2c59def4817..1d66a42eb06 100644
--- a/packages/twenty-front/src/modules/ui/layout/dropdown/components/StyledHeaderDropdownButton.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/StyledHeaderDropdownButton.tsx
@@ -3,7 +3,6 @@ import { styled } from '@linaria/react';
type StyledDropdownButtonProps = {
isUnfolded?: boolean;
- isActive?: boolean;
};
export const StyledHeaderDropdownButton = styled.button<StyledDropdownButtonProps>`
@@ -14,10 +13,7 @@ export const StyledHeaderDropdownButton = styled.button<StyledDropdownButtonProp
: themeCssVariables.background.primary};
border: none;
border-radius: ${themeCssVariables.border.radius.md};
- color: ${({ isActive }) =>
- isActive
- ? themeCssVariables.color.blue
- : themeCssVariables.font.color.secondary};
+ color: ${themeCssVariables.font.color.secondary};
cursor: pointer;
display: flex;
diff --git a/packages/twenty-front/src/modules/views/components/UpdateViewButtonGroup.tsx b/packages/twenty-front/src/modules/views/components/UpdateViewButtonGroup.tsx
index 29e7a83c80c..0675cd25976 100644
--- a/packages/twenty-front/src/modules/views/components/UpdateViewButtonGroup.tsx
+++ b/packages/twenty-front/src/modules/views/components/UpdateViewButtonGroup.tsx
@@ -1,11 +1,10 @@
-import { ListItem } from 'twenty-ui/primitives/navigation';
import { styled } from '@linaria/react';
import { contextStoreCurrentViewIdComponentState } from '@/context-store/states/contextStoreCurrentViewIdComponentState';
-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';
-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
-import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
+import { Dropdown, IconButton } from 'twenty-ui/components';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
+import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';
import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
@@ -23,9 +22,9 @@ import { getViewPickerDropdownId } from '@/views/view-picker/utils/getViewPicker
import { useViewPickerMode } from '@/views/view-picker/hooks/useViewPickerMode';
import { viewPickerReferenceViewIdComponentState } from '@/views/view-picker/states/viewPickerReferenceViewIdComponentState';
import { t } from '@lingui/core/macro';
+import { isDefined } from 'twenty-shared/utils';
import { IconChevronDown, IconPlus } from 'twenty-ui/icon';
import { Button, ButtonGroup } from 'twenty-ui/primitives/input';
-import { IconButton } from 'twenty-ui/components';
import { themeCssVariables } from 'twenty-ui/theme';
const StyledContainer = styled.div`
@@ -45,18 +44,21 @@ export const UpdateViewButtonGroup = () => {
contextStoreCurrentViewIdComponentState,
);
- const { closeDropdown: closeUpdateViewButtonDropdown } = useCloseDropdown();
const { recordIndexId } = useRecordIndexContextOrThrow();
const updateViewButtonDropdownId = `${UPDATE_VIEW_BUTTON_DROPDOWN_ID}-${recordIndexId}`;
const { openDropdown: openViewPickerDropdown } = useOpenDropdown();
const { currentView } = useGetCurrentViewOnly();
+ const isDropdownOpen = useAtomComponentStateValue(
+ isDropdownOpenComponentState,
+ getViewPickerDropdownId(recordIndexId),
+ );
const setViewPickerReferenceViewId = useSetAtomComponentState(
viewPickerReferenceViewIdComponentState,
);
const openViewPickerInCreateMode = () => {
- if (!contextStoreCurrentViewId) {
+ if (!isDefined(contextStoreCurrentViewId)) {
return;
}
@@ -66,8 +68,6 @@ export const UpdateViewButtonGroup = () => {
});
setViewPickerReferenceViewId(contextStoreCurrentViewId);
setViewPickerMode('create-from-current');
-
- closeUpdateViewButtonDropdown(updateViewButtonDropdownId);
};
const handleCreateViewClick = () => {
@@ -116,24 +116,23 @@ export const UpdateViewButtonGroup = () => {
onClick={handleUpdateViewClick}
disabled={!canPersistChanges}
>{t`Update view`}</Button>
- <Dropdown
- dropdownId={updateViewButtonDropdownId}
- clickableComponent={
- <IconButton aria-label={t`View update options`}>
- <IconChevronDown />
- </IconButton>
- }
- dropdownComponents={
- <LegacyDropdownContent>
- <DropdownMenuItemsContainer>
- <ListItem
- onClick={handleCreateViewClick}
- startIcon={<IconPlus />}
- >{t`Create view`}</ListItem>
- </DropdownMenuItemsContainer>
- </LegacyDropdownContent>
- }
- />
+ <DropdownRoot dropdownId={updateViewButtonDropdownId} type="menu">
+ <Dropdown.Trigger
+ render={
+ <IconButton aria-label={t`View update options`}>
+ <IconChevronDown />
+ </IconButton>
+ }
+ />
+ <DropdownContent align="end" finalFocus={() => !isDropdownOpen}>
+ <Dropdown.Section>
+ <Dropdown.ActionItem
+ onClick={handleCreateViewClick}
+ startIcon={<IconPlus />}
+ >{t`Create view`}</Dropdown.ActionItem>
+ </Dropdown.Section>
+ </DropdownContent>
+ </DropdownRoot>
</ButtonGroup>
) : (
<Button
diff --git a/packages/twenty-front/src/modules/views/components/__stories__/UpdateViewButtonGroup.stories.tsx b/packages/twenty-front/src/modules/views/components/__stories__/UpdateViewButtonGroup.stories.tsx
new file mode 100644
index 00000000000..1939b34ff14
--- /dev/null
+++ b/packages/twenty-front/src/modules/views/components/__stories__/UpdateViewButtonGroup.stories.tsx
@@ -0,0 +1,80 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { graphql, HttpResponse } from 'msw';
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+import { ContextStoreDecorator } from '~/testing/decorators/ContextStoreDecorator';
+import { IconsProviderDecorator } from '~/testing/decorators/IconsProviderDecorator';
+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
+import { SortViewDecorator } from '~/testing/decorators/SortViewDecorator';
+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';
+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
+import { UpdateViewButtonGroup } from '@/views/components/UpdateViewButtonGroup';
+import { graphqlMocks } from '~/testing/graphqlMocks';
+import { ViewPickerDropdown } from '@/views/view-picker/components/ViewPickerDropdown';
+
+const meta: Meta<typeof UpdateViewButtonGroup> = {
+ title: 'Modules/Views/UpdateViewButtonGroup',
+ component: UpdateViewButtonGroup,
+ parameters: {
+ msw: {
+ handlers: [
+ ...graphqlMocks.handlers,
+ graphql.query('AggregateCompanies', () =>
+ HttpResponse.json({ data: { companies: { totalCount: 1 } } }),
+ ),
+ ],
+ },
+ },
+ decorators: [
+ SortViewDecorator,
+ ContextStoreDecorator,
+ ObjectMetadataItemsDecorator,
+ ToastDecorator,
+ ComponentDecorator,
+ IconsProviderDecorator,
+ MemoryRouterDecorator,
+ ],
+ render: () => (
+ <>
+ <ViewPickerDropdown />
+ <UpdateViewButtonGroup />
+ </>
+ ),
+};
+export default meta;
+type Story = StoryObj<typeof UpdateViewButtonGroup>;
+
+export const CreateView: Story = {
+ parameters: { hasSortChanges: true },
+ play: async ({ canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ await within(canvasElement).findByRole('button', {
+ name: 'View update options',
+ }),
+ );
+ await userEvent.click(
+ await body.findByRole('menuitem', { name: 'Create view' }),
+ );
+ await waitFor(() =>
+ expect(body.queryByRole('menu')).not.toBeInTheDocument(),
+ );
+ const name = await body.findByRole('textbox');
+ await waitFor(() => expect(name).toHaveFocus());
+ await expect(body.getByText('Create view')).toBeVisible();
+ },
+};
+
+export const UnchangedView: Story = {
+ play: async ({ canvasElement }) => {
+ await within(canvasElement).findByText('All Companies');
+ await expect(
+ within(canvasElement).queryByRole('button', {
+ name: 'View update options',
+ }),
+ ).not.toBeInTheDocument();
+ await expect(
+ within(canvasElement).queryByRole('button', { name: 'Update view' }),
+ ).not.toBeInTheDocument();
+ },
+};
diff --git a/packages/twenty-front/src/modules/views/editable-chip/components/EditableSortChip.tsx b/packages/twenty-front/src/modules/views/editable-chip/components/EditableSortChip.tsx
index 1e8d1bcc736..7dca8c39d9c 100644
--- a/packages/twenty-front/src/modules/views/editable-chip/components/EditableSortChip.tsx
+++ b/packages/twenty-front/src/modules/views/editable-chip/components/EditableSortChip.tsx
@@ -4,16 +4,13 @@ import { useSortSubFieldChoicesForField } from '@/object-metadata/hooks/useSortS
import { useRemoveRecordSort } from '@/object-record/record-sort/hooks/useRemoveRecordSort';
import { useUpsertRecordSort } from '@/object-record/record-sort/hooks/useUpsertRecordSort';
import { type RecordSort } from '@/object-record/record-sort/types/RecordSort';
-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';
-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
-import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';
-import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
+import { Dropdown } from 'twenty-ui/components';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
import { SortOrFilterChip } from '@/views/components/SortOrFilterChip';
import { useLingui } from '@lingui/react/macro';
import { isDefined } from 'twenty-shared/utils';
import { IconArrowDown, IconArrowUp } from 'twenty-ui/icon';
-import { ListItem } from 'twenty-ui/primitives/navigation';
import { ViewSortDirection } from '~/generated-metadata/graphql';
type EditableSortChipProps = {
@@ -24,7 +21,6 @@ export const EditableSortChip = ({ recordSort }: EditableSortChipProps) => {
const { t } = useLingui();
const { removeRecordSort } = useRemoveRecordSort();
const { upsertRecordSort } = useUpsertRecordSort();
- const { closeDropdown } = useCloseDropdown();
const { fieldMetadataItem } = useFieldMetadataItemByIdOrThrow(
recordSort.fieldMetadataId,
@@ -55,12 +51,6 @@ export const EditableSortChip = ({ recordSort }: EditableSortChipProps) => {
const handleSubFieldSelect = (value: string) => {
upsertRecordSort({ ...recordSort, subFieldName: value });
- closeDropdown(dropdownId);
- };
-
- const handleDirectionSelect = (direction: ViewSortDirection) => {
- setDirection(direction);
- closeDropdown(dropdownId);
};
const Icon =
@@ -83,9 +73,8 @@ export const EditableSortChip = ({ recordSort }: EditableSortChipProps) => {
}
return (
- <Dropdown
- dropdownId={dropdownId}
- clickableComponent={
+ <DropdownRoot dropdownId={dropdownId} type="picker">
+ <Dropdown.Trigger render={<div />} nativeButton={false}>
<SortOrFilterChip
key={recordSort.fieldMetadataId}
testId={recordSort.fieldMetadataId}
@@ -95,46 +84,33 @@ export const EditableSortChip = ({ recordSort }: EditableSortChipProps) => {
onRemove={handleRemove}
type="sort"
/>
- }
- dropdownComponents={
- <LegacyDropdownContent>
- <DropdownMenuItemsContainer>
- <ListItem
- onClick={() => handleDirectionSelect(ViewSortDirection.ASC)}
- role="option"
- aria-selected={recordSort.direction === ViewSortDirection.ASC}
- selected={recordSort.direction === ViewSortDirection.ASC}
- indicator="check"
- startIcon={<SelectOptionIcon Icon={IconArrowUp} />}
- >{t`Ascending`}</ListItem>
- <ListItem
- onClick={() => handleDirectionSelect(ViewSortDirection.DESC)}
- role="option"
- aria-selected={recordSort.direction === ViewSortDirection.DESC}
- selected={recordSort.direction === ViewSortDirection.DESC}
- indicator="check"
- startIcon={<SelectOptionIcon Icon={IconArrowDown} />}
- >{t`Descending`}</ListItem>
- </DropdownMenuItemsContainer>
- <DropdownMenuSeparator />
- <DropdownMenuItemsContainer>
- {subFieldChoices.options.map((option) => (
- <ListItem
- key={option.value}
- onClick={() => handleSubFieldSelect(option.value)}
- role="option"
- aria-selected={option.value === subFieldChoices.selectedValue}
- selected={option.value === subFieldChoices.selectedValue}
- indicator="check"
- >
- {option.label}
- </ListItem>
- ))}
- </DropdownMenuItemsContainer>
- </LegacyDropdownContent>
- }
- dropdownOffset={{ y: 8, x: 0 }}
- dropdownPlacement="bottom-start"
- />
+ </Dropdown.Trigger>
+ <DropdownContent sideOffset={8}>
+ <Dropdown.Section>
+ <Dropdown.OptionItem
+ onSelect={() => setDirection(ViewSortDirection.ASC)}
+ selected={recordSort.direction === ViewSortDirection.ASC}
+ startIcon={<SelectOptionIcon Icon={IconArrowUp} />}
+ >{t`Ascending`}</Dropdown.OptionItem>
+ <Dropdown.OptionItem
+ onSelect={() => setDirection(ViewSortDirection.DESC)}
+ selected={recordSort.direction === ViewSortDirection.DESC}
+ startIcon={<SelectOptionIcon Icon={IconArrowDown} />}
+ >{t`Descending`}</Dropdown.OptionItem>
+ </Dropdown.Section>
+ <Dropdown.Separator />
+ <Dropdown.Section>
+ {subFieldChoices.options.map((option) => (
+ <Dropdown.OptionItem
+ key={option.value}
+ onSelect={() => handleSubFieldSelect(option.value)}
+ selected={option.value === subFieldChoices.selectedValue}
+ >
+ {option.label}
+ </Dropdown.OptionItem>
+ ))}
+ </Dropdown.Section>
+ </DropdownContent>
+ </DropdownRoot>
);
};
diff --git a/packages/twenty-front/src/modules/views/editable-chip/components/__stories__/EditableSortChip.stories.tsx b/packages/twenty-front/src/modules/views/editable-chip/components/__stories__/EditableSortChip.stories.tsx
new file mode 100644
index 00000000000..395da5e013b
--- /dev/null
+++ b/packages/twenty-front/src/modules/views/editable-chip/components/__stories__/EditableSortChip.stories.tsx
@@ -0,0 +1,97 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+import { ContextStoreDecorator } from '~/testing/decorators/ContextStoreDecorator';
+import { IconsProviderDecorator } from '~/testing/decorators/IconsProviderDecorator';
+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
+import { SortViewDecorator } from '~/testing/decorators/SortViewDecorator';
+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';
+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
+import { useEffect } from 'react';
+import { EditableSortChip } from '@/views/editable-chip/components/EditableSortChip';
+import { currentRecordSortsComponentState } from '@/object-record/record-sort/states/currentRecordSortsComponentState';
+import { useAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentState';
+import { ViewSortDirection } from '~/generated-metadata/graphql';
+import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
+
+const SortChipExample = ({ fieldName = 'address' }: { fieldName?: string }) => {
+ const [sorts, setSorts] = useAtomComponentState(
+ currentRecordSortsComponentState,
+ );
+ const field = getMockObjectMetadataItemOrThrow('company').fields.find(
+ (field) => field.name === fieldName,
+ )!;
+ useEffect(() => {
+ setSorts([
+ {
+ id: 'chip-story',
+ fieldMetadataId: field.id,
+ direction: ViewSortDirection.ASC,
+ },
+ ]);
+ }, [setSorts, field.id]);
+ return (
+ <>
+ {sorts.map((sort) => (
+ <EditableSortChip key={sort.id} recordSort={sort} />
+ ))}
+ </>
+ );
+};
+
+const meta: Meta<typeof SortChipExample> = {
+ title: 'Modules/Views/EditableSortChip',
+ component: SortChipExample,
+ decorators: [
+ SortViewDecorator,
+ ContextStoreDecorator,
+ ObjectMetadataItemsDecorator,
+ ToastDecorator,
+ ComponentDecorator,
+ IconsProviderDecorator,
+ MemoryRouterDecorator,
+ ],
+};
+export default meta;
+type Story = StoryObj<typeof SortChipExample>;
+
+export const CompositeField: Story = {
+ play: async ({ canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ const canvas = within(canvasElement);
+ const trigger = await canvas.findByRole('button', { name: /Address/ });
+ await userEvent.click(trigger);
+ await expect(
+ await body.findByRole('button', { name: 'Ascending' }),
+ ).toHaveAttribute('aria-pressed', 'true');
+ await userEvent.click(body.getByRole('button', { name: 'Descending' }));
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ await userEvent.click(trigger);
+ await expect(
+ await body.findByRole('button', { name: 'Descending' }),
+ ).toHaveAttribute('aria-pressed', 'true');
+ await userEvent.click(body.getByRole('button', { name: 'City' }));
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ await expect(trigger).toHaveTextContent('City');
+ await userEvent.click(canvas.getByTestId(/^remove-icon-/));
+ await expect(body.queryByRole('dialog')).not.toBeInTheDocument();
+ await expect(canvas.queryByText('Address')).not.toBeInTheDocument();
+ },
+};
+
+export const SimpleField: Story = {
+ args: { fieldName: 'name' },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(await canvas.findByText('Name'));
+ await expect(
+ within(canvasElement.ownerDocument.body).queryByRole('dialog'),
+ ).not.toBeInTheDocument();
+ await userEvent.click(canvas.getByTestId(/^remove-icon-/));
+ await expect(canvas.queryByText('Name')).not.toBeInTheDocument();
+ },
+};
diff --git a/packages/twenty-front/src/testing/decorators/SortViewDecorator.tsx b/packages/twenty-front/src/testing/decorators/SortViewDecorator.tsx
new file mode 100644
index 00000000000..001daf0ae6f
--- /dev/null
+++ b/packages/twenty-front/src/testing/decorators/SortViewDecorator.tsx
@@ -0,0 +1,105 @@
+import { type Decorator } from '@storybook/react-vite';
+import { useStore } from 'jotai';
+import { useEffect, useState } from 'react';
+
+import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';
+import { contextStoreCurrentViewIdComponentState } from '@/context-store/states/contextStoreCurrentViewIdComponentState';
+import { RecordComponentInstanceContextsWrapper } from '@/object-record/components/RecordComponentInstanceContextsWrapper';
+import { ObjectSortDropdownComponentInstanceContext } from '@/object-record/object-sort-dropdown/states/context/ObjectSortDropdownComponentInstanceContext';
+import { currentRecordFieldsComponentState } from '@/object-record/record-field/states/currentRecordFieldsComponentState';
+import { currentRecordSortsComponentState } from '@/object-record/record-sort/states/currentRecordSortsComponentState';
+import { RecordIndexContextProvider } from '@/object-record/record-index/contexts/RecordIndexContext';
+import { useRecordIndexFieldMetadataDerivedStates } from '@/object-record/record-index/hooks/useRecordIndexFieldMetadataDerivedStates';
+import { ViewComponentInstanceContext } from '@/views/states/contexts/ViewComponentInstanceContext';
+import { viewObjectMetadataIdComponentState } from '@/views/states/viewObjectMetadataIdComponentState';
+import { ViewSortDirection } from '~/generated-metadata/graphql';
+import { mockedViews } from '~/testing/mock-data/generated/metadata/views/mock-views-data';
+import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
+import { setTestViewsInMetadataStore } from '~/testing/utils/setTestViewsInMetadataStore';
+
+const INSTANCE_ID = 'sort-view-story';
+
+export const SortViewDecorator: Decorator = (Story, { parameters }) => {
+ const store = useStore();
+ const objectMetadataItem = getMockObjectMetadataItemOrThrow('company');
+ const [loaded, setLoaded] = useState(false);
+ const hasChanges = parameters.hasSortChanges === true;
+ const derivedStates = useRecordIndexFieldMetadataDerivedStates(
+ objectMetadataItem,
+ INSTANCE_ID,
+ );
+
+ useEffect(() => {
+ const view = {
+ ...mockedViews.find((view) => view.name === 'All Companies')!,
+ key: null,
+ viewSorts: [],
+ };
+ setTestViewsInMetadataStore(store, [view]);
+ store.set(
+ contextStoreCurrentViewIdComponentState.atomFamily({
+ instanceId: MAIN_CONTEXT_STORE_INSTANCE_ID,
+ }),
+ view.id,
+ );
+ store.set(
+ viewObjectMetadataIdComponentState.atomFamily({
+ instanceId: INSTANCE_ID,
+ }),
+ objectMetadataItem.id,
+ );
+ store.set(
+ currentRecordFieldsComponentState.atomFamily({ instanceId: INSTANCE_ID }),
+ objectMetadataItem.fields.map((field, position) => ({
+ id: field.id,
+ fieldMetadataItemId: field.id,
+ isVisible: field.name === 'name',
+ position,
+ size: 100,
+ })),
+ );
+ store.set(
+ currentRecordSortsComponentState.atomFamily({ instanceId: INSTANCE_ID }),
+ hasChanges
+ ? [
+ {
+ id: 'sort-story',
+ fieldMetadataId: objectMetadataItem.fields.find(
+ (field) => field.name === 'name',
+ )!.id,
+ direction: ViewSortDirection.ASC,
+ },
+ ]
+ : [],
+ );
+ setLoaded(true);
+ }, [store, objectMetadataItem, hasChanges]);
+
+ return (
+ <RecordIndexContextProvider
+ value={{
+ ...derivedStates,
+ objectPermissionsByObjectMetadataId: {},
+ indexIdentifierUrl: () => '',
+ onIndexRecordsLoaded: () => {},
+ objectNamePlural: objectMetadataItem.namePlural,
+ objectNameSingular: objectMetadataItem.nameSingular,
+ objectMetadataItem,
+ recordIndexId: INSTANCE_ID,
+ viewBarInstanceId: INSTANCE_ID,
+ }}
+ >
+ <RecordComponentInstanceContextsWrapper componentInstanceId={INSTANCE_ID}>
+ <ViewComponentInstanceContext.Provider
+ value={{ instanceId: INSTANCE_ID }}
+ >
+ <ObjectSortDropdownComponentInstanceContext.Provider
+ value={{ instanceId: INSTANCE_ID }}
+ >
+ {loaded && <Story />}
+ </ObjectSortDropdownComponentInstanceContext.Provider>
+ </ViewComponentInstanceContext.Provider>
+ </RecordComponentInstanceContextsWrapper>
+ </RecordIndexContextProvider>
+ );
+};
diff --git a/packages/twenty-ui/docs/components.ts b/packages/twenty-ui/docs/components.ts
index 95ac26298e5..ffb159d13a4 100644
--- a/packages/twenty-ui/docs/components.ts
+++ b/packages/twenty-ui/docs/components.ts
@@ -245,6 +245,9 @@ export const DOCUMENTED_COMPONENTS = [
'ActionItem',
'OptionItem',
'Search',
+ 'Header',
+ 'Title',
+ 'Close',
'Page',
'Back',
'Submenu',
diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.json
index 56fe0366933..fffabb10b1a 100644
--- a/packages/twenty-ui/generated/components.docs.json
+++ b/packages/twenty-ui/generated/components.docs.json
@@ -6395,6 +6395,84 @@
}
]
},
+ {
+ "name": "Header",
+ "props": [
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."
+ }
+ ]
+ },
+ {
+ "name": "Title",
+ "props": [
+ {
+ "name": "className",
+ "type": "string | ((state: PopoverTitleState) => string | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, PopoverTitleState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."
+ },
+ {
+ "name": "style",
+ "type": "CSSProperties | ((state: PopoverTitleState) => CSSProperties | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."
+ }
+ ]
+ },
+ {
+ "name": "Close",
+ "props": [
+ {
+ "name": "aria-label",
+ "type": "string",
+ "required": true,
+ "defaultValue": null,
+ "description": ""
+ },
+ {
+ "name": "className",
+ "type": "string | ((state: PopoverCloseState) => string | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."
+ },
+ {
+ "name": "nativeButton",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "true",
+ "description": "Whether the component renders a native `<button>` element when replacing it\nvia the `render` prop.\nSet to `false` if the rendered element is not a button (for example, `<div>`)."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, PopoverCloseState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."
+ },
+ {
+ "name": "style",
+ "type": "CSSProperties | ((state: PopoverCloseState) => CSSProperties | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."
+ }
+ ]
+ },
{
"name": "Page",
"props": [
diff --git a/packages/twenty-ui/src/components/index.ts b/packages/twenty-ui/src/components/index.ts
index b6f7b51cef4..2a513041d2d 100644
--- a/packages/twenty-ui/src/components/index.ts
+++ b/packages/twenty-ui/src/components/index.ts
@@ -72,7 +72,9 @@ export type { SectionHeaderProps } from './layout/Section/types/SectionHeaderPro
export type { SectionRootProps } from './layout/Section/types/SectionRootProps';
export { Dropdown } from './navigation/Dropdown/Dropdown';
export type { DropdownActionItemProps } from './navigation/Dropdown/types/DropdownActionItemProps';
+export type { DropdownCloseProps } from './navigation/Dropdown/types/DropdownCloseProps';
export type { DropdownContentProps } from './navigation/Dropdown/types/DropdownContentProps';
+export type { DropdownHeaderProps } from './navigation/Dropdown/types/DropdownHeaderProps';
export type { DropdownOptionItemProps } from './navigation/Dropdown/types/DropdownOptionItemProps';
export type { DropdownPageProps } from './navigation/Dropdown/types/DropdownPageProps';
export type { DropdownRootProps } from './navigation/Dropdown/types/DropdownRootProps';
@@ -80,6 +82,7 @@ export type { DropdownSearchProps } from './navigation/Dropdown/types/DropdownSe
export type { DropdownSectionProps } from './navigation/Dropdown/types/DropdownSectionProps';
export type { DropdownSubmenuProps } from './navigation/Dropdown/types/DropdownSubmenuProps';
export type { DropdownSubmenuTriggerProps } from './navigation/Dropdown/types/DropdownSubmenuTriggerProps';
+export type { DropdownTitleProps } from './navigation/Dropdown/types/DropdownTitleProps';
export type { DropdownTriggerProps } from './navigation/Dropdown/types/DropdownTriggerProps';
export type { DropdownType } from './navigation/Dropdown/types/DropdownType';
export { DEFAULT_COLOR_LABELS } from './navigation/MenuItem/constants/DefaultColorLabels';
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.module.scss b/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.module.scss
index 02b0ae34f5f..7470a198356 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.module.scss
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.module.scss
@@ -70,3 +70,29 @@
font-size: var(--t-font-size-sm);
padding: var(--t-spacing-2);
}
+
+.header {
+ align-items: center;
+ border-bottom: 1px solid var(--t-border-color-light);
+ color: var(--t-font-color-primary);
+ display: flex;
+ flex: none;
+ font-size: var(--t-font-size-md);
+ font-weight: var(--t-font-weight-medium);
+ gap: var(--t-spacing-1);
+ min-block-size: 33px;
+ padding-inline: var(--t-spacing-2);
+
+ &:dir(rtl) svg {
+ transform: rotate(180deg);
+ }
+}
+
+.title {
+ flex: 1;
+ margin: 0;
+ min-inline-size: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.module.scss.d.ts b/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.module.scss.d.ts
index ae80577c77b..e8d14f39389 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.module.scss.d.ts
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.module.scss.d.ts
@@ -1,4 +1,5 @@
declare const classNames: {
+ readonly header: 'header';
readonly content: 'content';
readonly page: 'page';
readonly section: 'section';
@@ -7,5 +8,6 @@ declare const classNames: {
readonly searchContainer: 'searchContainer';
readonly search: 'search';
readonly status: 'status';
+ readonly title: 'title';
};
export default classNames;
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.tsx
index d7f293af370..9db3398418f 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.tsx
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/Dropdown.tsx
@@ -2,8 +2,10 @@ import { type ReactElement } from 'react';
import { DropdownActionItem } from './internal/DropdownActionItem';
import { DropdownBack } from './internal/DropdownBack';
+import { DropdownClose } from './internal/DropdownClose';
import { DropdownContent } from './internal/DropdownContent';
import { DropdownEmpty } from './internal/DropdownEmpty';
+import { DropdownHeader } from './internal/DropdownHeader';
import { DropdownLoading } from './internal/DropdownLoading';
import { DropdownOptionItem } from './internal/DropdownOptionItem';
import { DropdownPage } from './internal/DropdownPage';
@@ -13,6 +15,7 @@ import { DropdownSection } from './internal/DropdownSection';
import { DropdownSeparator } from './internal/DropdownSeparator';
import { DropdownSubmenu } from './internal/DropdownSubmenu';
import { DropdownSubmenuTrigger } from './internal/DropdownSubmenuTrigger';
+import { DropdownTitle } from './internal/DropdownTitle';
import { DropdownTrigger } from './internal/DropdownTrigger';
import { type DropdownRootProps } from './types/DropdownRootProps';
@@ -26,6 +29,9 @@ export const Dropdown = {
ActionItem: DropdownActionItem,
OptionItem: DropdownOptionItem,
Search: DropdownSearch,
+ Header: DropdownHeader,
+ Title: DropdownTitle,
+ Close: DropdownClose,
Page: DropdownPage,
Back: DropdownBack,
Submenu: DropdownSubmenu,
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/__stories__/Dropdown.stories.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/__stories__/Dropdown.stories.tsx
index 21f01d2281c..b6e8e66fc51 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/__stories__/Dropdown.stories.tsx
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/__stories__/Dropdown.stories.tsx
@@ -6,6 +6,7 @@ import { Button } from '@ui/primitives/input/Button/Button';
import { ComponentDecorator } from '@ui/testing';
import { Dropdown } from '../Dropdown';
+import { DropdownNestedExample } from './DropdownNestedExample';
import { DropdownPagesExample } from './DropdownPagesExample';
import { DropdownPanelExample } from './DropdownPanelExample';
import { DropdownPickerExample } from './DropdownPickerExample';
@@ -244,3 +245,47 @@ export const Panel: Story = {
);
},
};
+
+export const Nested: Story = {
+ render: () => <DropdownNestedExample />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ await userEvent.click(canvas.getByRole('button', { name: 'Sort' }));
+ await userEvent.click(
+ await body.findByRole('button', { name: 'Ascending' }),
+ );
+ await userEvent.click(
+ await body.findByRole('button', { name: 'Descending' }),
+ );
+ await waitFor(() =>
+ expect(
+ body.queryByRole('dialog', { name: 'Sort direction' }),
+ ).not.toBeInTheDocument(),
+ );
+ await expect(body.getByRole('dialog', { name: 'Sort' })).toBeVisible();
+ const direction = body.getByRole('button', { name: 'Descending' });
+ await expect(direction).toHaveFocus();
+ await userEvent.click(direction);
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(direction).toHaveFocus());
+ await waitFor(() => expect(body.getAllByRole('dialog')).toHaveLength(1));
+ await userEvent.click(direction);
+ await waitFor(() => expect(body.getAllByRole('dialog')).toHaveLength(2));
+ await userEvent.click(canvasElement);
+ await waitFor(() => expect(body.getAllByRole('dialog')).toHaveLength(1));
+ const search = body.getByRole('searchbox', { name: 'Search fields' });
+ await userEvent.type(search, 'Company');
+ await userEvent.keyboard('{Enter}');
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ await userEvent.click(canvas.getByRole('button', { name: 'Sort' }));
+ await userEvent.click(
+ await body.findByRole('button', { name: 'Close sort' }),
+ );
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ },
+};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/__stories__/DropdownNestedExample.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/__stories__/DropdownNestedExample.tsx
new file mode 100644
index 00000000000..3970be4d34a
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/__stories__/DropdownNestedExample.tsx
@@ -0,0 +1,58 @@
+import { useState } from 'react';
+
+import { Button } from '@ui/primitives/input/Button/Button';
+
+import { Dropdown } from '../Dropdown';
+
+export const DropdownNestedExample = () => {
+ const [open, setOpen] = useState(false);
+ const [direction, setDirection] = useState('Ascending');
+ const [search, setSearch] = useState('');
+ const fields = ['Name', 'Created at', 'Company'].filter((field) =>
+ field.toLowerCase().includes(search.toLowerCase()),
+ );
+
+ return (
+ <Dropdown.Root type="picker" open={open} onOpenChange={setOpen}>
+ <Dropdown.Trigger render={<Button>Sort</Button>} />
+ <Dropdown.Content width={240}>
+ <Dropdown.Header>
+ <Dropdown.Close aria-label="Close sort" />
+ <Dropdown.Title>Sort</Dropdown.Title>
+ </Dropdown.Header>
+ <Dropdown.Section>
+ <Dropdown.Root type="picker">
+ <Dropdown.Trigger render={<Button>{direction}</Button>} />
+ <Dropdown.Content aria-label="Sort direction">
+ <Dropdown.Section>
+ {['Ascending', 'Descending'].map((option) => (
+ <Dropdown.OptionItem
+ key={option}
+ selected={option === direction}
+ onSelect={() => setDirection(option)}
+ >
+ {option}
+ </Dropdown.OptionItem>
+ ))}
+ </Dropdown.Section>
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </Dropdown.Section>
+ <Dropdown.Separator />
+ <Dropdown.Search
+ aria-label="Search fields"
+ placeholder="Search fields"
+ value={search}
+ onValueChange={setSearch}
+ />
+ <Dropdown.Section label="Fields">
+ {fields.map((field) => (
+ <Dropdown.OptionItem key={field} selected={false}>
+ {field}
+ </Dropdown.OptionItem>
+ ))}
+ </Dropdown.Section>
+ </Dropdown.Content>
+ </Dropdown.Root>
+ );
+};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/__tests__/Dropdown.nested.test.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/__tests__/Dropdown.nested.test.tsx
new file mode 100644
index 00000000000..5c0ce630f26
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/__tests__/Dropdown.nested.test.tsx
@@ -0,0 +1,91 @@
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { describe, expect, it, vi } from 'vitest';
+
+import { Dropdown } from '../Dropdown';
+
+const NestedPicker = ({ onSelect }: { onSelect: () => void }) => (
+ <>
+ <button>Outside</button>
+ <Dropdown.Root type="picker">
+ <Dropdown.Trigger>Sort</Dropdown.Trigger>
+ <Dropdown.Content aria-label="Sort fields">
+ <Dropdown.Root type="picker">
+ <Dropdown.Trigger>Direction</Dropdown.Trigger>
+ <Dropdown.Content aria-label="Sort direction">
+ <Dropdown.OptionItem selected={false} onSelect={onSelect}>
+ Descending
+ </Dropdown.OptionItem>
+ </Dropdown.Content>
+ </Dropdown.Root>
+ <Dropdown.Search aria-label="Search fields" />
+ <Dropdown.OptionItem selected={false}>Name</Dropdown.OptionItem>
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </>
+);
+
+describe('Independent nested dropdown roots', () => {
+ it('selects an inner option without closing its parent and restores the inner trigger focus', async () => {
+ const user = userEvent.setup();
+ const onSelect = vi.fn();
+ render(<NestedPicker onSelect={onSelect} />);
+
+ await user.click(screen.getByRole('button', { name: 'Sort' }));
+ await user.click(screen.getByRole('button', { name: 'Direction' }));
+ await user.click(screen.getByRole('button', { name: 'Descending' }));
+
+ expect(onSelect).toHaveBeenCalledOnce();
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: 'Sort direction' }),
+ ).not.toBeInTheDocument(),
+ );
+ expect(screen.getByRole('dialog', { name: 'Sort fields' })).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Direction' })).toHaveFocus();
+ });
+
+ it.each(['escape', 'outside press'] as const)(
+ 'dismisses one layer at a time with %s',
+ async (dismissal) => {
+ const user = userEvent.setup();
+ render(<NestedPicker onSelect={vi.fn()} />);
+
+ await user.click(screen.getByRole('button', { name: 'Sort' }));
+ await user.click(screen.getByRole('button', { name: 'Direction' }));
+ await screen.findByRole('dialog', { name: 'Sort direction' });
+
+ const dismiss = async () => {
+ if (dismissal === 'escape') {
+ await user.keyboard('{Escape}');
+ return;
+ }
+ await user.click(screen.getByRole('button', { name: 'Outside' }));
+ };
+
+ await dismiss();
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: 'Sort direction' }),
+ ).not.toBeInTheDocument(),
+ );
+ expect(screen.getByRole('dialog', { name: 'Sort fields' })).toBeVisible();
+ if (dismissal === 'escape') {
+ expect(screen.getByRole('button', { name: 'Direction' })).toHaveFocus();
+ }
+ await user.click(screen.getByRole('button', { name: 'Direction' }));
+ await screen.findByRole('dialog', { name: 'Sort direction' });
+ await dismiss();
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: 'Sort direction' }),
+ ).not.toBeInTheDocument(),
+ );
+ expect(screen.getByRole('dialog', { name: 'Sort fields' })).toBeVisible();
+ await dismiss();
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ },
+ );
+});
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/__tests__/Dropdown.picker.test.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/__tests__/Dropdown.picker.test.tsx
index 069a5d3d67d..5660bed0214 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/__tests__/Dropdown.picker.test.tsx
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/__tests__/Dropdown.picker.test.tsx
@@ -1,4 +1,4 @@
-import { isNonEmptyArray } from '@sniptt/guards';
+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useState } from 'react';
@@ -11,9 +11,11 @@ const PEOPLE = ['Ada Lovelace', 'Grace Hopper', 'Margaret Hamilton'];
const SearchablePicker = ({
multiple = false,
onCreate,
+ onSelectPerson,
}: {
multiple?: boolean;
onCreate: () => void;
+ onSelectPerson?: (person: string) => void;
}) => {
const [search, setSearch] = useState('');
const [selectedPeople, setSelectedPeople] = useState<string[]>([]);
@@ -37,15 +39,16 @@ const SearchablePicker = ({
<Dropdown.OptionItem
key={person}
selected={selectedPeople.includes(person)}
- onSelect={() =>
+ onSelect={() => {
+ onSelectPerson?.(person);
setSelectedPeople((current) =>
current.includes(person)
? current.filter(
(selectedPerson) => selectedPerson !== person,
)
: [...current, person],
- )
- }
+ );
+ }}
>
{person}
</Dropdown.OptionItem>
@@ -59,6 +62,141 @@ const SearchablePicker = ({
};
describe('Dropdown picker', () => {
+ it.each([
+ { query: '', selectedPerson: undefined },
+ { query: 'grace', selectedPerson: 'Grace Hopper' },
+ ])(
+ 'handles Enter from search with query "$query"',
+ async ({ query, selectedPerson }) => {
+ const user = userEvent.setup();
+ const onCreate = vi.fn();
+ const onSelectPerson = vi.fn();
+ render(
+ <SearchablePicker
+ onCreate={onCreate}
+ onSelectPerson={onSelectPerson}
+ />,
+ );
+ await user.click(screen.getByRole('button', { name: 'Assignees' }));
+ const search = screen.getByRole('searchbox', { name: 'Search people' });
+ await waitFor(() => expect(search).toHaveFocus());
+ if (isNonEmptyString(query)) {
+ await user.type(search, query);
+ }
+ await user.keyboard('{Enter}');
+ expect(onCreate).not.toHaveBeenCalled();
+ if (isNonEmptyString(selectedPerson)) {
+ expect(onSelectPerson).toHaveBeenCalledExactlyOnceWith(selectedPerson);
+ } else {
+ expect(onSelectPerson).not.toHaveBeenCalled();
+ }
+ },
+ );
+
+ it('highlights the option Enter picks while the search has text', async () => {
+ const user = userEvent.setup();
+ render(<SearchablePicker onCreate={vi.fn()} />);
+ await user.click(screen.getByRole('button', { name: 'Assignees' }));
+ const search = screen.getByRole('searchbox', { name: 'Search people' });
+ await waitFor(() => expect(search).toHaveFocus());
+ expect(search).not.toHaveAttribute('aria-activedescendant');
+
+ await user.type(search, 'a');
+ const ada = screen.getByRole('button', { name: 'Ada Lovelace' });
+ await waitFor(() => expect(ada).toHaveAttribute('data-highlighted'));
+ expect(search).toHaveAttribute('aria-activedescendant', ada.id);
+ expect(
+ screen.getByRole('button', { name: 'Create person' }),
+ ).not.toHaveAttribute('data-highlighted');
+
+ await user.type(search, 'r');
+ const margaret = screen.getByRole('button', { name: 'Margaret Hamilton' });
+ await waitFor(() => expect(margaret).toHaveAttribute('data-highlighted'));
+ expect(search).toHaveAttribute('aria-activedescendant', margaret.id);
+
+ await user.clear(search);
+ await waitFor(() =>
+ expect(search).not.toHaveAttribute('aria-activedescendant'),
+ );
+ expect(
+ screen.getByRole('button', { name: 'Ada Lovelace' }),
+ ).not.toHaveAttribute('data-highlighted');
+ });
+
+ it('selects the first enabled result', async () => {
+ const user = userEvent.setup();
+ const onSelect = vi.fn();
+ render(
+ <Dropdown.Root type="picker">
+ <Dropdown.Trigger>Fields</Dropdown.Trigger>
+ <Dropdown.Content aria-label="Fields">
+ <Dropdown.Search aria-label="Search fields" />
+ <Dropdown.OptionItem selected={false} disabled>
+ Disabled
+ </Dropdown.OptionItem>
+ <Dropdown.OptionItem selected={false} onSelect={onSelect}>
+ Name
+ </Dropdown.OptionItem>
+ </Dropdown.Content>
+ </Dropdown.Root>,
+ );
+ await user.click(screen.getByRole('button', { name: 'Fields' }));
+ const search = screen.getByRole('searchbox');
+ await waitFor(() => expect(search).toHaveFocus());
+ await user.type(search, 'n');
+ await user.keyboard('{Enter}');
+ expect(onSelect).toHaveBeenCalledOnce();
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ });
+
+ it('leaves an empty result list open when Enter has no option to pick', async () => {
+ const user = userEvent.setup();
+ render(
+ <Dropdown.Root type="picker">
+ <Dropdown.Trigger>Fields</Dropdown.Trigger>
+ <Dropdown.Content aria-label="Fields">
+ <Dropdown.Search aria-label="Search fields" />
+ <Dropdown.Empty>No fields found</Dropdown.Empty>
+ </Dropdown.Content>
+ </Dropdown.Root>,
+ );
+ await user.click(screen.getByRole('button', { name: 'Fields' }));
+ const search = screen.getByRole('searchbox');
+ await waitFor(() => expect(search).toHaveFocus());
+ await user.type(search, 'x');
+ await user.keyboard('{Enter}');
+ expect(screen.getByRole('dialog')).toBeVisible();
+ expect(search).toHaveFocus();
+ });
+
+ it('names the popup after its title and closes from the header', async () => {
+ const user = userEvent.setup();
+ const onOpenChange = vi.fn();
+ render(
+ <Dropdown.Root type="picker" onOpenChange={onOpenChange}>
+ <Dropdown.Trigger>Sort</Dropdown.Trigger>
+ <Dropdown.Content>
+ <Dropdown.Header>
+ <Dropdown.Close aria-label="Close sort" />
+ <Dropdown.Title>Sort by</Dropdown.Title>
+ </Dropdown.Header>
+ <Dropdown.OptionItem selected={false}>Name</Dropdown.OptionItem>
+ </Dropdown.Content>
+ </Dropdown.Root>,
+ );
+ await user.click(screen.getByRole('button', { name: 'Sort' }));
+ expect(
+ await screen.findByRole('dialog', { name: 'Sort by' }),
+ ).toBeVisible();
+ await user.click(screen.getByRole('button', { name: 'Close sort' }));
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ });
+
it('filters caller-owned results and navigates mixed commands and options from search', async () => {
const user = userEvent.setup();
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownClose.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownClose.tsx
new file mode 100644
index 00000000000..40dc00f955e
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownClose.tsx
@@ -0,0 +1,28 @@
+import { Popover as PopoverPrimitive } from '@base-ui/react/popover';
+
+import { LightIconButton } from '@ui/components/input/LightIconButton/LightIconButton';
+import { IconX } from '@ui/icon';
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import { type DropdownCloseProps } from '../types/DropdownCloseProps';
+
+export const DropdownClose = ({
+ render,
+ children,
+ 'aria-label': ariaLabel,
+ ...props
+}: DropdownCloseProps) => (
+ <PopoverPrimitive.Close
+ {...props}
+ aria-label={ariaLabel}
+ render={
+ render ?? (
+ <LightIconButton size="sm" aria-label={ariaLabel}>
+ {children ?? <IconX />}
+ </LightIconButton>
+ )
+ }
+ >
+ {isDefined(render) ? children : undefined}
+ </PopoverPrimitive.Close>
+);
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownContent.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownContent.tsx
index 58809540505..a12218405ab 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownContent.tsx
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownContent.tsx
@@ -1,6 +1,6 @@
import { useMergedRefs } from '@base-ui/utils/useMergedRefs';
import { isFunction } from '@sniptt/guards';
-import { useRef } from 'react';
+import { useRef, useState } from 'react';
import { Popover } from '@ui/primitives/surfaces/Popover/Popover';
import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
@@ -9,6 +9,7 @@ import { isDefined } from '@ui/utilities/utils/isDefined';
import styles from '../Dropdown.module.scss';
import { type DropdownContentProps } from '../types/DropdownContentProps';
import { DropdownPageFocusEffect } from './DropdownPageFocusEffect';
+import { DropdownSearchTargetEffect } from './DropdownSearchTargetEffect';
import { getDropdownFocusTarget } from './getDropdownFocusTarget';
import { isUnhandledModifierShortcut } from './isUnhandledModifierShortcut';
import { useDropdownContext } from './useDropdownContext';
@@ -37,7 +38,8 @@ export const DropdownContent = ({
const { type, isSubmenu, setOpen, initialFocusEdge, focusOnOpen } =
useDropdownContext();
const contentRef = useRef<HTMLDivElement>(null);
- const mergedRef = useMergedRefs(contentRef, ref);
+ const [content, setContent] = useState<HTMLDivElement | null>(null);
+ const mergedRef = useMergedRefs(contentRef, ref, setContent);
const handleNavigation = useDropdownKeyboardNavigation({
type,
isSubmenu,
@@ -106,6 +108,7 @@ export const DropdownContent = ({
{children}
</Popover.Popup>
<DropdownPageFocusEffect contentRef={contentRef} />
+ <DropdownSearchTargetEffect content={content} />
</>
);
};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownContextValue.ts b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownContextValue.ts
index 52039ec3aa5..cb241938bff 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownContextValue.ts
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownContextValue.ts
@@ -26,4 +26,7 @@ export type DropdownContextValue = {
goToPage: (page: { id: string; trigger: DropdownFocusTarget }) => void;
goBack: () => void;
registerPage: (page: { id: string; type?: DropdownType }) => void;
+ registerOpenNestedRoot: () => () => void;
+ searchTargetId?: string;
+ setSearchTargetId: (id: string | undefined) => void;
};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownHeader.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownHeader.tsx
new file mode 100644
index 00000000000..97590937c04
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownHeader.tsx
@@ -0,0 +1,17 @@
+import { useRender } from '@base-ui/react/use-render';
+import { clsx } from 'clsx';
+
+import styles from '../Dropdown.module.scss';
+import { type DropdownHeaderProps } from '../types/DropdownHeaderProps';
+
+export const DropdownHeader = ({
+ render,
+ ref,
+ className,
+ ...props
+}: DropdownHeaderProps) =>
+ useRender({
+ render,
+ ref,
+ props: { ...props, className: clsx(styles.header, className) },
+ });
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownNestedRootEffect.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownNestedRootEffect.tsx
new file mode 100644
index 00000000000..2bc8978b47f
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownNestedRootEffect.tsx
@@ -0,0 +1,21 @@
+import { useEffect } from 'react';
+
+type DropdownNestedRootEffectProps = {
+ open: boolean;
+ registerOpenNestedRoot?: () => () => void;
+};
+
+export const DropdownNestedRootEffect = ({
+ open,
+ registerOpenNestedRoot,
+}: DropdownNestedRootEffectProps) => {
+ useEffect(() => {
+ if (!open) {
+ return;
+ }
+
+ return registerOpenNestedRoot?.();
+ }, [open, registerOpenNestedRoot]);
+
+ return null;
+};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownOptionItem.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownOptionItem.tsx
index c2204d16624..afdfe317ba1 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownOptionItem.tsx
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownOptionItem.tsx
@@ -29,7 +29,7 @@ export const DropdownOptionItem = ({
id,
...props
}: DropdownOptionItemProps) => {
- const { type, multiple, closeTree } = useDropdownContext();
+ const { type, multiple, closeTree, searchTargetId } = useDropdownContext();
const isMenu = type === 'menu';
const menuOptionRole = multiple ? 'menuitemcheckbox' : 'menuitemradio';
const generatedId = useId();
@@ -51,6 +51,7 @@ export const DropdownOptionItem = ({
onFocus?.(event);
}}
data-dropdown-item=""
+ data-dropdown-option-item=""
onClick={(event) => {
onClick?.(event);
@@ -70,6 +71,7 @@ export const DropdownOptionItem = ({
render={render ?? <button type="button" />}
disabled={disabled}
selected={selected}
+ focused={searchTargetId === itemId}
indicator={indicator ?? (multiple ? 'checkbox' : 'check')}
color={color}
startIcon={startIcon}
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownRoot.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownRoot.tsx
index c96451a0c2f..41e95f6d654 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownRoot.tsx
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownRoot.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useContext, useState } from 'react';
+import { useCallback, useContext, useRef, useState } from 'react';
import { Popover } from '@ui/primitives/surfaces/Popover/Popover';
import { isDefined } from '@ui/utilities/utils/isDefined';
@@ -8,6 +8,7 @@ import { type DropdownType } from '../types/DropdownType';
import { DropdownContext } from './DropdownContext';
import { type DropdownFocusTarget } from './DropdownFocusTarget';
import { type DropdownPageFocusRequest } from './DropdownPageFocusRequest';
+import { DropdownNestedRootEffect } from './DropdownNestedRootEffect';
import { preventDismissingClickActivation } from './preventDismissingClickActivation';
type PageHistoryEntry = { id?: string; trigger?: DropdownFocusTarget };
@@ -23,6 +24,14 @@ export const DropdownRoot = ({
isSubmenu = false,
}: DropdownRootProps & { isSubmenu?: boolean }) => {
const parent = useContext(DropdownContext);
+ const openNestedRootCountRef = useRef(0);
+ const registerOpenNestedRoot = useCallback(() => {
+ openNestedRootCountRef.current += 1;
+
+ return () => {
+ openNestedRootCountRef.current -= 1;
+ };
+ }, []);
const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
const open = controlledOpen ?? uncontrolledOpen;
const [previousOpen, setPreviousOpen] = useState(open);
@@ -41,6 +50,7 @@ export const DropdownRoot = ({
'first',
);
const [focusOnOpen, setFocusOnOpen] = useState(true);
+ const [searchTargetId, setSearchTargetId] = useState<string>();
if (previousOpen !== open) {
setPreviousOpen(open);
@@ -51,6 +61,7 @@ export const DropdownRoot = ({
setPageFocusRequest(undefined);
setInitialFocusEdge('first');
setFocusOnOpen(true);
+ setSearchTargetId(undefined);
}
}
@@ -117,10 +128,16 @@ export const DropdownRoot = ({
<Popover.Root
open={open}
onOpenChange={(nextOpen, eventDetails) => {
- if (
+ const isOutsideDismissal =
eventDetails.reason === 'outside-press' ||
- eventDetails.reason === 'focus-out'
- ) {
+ eventDetails.reason === 'focus-out';
+
+ if (isOutsideDismissal && openNestedRootCountRef.current > 0) {
+ eventDetails.cancel();
+ return;
+ }
+
+ if (isOutsideDismissal) {
preventDismissingClickActivation(eventDetails.event);
}
@@ -156,8 +173,17 @@ export const DropdownRoot = ({
goToPage,
goBack,
registerPage,
+ registerOpenNestedRoot,
+ searchTargetId,
+ setSearchTargetId,
}}
>
+ <DropdownNestedRootEffect
+ open={open}
+ registerOpenNestedRoot={
+ isSubmenu ? undefined : parent?.registerOpenNestedRoot
+ }
+ />
{children}
</DropdownContext.Provider>
</Popover.Root>
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownSearch.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownSearch.tsx
index ef14279b8f1..353500ba63e 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownSearch.tsx
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownSearch.tsx
@@ -3,20 +3,26 @@ import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
import styles from '../Dropdown.module.scss';
import { type DropdownSearchProps } from '../types/DropdownSearchProps';
+import { useDropdownContext } from './useDropdownContext';
export const DropdownSearch = ({
onValueChange,
className,
...props
-}: DropdownSearchProps) => (
- <div className={styles.searchContainer}>
- <Input
- type="search"
- autoComplete="off"
- {...props}
- data-dropdown-search=""
- className={mergeClassNames(styles.search, className)}
- onValueChange={(value) => onValueChange?.(value)}
- />
- </div>
-);
+}: DropdownSearchProps) => {
+ const { searchTargetId } = useDropdownContext();
+
+ return (
+ <div className={styles.searchContainer}>
+ <Input
+ type="search"
+ autoComplete="off"
+ aria-activedescendant={searchTargetId}
+ {...props}
+ data-dropdown-search=""
+ className={mergeClassNames(styles.search, className)}
+ onValueChange={(value) => onValueChange?.(value)}
+ />
+ </div>
+ );
+};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownSearchTargetEffect.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownSearchTargetEffect.tsx
new file mode 100644
index 00000000000..5470adf758d
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownSearchTargetEffect.tsx
@@ -0,0 +1,45 @@
+import { useLayoutEffect } from 'react';
+
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import { getDropdownSearchTarget } from './getDropdownSearchTarget';
+import { useDropdownContext } from './useDropdownContext';
+
+type DropdownSearchTargetEffectProps = {
+ content: HTMLDivElement | null;
+};
+
+export const DropdownSearchTargetEffect = ({
+ content,
+}: DropdownSearchTargetEffectProps) => {
+ const { setSearchTargetId } = useDropdownContext();
+
+ useLayoutEffect(() => {
+ if (!isDefined(content)) {
+ return;
+ }
+
+ const updateSearchTarget = () =>
+ setSearchTargetId(getDropdownSearchTarget(content)?.id);
+
+ updateSearchTarget();
+
+ const observer = new MutationObserver(updateSearchTarget);
+
+ observer.observe(content, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['disabled', 'aria-disabled'],
+ });
+ content.addEventListener('input', updateSearchTarget);
+
+ return () => {
+ observer.disconnect();
+ content.removeEventListener('input', updateSearchTarget);
+ setSearchTargetId(undefined);
+ };
+ }, [content, setSearchTargetId]);
+
+ return null;
+};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownTitle.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownTitle.tsx
new file mode 100644
index 00000000000..aa8b3476d5f
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownTitle.tsx
@@ -0,0 +1,18 @@
+import { Popover as PopoverPrimitive } from '@base-ui/react/popover';
+
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
+
+import styles from '../Dropdown.module.scss';
+import { type DropdownTitleProps } from '../types/DropdownTitleProps';
+
+export const DropdownTitle = ({
+ className,
+ render,
+ ...props
+}: DropdownTitleProps) => (
+ <PopoverPrimitive.Title
+ {...props}
+ render={render ?? <div />}
+ className={mergeClassNames(styles.title, className)}
+ />
+);
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/getDropdownSearchTarget.ts b/packages/twenty-ui/src/components/navigation/Dropdown/internal/getDropdownSearchTarget.ts
new file mode 100644
index 00000000000..e6b99c4740e
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/getDropdownSearchTarget.ts
@@ -0,0 +1,23 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import { getDropdownItems } from './getDropdownItems';
+
+export const getDropdownSearchTarget = (content: HTMLElement) => {
+ if (content.dataset.type === 'panel') {
+ return undefined;
+ }
+
+ const search = content.querySelector<HTMLInputElement>(
+ '[data-dropdown-search]:not(:disabled)',
+ );
+
+ if (!isDefined(search) || !isNonEmptyString(search.value.trim())) {
+ return undefined;
+ }
+
+ return getDropdownItems(content).find((item) =>
+ item.hasAttribute('data-dropdown-option-item'),
+ );
+};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/useDropdownKeyboardNavigation.ts b/packages/twenty-ui/src/components/navigation/Dropdown/internal/useDropdownKeyboardNavigation.ts
index 63ad5db44a7..9fedc636066 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/useDropdownKeyboardNavigation.ts
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/useDropdownKeyboardNavigation.ts
@@ -5,6 +5,7 @@ import { isDefined } from '@ui/utilities/utils/isDefined';
import { type DropdownType } from '../types/DropdownType';
import { getDropdownItemLabel } from './getDropdownItemLabel';
import { getDropdownItems } from './getDropdownItems';
+import { getDropdownSearchTarget } from './getDropdownSearchTarget';
import { getDropdownTrigger } from './getDropdownTrigger';
import { getNextDropdownItem } from './getNextDropdownItem';
@@ -69,6 +70,17 @@ export const useDropdownKeyboardNavigation = ({
const items = getDropdownItems(content).filter(
(item) => !isDefined(search) || !item.hasAttribute('data-dropdown-back'),
);
+ const searchTarget =
+ isSearch && event.key === 'Enter' && !event.nativeEvent.isComposing
+ ? getDropdownSearchTarget(content)
+ : undefined;
+
+ if (isDefined(searchTarget)) {
+ event.preventDefault();
+ searchTarget.click();
+ return;
+ }
+
const currentIndex = items.indexOf(target);
const nextItem = getNextDropdownItem({
key: event.key,
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownCloseProps.ts b/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownCloseProps.ts
new file mode 100644
index 00000000000..d1685f7b965
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownCloseProps.ts
@@ -0,0 +1,8 @@
+import { type Popover as PopoverPrimitive } from '@base-ui/react/popover';
+
+export type DropdownCloseProps = Omit<
+ PopoverPrimitive.Close.Props,
+ 'aria-label'
+> & {
+ 'aria-label': string;
+};
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownHeaderProps.ts b/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownHeaderProps.ts
new file mode 100644
index 00000000000..fee39fb8a58
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownHeaderProps.ts
@@ -0,0 +1,3 @@
+import { type useRender } from '@base-ui/react/use-render';
+
+export type DropdownHeaderProps = useRender.ComponentProps<'div'>;
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownTitleProps.ts b/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownTitleProps.ts
new file mode 100644
index 00000000000..687eee887c8
--- /dev/null
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/types/DropdownTitleProps.ts
@@ -0,0 +1,3 @@
+import { type Popover as PopoverPrimitive } from '@base-ui/react/popover';
+
+export type DropdownTitleProps = PopoverPrimitive.Title.Props;