Skip to content

The open alternative to Salesforce, designed for AI.

fix(front): select first matching option on enter in multi-select input (#24015)

Thomas Trompette64a051e6bc56
diff --git a/packages/twenty-front/src/modules/ui/field/input/components/MultiSelectInput.tsx b/packages/twenty-front/src/modules/ui/field/input/components/MultiSelectInput.tsx
index 8391bf08e50..d041bb2cbfd 100644
--- a/packages/twenty-front/src/modules/ui/field/input/components/MultiSelectInput.tsx
+++ b/packages/twenty-front/src/modules/ui/field/input/components/MultiSelectInput.tsx
@@ -1,4 +1,5 @@
-import { useMemo, useRef, useState } from 'react';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useRef, useState } from 'react';
import { Key } from 'ts-key-enum';
import { type FieldMultiSelectValue } from '@/object-record/record-field/ui/types/FieldMetadata';
@@ -59,12 +60,14 @@ export const MultiSelectInput = ({
values?.includes(option.value),
);
- const filteredOptionsInDropDown = useMemo(() => {
- const searchTerm = normalizeSearchText(searchFilter);
+ const filterOptions = (searchText: string) => {
+ const searchTerm = normalizeSearchText(searchText);
return options.filter((option) => {
return normalizeSearchText(option.label).includes(searchTerm);
});
- }, [options, searchFilter]);
+ };
+
+ const filteredOptionsInDropDown = filterOptions(searchFilter);
const formatNewSelectedOptions = (value: string) => {
const selectedOptionsValues = selectedOptions.map(
@@ -113,6 +116,7 @@ export const MultiSelectInput = ({
selectableListInstanceId={selectableListComponentInstanceId}
selectableItemIdArray={optionIds}
focusId={focusId}
+ shouldPreselectFirstItem={isNonEmptyString(searchFilter)}
>
<DropdownContent
ref={containerRef}
diff --git a/packages/twenty-front/src/modules/ui/layout/selectable-list/components/SelectableList.tsx b/packages/twenty-front/src/modules/ui/layout/selectable-list/components/SelectableList.tsx
index 3cb927874d4..27d0422632b 100644
--- a/packages/twenty-front/src/modules/ui/layout/selectable-list/components/SelectableList.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/selectable-list/components/SelectableList.tsx
@@ -1,10 +1,13 @@
import { type ReactNode, useEffect } from 'react';
+import { useSelectableList } from '@/ui/layout/selectable-list/hooks/useSelectableList';
import { useSelectableListHotKeys } from '@/ui/layout/selectable-list/hooks/internal/useSelectableListHotKeys';
import { SelectableListComponentInstanceContext } from '@/ui/layout/selectable-list/states/contexts/SelectableListComponentInstanceContext';
import { SelectableListContextProvider } from '@/ui/layout/selectable-list/states/contexts/SelectableListContext';
import { selectableItemIdsComponentState } from '@/ui/layout/selectable-list/states/selectableItemIdsComponentState';
+import { selectedItemIdComponentState } from '@/ui/layout/selectable-list/states/selectedItemIdComponentState';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
+import { useStore } from 'jotai';
import { isDefined } from 'twenty-shared/utils';
import { arrayToChunks } from '~/utils/array/arrayToChunks';
@@ -15,6 +18,7 @@ type SelectableListProps = {
onSelect?: (selected: string) => void;
selectableListInstanceId: string;
focusId: string;
+ shouldPreselectFirstItem?: boolean;
};
export const SelectableList = ({
@@ -24,9 +28,16 @@ export const SelectableList = ({
selectableListInstanceId,
onSelect,
focusId,
+ shouldPreselectFirstItem,
}: SelectableListProps) => {
useSelectableListHotKeys(selectableListInstanceId, focusId, onSelect);
+ const store = useStore();
+
+ const { resetSelectedItem, setSelectedItemId } = useSelectableList(
+ selectableListInstanceId,
+ );
+
const setSelectableItemIds = useSetAtomComponentState(
selectableItemIdsComponentState,
selectableListInstanceId,
@@ -46,7 +57,39 @@ export const SelectableList = ({
if (isDefined(selectableItemIdArray)) {
setSelectableItemIds(arrayToChunks(selectableItemIdArray, 1));
}
- }, [selectableItemIdArray, selectableItemIdMatrix, setSelectableItemIds]);
+
+ if (shouldPreselectFirstItem !== true) {
+ return;
+ }
+
+ const itemIds =
+ selectableItemIdArray ?? selectableItemIdMatrix?.flat() ?? [];
+ const firstItemId = itemIds[0];
+
+ if (!isDefined(firstItemId)) {
+ resetSelectedItem();
+ return;
+ }
+
+ const selectedItemId = store.get(
+ selectedItemIdComponentState.atomFamily({
+ instanceId: selectableListInstanceId,
+ }),
+ );
+
+ if (!isDefined(selectedItemId) || !itemIds.includes(selectedItemId)) {
+ setSelectedItemId(firstItemId);
+ }
+ }, [
+ selectableItemIdArray,
+ selectableItemIdMatrix,
+ selectableListInstanceId,
+ setSelectableItemIds,
+ shouldPreselectFirstItem,
+ resetSelectedItem,
+ setSelectedItemId,
+ store,
+ ]);
return (
<SelectableListComponentInstanceContext.Provider
diff --git a/packages/twenty-front/src/modules/ui/layout/selectable-list/components/__stories__/SelectableList.stories.tsx b/packages/twenty-front/src/modules/ui/layout/selectable-list/components/__stories__/SelectableList.stories.tsx
new file mode 100644
index 00000000000..91fbde22a47
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/layout/selectable-list/components/__stories__/SelectableList.stories.tsx
@@ -0,0 +1,165 @@
+import { SelectableList } from '@/ui/layout/selectable-list/components/SelectableList';
+import { SelectableListItem } from '@/ui/layout/selectable-list/components/SelectableListItem';
+import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';
+import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
+import { isNonEmptyString } from '@sniptt/guards';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useEffect, useState } from 'react';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import { MenuItem } from 'twenty-ui/navigation';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+const ITEM_LABELS = [
+ 'Content Marketing',
+ 'Growth Hacking',
+ 'Search Engine',
+ 'Viral Marketing',
+];
+
+const focusId = 'selectable-list-story';
+
+type RenderProps = {
+ onEnter: (itemLabel: string) => void;
+ shouldPreselectFirstItem?: boolean;
+};
+
+const Render = ({ onEnter, shouldPreselectFirstItem }: RenderProps) => {
+ const [searchFilter, setSearchFilter] = useState('');
+
+ const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();
+
+ useEffect(() => {
+ pushFocusItemToFocusStack({
+ focusId,
+ component: {
+ type: FocusComponentType.DROPDOWN,
+ instanceId: focusId,
+ },
+ });
+ }, [pushFocusItemToFocusStack]);
+
+ const filteredItemLabels = ITEM_LABELS.filter((itemLabel) =>
+ itemLabel.toLowerCase().includes(searchFilter.toLowerCase()),
+ );
+
+ return (
+ <SelectableList
+ selectableListInstanceId={focusId}
+ selectableItemIdArray={filteredItemLabels}
+ focusId={focusId}
+ shouldPreselectFirstItem={
+ shouldPreselectFirstItem ?? isNonEmptyString(searchFilter)
+ }
+ >
+ <input
+ aria-label="Search"
+ value={searchFilter}
+ onChange={(event) => setSearchFilter(event.currentTarget.value)}
+ autoFocus
+ />
+ {filteredItemLabels.map((itemLabel) => (
+ <SelectableListItem
+ key={itemLabel}
+ itemId={itemLabel}
+ onEnter={() => onEnter(itemLabel)}
+ >
+ <MenuItem text={itemLabel} />
+ </SelectableListItem>
+ ))}
+ </SelectableList>
+ );
+};
+
+const meta: Meta<typeof Render> = {
+ title: 'UI/Layout/SelectableList/SelectableList',
+ component: Render,
+ decorators: [ComponentDecorator],
+ args: {
+ onEnter: fn(),
+ },
+ render: Render,
+};
+
+export default meta;
+type Story = StoryObj<typeof Render>;
+
+export const PreselectsFirstMatchingItem: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.type(await canvas.findByLabelText('Search'), 'marketing');
+
+ await waitFor(() => {
+ expect(canvas.queryByText('Growth Hacking')).not.toBeInTheDocument();
+ });
+
+ await userEvent.keyboard('{Enter}');
+
+ await waitFor(() => {
+ expect(args.onEnter).toHaveBeenCalledWith('Content Marketing');
+ });
+ },
+};
+
+export const KeepsSelectedItemWhileItStillMatches: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ const searchInput = await canvas.findByLabelText('Search');
+
+ await userEvent.type(searchInput, 'ar');
+
+ await waitFor(() => {
+ expect(canvas.getByText('Search Engine')).toBeVisible();
+ });
+
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.type(searchInput, 'k');
+
+ await waitFor(() => {
+ expect(canvas.queryByText('Search Engine')).not.toBeInTheDocument();
+ });
+
+ await userEvent.keyboard('{Enter}');
+
+ await waitFor(() => {
+ expect(args.onEnter).toHaveBeenCalledWith('Viral Marketing');
+ });
+ },
+};
+
+export const SelectsNothingWithoutMatchingItem: Story = {
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.type(await canvas.findByLabelText('Search'), 'xyz123');
+
+ await waitFor(() => {
+ expect(canvas.queryByText('Content Marketing')).not.toBeInTheDocument();
+ });
+
+ await userEvent.keyboard('{Enter}');
+
+ expect(args.onEnter).not.toHaveBeenCalled();
+ },
+};
+
+export const SelectsNothingWithoutPreselection: Story = {
+ args: {
+ shouldPreselectFirstItem: false,
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.type(await canvas.findByLabelText('Search'), 'marketing');
+
+ await waitFor(() => {
+ expect(canvas.queryByText('Growth Hacking')).not.toBeInTheDocument();
+ });
+
+ await userEvent.keyboard('{Enter}');
+
+ expect(args.onEnter).not.toHaveBeenCalled();
+ },
+};