Skip to content

The open alternative to Salesforce, designed for AI.

Navigate the inbox with the arrow keys (#27875)

Félix Malfait8f7a6b078daa
diff --git a/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx b/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx
index 8f3e9caec9a..c018bb76eb9 100644
--- a/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx
+++ b/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx
@@ -256,6 +256,32 @@ export const PageChangeEffect = () => {
}
break;
}
+ case isMatchingLocation(location, AppPath.AiChatInbox): {
+ const isEnteringAiChatInbox = !matchPath(
+ AppPath.AiChatInbox,
+ previousLocation,
+ );
+
+ if (!isEnteringAiChatInbox) {
+ break;
+ }
+
+ resetFocusStackToFocusItem({
+ focusStackItem: {
+ focusId: PageFocusId.AiChatInbox,
+ componentInstance: {
+ componentType: FocusComponentType.PAGE,
+ componentInstanceId: PageFocusId.AiChatInbox,
+ },
+ globalHotkeysConfig: {
+ enableGlobalHotkeysWithModifiers: true,
+ enableGlobalHotkeysConflictingWithKeyboard: true,
+ },
+ },
+ shouldKeepItemsAbovePage: store.get(isSidePanelOpenedState.atom),
+ });
+ break;
+ }
case isMatchingLocation(location, AppPath.PageLayoutPage): {
resetFocusStackToFocusItem({
focusStackItem: {
diff --git a/packages/twenty-front/src/modules/app/effect-components/__tests__/PageChangeEffect.test.tsx b/packages/twenty-front/src/modules/app/effect-components/__tests__/PageChangeEffect.test.tsx
index e6290cc256e..ddc0bc9af53 100644
--- a/packages/twenty-front/src/modules/app/effect-components/__tests__/PageChangeEffect.test.tsx
+++ b/packages/twenty-front/src/modules/app/effect-components/__tests__/PageChangeEffect.test.tsx
@@ -13,6 +13,10 @@ import {
type SidePanelNavigationStackItem,
sidePanelNavigationStackState,
} from '@/side-panel/states/sidePanelNavigationStackState';
+import { PageFocusId } from '@/types/PageFocusId';
+import { currentGlobalHotkeysConfigSelector } from '@/ui/utilities/focus/states/currentGlobalHotkeysConfigSelector';
+import { focusStackState } from '@/ui/utilities/focus/states/focusStackState';
+import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';
import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
@@ -116,4 +120,117 @@ describe('PageChangeEffect', () => {
});
expect(jotaiStore.get(isSidePanelOpenedState.atom)).toBe(true);
});
+
+ it('should let the inbox use global hotkeys when coming from settings', async () => {
+ renderPageChangeEffect();
+
+ act(() => navigateMainPage?.('/settings/profile'));
+ await waitFor(() => {
+ expect(
+ jotaiStore.get(currentGlobalHotkeysConfigSelector.atom)
+ .enableGlobalHotkeysConflictingWithKeyboard,
+ ).toBe(false);
+ });
+
+ act(() => navigateMainPage?.('/inbox'));
+
+ await waitFor(() => {
+ expect(jotaiStore.get(focusStackState.atom).at(-1)?.focusId).toBe(
+ PageFocusId.AiChatInbox,
+ );
+ });
+ expect(
+ jotaiStore.get(currentGlobalHotkeysConfigSelector.atom)
+ .enableGlobalHotkeysConflictingWithKeyboard,
+ ).toBe(true);
+ });
+
+ it('should keep what is focused over the inbox when moving between chats', async () => {
+ renderPageChangeEffect();
+
+ act(() => navigateMainPage?.('/inbox'));
+ await waitFor(() => {
+ expect(jotaiStore.get(focusStackState.atom).at(-1)?.focusId).toBe(
+ PageFocusId.AiChatInbox,
+ );
+ });
+
+ act(() => {
+ jotaiStore.set(focusStackState.atom, [
+ ...jotaiStore.get(focusStackState.atom),
+ {
+ focusId: 'chat-menu',
+ componentInstance: {
+ componentType: FocusComponentType.DROPDOWN,
+ componentInstanceId: 'chat-menu',
+ },
+ globalHotkeysConfig: {
+ enableGlobalHotkeysWithModifiers: true,
+ enableGlobalHotkeysConflictingWithKeyboard: false,
+ },
+ },
+ ]);
+ });
+ act(() =>
+ navigateMainPage?.('/inbox/6f1c2b0e-7a4d-4e8b-9c3f-2d5a1b8e7c60'),
+ );
+
+ await waitFor(() => {
+ expect(jotaiStore.get(focusStackState.atom).at(-1)?.focusId).toBe(
+ 'chat-menu',
+ );
+ });
+ });
+
+ it('should give the inbox global hotkeys back once a panel kept open from settings closes', async () => {
+ renderPageChangeEffect();
+
+ act(() => navigateMainPage?.('/settings/profile'));
+ await waitFor(() => {
+ expect(jotaiStore.get(focusStackState.atom).at(-1)?.focusId).toBe(
+ PageFocusId.Settings,
+ );
+ });
+
+ const sidePanelFocusStackItem = {
+ focusId: 'side-panel',
+ componentInstance: {
+ componentType: FocusComponentType.SIDE_PANEL,
+ componentInstanceId: 'side-panel',
+ },
+ globalHotkeysConfig: {
+ enableGlobalHotkeysWithModifiers: true,
+ enableGlobalHotkeysConflictingWithKeyboard: false,
+ },
+ };
+
+ openSidePanelWith([RECORD_PAGE]);
+ act(() => {
+ jotaiStore.set(focusStackState.atom, [
+ ...jotaiStore.get(focusStackState.atom),
+ sidePanelFocusStackItem,
+ ]);
+ });
+ act(() => navigateMainPage?.('/inbox'));
+
+ await waitFor(() => {
+ expect(
+ jotaiStore.get(focusStackState.atom).map(({ focusId }) => focusId),
+ ).toEqual([PageFocusId.AiChatInbox, 'side-panel']);
+ });
+
+ act(() => {
+ jotaiStore.set(
+ focusStackState.atom,
+ jotaiStore
+ .get(focusStackState.atom)
+ .filter(({ focusId }) => focusId !== 'side-panel'),
+ );
+ });
+
+ expect(
+ jotaiStore.get(currentGlobalHotkeysConfigSelector.atom)
+ .enableGlobalHotkeysConflictingWithKeyboard,
+ ).toBe(true);
+ });
});
diff --git a/packages/twenty-front/src/modules/object-record/record-selection/components/RecordSelectionDragSelect.tsx b/packages/twenty-front/src/modules/object-record/record-selection/components/RecordSelectionDragSelect.tsx
index dd15b492036..0d98d58da3b 100644
--- a/packages/twenty-front/src/modules/object-record/record-selection/components/RecordSelectionDragSelect.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-selection/components/RecordSelectionDragSelect.tsx
@@ -2,9 +2,11 @@ import { useStore } from 'jotai';
import { type RefObject, useCallback } from 'react';
import { isRecordSelectedComponentFamilyState } from '@/object-record/record-selection/states/isRecordSelectedComponentFamilyState';
+import { recordSelectionRangeComponentState } from '@/object-record/record-selection/states/recordSelectionRangeComponentState';
import { DragSelect } from '@/ui/utilities/drag-select/components/DragSelect';
import { RECORD_INDEX_DRAG_SELECT_BOUNDARY_CLASS } from '@/ui/utilities/drag-select/constants/RecordIndexDragSelectBoundaryClass';
import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';
+import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';
type RecordSelectionDragSelectProps = {
selectableItemsContainerRef: RefObject<HTMLElement | null>;
@@ -21,6 +23,14 @@ export const RecordSelectionDragSelect = ({
const isRecordSelectedFamilyState = useAtomComponentFamilyStateCallbackState(
isRecordSelectedComponentFamilyState,
);
+ const recordSelectionRange = useAtomComponentStateCallbackState(
+ recordSelectionRangeComponentState,
+ );
+
+ const handleDragSelectionStart = () => {
+ store.set(recordSelectionRange, null);
+ onDragSelectionStart?.();
+ };
const handleDragSelectionChange = useCallback(
(recordId: string, isSelected: boolean) => {
@@ -62,7 +72,7 @@ export const RecordSelectionDragSelect = ({
return (
<DragSelect
selectableItemsContainerRef={selectableItemsContainerRef}
- onDragSelectionStart={onDragSelectionStart}
+ onDragSelectionStart={handleDragSelectionStart}
onDragSelectionChange={handleDragSelectionChange}
onDragSelectionEnd={handleDragSelectionEnd}
selectionBoundaryClass={RECORD_INDEX_DRAG_SELECT_BOUNDARY_CLASS}
diff --git a/packages/twenty-front/src/modules/object-record/record-selection/hooks/__tests__/useRecordSelectionArrowKeyNavigation.test.tsx b/packages/twenty-front/src/modules/object-record/record-selection/hooks/__tests__/useRecordSelectionArrowKeyNavigation.test.tsx
new file mode 100644
index 00000000000..075f0cdae32
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-selection/hooks/__tests__/useRecordSelectionArrowKeyNavigation.test.tsx
@@ -0,0 +1,178 @@
+import { act, renderHook } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+import { Key } from 'ts-key-enum';
+
+import { recordIndexRecordIdsByGroupComponentFamilyState } from '@/object-record/record-index/states/recordIndexRecordIdsByGroupComponentFamilyState';
+import { NO_RECORD_GROUP_FAMILY_KEY } from '@/object-record/record-index/states/selectors/recordIndexAllRecordIdsComponentSelector';
+import { useRecordSelectionArrowKeyNavigation } from '@/object-record/record-selection/hooks/useRecordSelectionArrowKeyNavigation';
+import { RecordSelectionComponentInstanceContext } from '@/object-record/record-selection/states/contexts/RecordSelectionComponentInstanceContext';
+import { selectedRecordIdsComponentSelector } from '@/object-record/record-selection/states/selectors/selectedRecordIdsComponentSelector';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+
+const instanceId = 'record-index-id';
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>
+ <RecordSelectionComponentInstanceContext.Provider value={{ instanceId }}>
+ {children}
+ </RecordSelectionComponentInstanceContext.Provider>
+ </JotaiProvider>
+);
+
+const getSelectedRecordIds = () =>
+ jotaiStore.get(
+ selectedRecordIdsComponentSelector.selectorFamily({ instanceId }),
+ );
+
+const pressArrowKey = (
+ navigateWithArrowKey: (keyboardEvent: KeyboardEvent) => void,
+ key: Key.ArrowUp | Key.ArrowDown,
+ shiftKey = false,
+) =>
+ act(() =>
+ navigateWithArrowKey(new KeyboardEvent('keydown', { key, shiftKey })),
+ );
+
+const renderArrowKeyNavigation = ({
+ activeRecordId,
+ container = null,
+}: {
+ activeRecordId?: string;
+ container?: HTMLElement | null;
+}) => {
+ const onActiveRecordChange = jest.fn();
+ const onEndReached = jest.fn();
+ const { result } = renderHook(
+ () =>
+ useRecordSelectionArrowKeyNavigation({
+ selectableItemsContainerRef: { current: container },
+ activeRecordId,
+ onActiveRecordChange,
+ onEndReached,
+ }),
+ { wrapper: Wrapper },
+ );
+
+ return {
+ navigateWithArrowKey: (keyboardEvent: KeyboardEvent) =>
+ result.current.navigateWithArrowKey(keyboardEvent),
+ onActiveRecordChange,
+ onEndReached,
+ };
+};
+
+const renderSelectableItems = (recordIds: string[]) => {
+ const container = document.createElement('div');
+
+ for (const recordId of recordIds) {
+ const item = document.createElement('div');
+
+ item.dataset.selectableId = recordId;
+ item.scrollIntoView = jest.fn();
+ container.appendChild(item);
+ }
+
+ document.body.appendChild(container);
+
+ return container;
+};
+
+describe('useRecordSelectionArrowKeyNavigation', () => {
+ beforeEach(() => {
+ resetJotaiStore();
+ document.body.innerHTML = '';
+ jotaiStore.set(
+ recordIndexRecordIdsByGroupComponentFamilyState.atomFamily({
+ instanceId,
+ familyKey: NO_RECORD_GROUP_FAMILY_KEY,
+ }),
+ ['a', 'b', 'c', 'd', 'e'],
+ );
+ });
+
+ it('should move to the record next to the active one', () => {
+ const { navigateWithArrowKey, onActiveRecordChange } =
+ renderArrowKeyNavigation({ activeRecordId: 'c' });
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown);
+ expect(onActiveRecordChange).toHaveBeenLastCalledWith('d');
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowUp);
+ expect(onActiveRecordChange).toHaveBeenLastCalledWith('b');
+ });
+
+ it('should start from the first record when none is active', () => {
+ const { navigateWithArrowKey, onActiveRecordChange } =
+ renderArrowKeyNavigation({});
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown);
+
+ expect(onActiveRecordChange).toHaveBeenCalledWith('a');
+ });
+
+ it('should stay on the first record', () => {
+ const { navigateWithArrowKey, onActiveRecordChange } =
+ renderArrowKeyNavigation({ activeRecordId: 'a' });
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowUp);
+
+ expect(onActiveRecordChange).not.toHaveBeenCalled();
+ });
+
+ it('should report going past the last record', () => {
+ const { navigateWithArrowKey, onActiveRecordChange, onEndReached } =
+ renderArrowKeyNavigation({ activeRecordId: 'e' });
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown);
+
+ expect(onActiveRecordChange).not.toHaveBeenCalled();
+ expect(onEndReached).toHaveBeenCalled();
+ });
+
+ it('should extend and shrink the selection from the active record', () => {
+ const { navigateWithArrowKey, onActiveRecordChange } =
+ renderArrowKeyNavigation({ activeRecordId: 'b' });
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown, true);
+ expect(getSelectedRecordIds()).toEqual(['b', 'c']);
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown, true);
+ expect(getSelectedRecordIds()).toEqual(['b', 'c', 'd']);
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowUp, true);
+ expect(getSelectedRecordIds()).toEqual(['b', 'c']);
+
+ expect(onActiveRecordChange).not.toHaveBeenCalled();
+ });
+
+ it('should clear the selection and move on from its end', () => {
+ const { navigateWithArrowKey, onActiveRecordChange } =
+ renderArrowKeyNavigation({ activeRecordId: 'a' });
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown, true);
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown, true);
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown);
+
+ expect(getSelectedRecordIds()).toEqual([]);
+ expect(onActiveRecordChange).toHaveBeenCalledWith('d');
+ });
+
+ it('should scroll the record it moves to into view', () => {
+ const container = renderSelectableItems(['a', 'b', 'c', 'd', 'e']);
+ const { navigateWithArrowKey } = renderArrowKeyNavigation({
+ activeRecordId: 'b',
+ container,
+ });
+
+ pressArrowKey(navigateWithArrowKey, Key.ArrowDown);
+
+ expect(
+ container.querySelector<HTMLElement>('[data-selectable-id="c"]')
+ ?.scrollIntoView,
+ ).toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-selection/hooks/useRecordSelectionArrowKeyNavigation.ts b/packages/twenty-front/src/modules/object-record/record-selection/hooks/useRecordSelectionArrowKeyNavigation.ts
new file mode 100644
index 00000000000..8f215cd4470
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-selection/hooks/useRecordSelectionArrowKeyNavigation.ts
@@ -0,0 +1,127 @@
+import { useStore } from 'jotai';
+import { type RefObject, useCallback } from 'react';
+import { Key } from 'ts-key-enum';
+import { isDefined } from 'twenty-shared/utils';
+
+import { recordIndexDisplayedRecordIdsComponentSelector } from '@/object-record/record-index/states/selectors/recordIndexDisplayedRecordIdsComponentSelector';
+import { useResetRecordSelection } from '@/object-record/record-selection/hooks/useResetRecordSelection';
+import { useToggleRecordSelection } from '@/object-record/record-selection/hooks/useToggleRecordSelection';
+import { RecordSelectionComponentInstanceContext } from '@/object-record/record-selection/states/contexts/RecordSelectionComponentInstanceContext';
+import { isRecordSelectedComponentFamilyState } from '@/object-record/record-selection/states/isRecordSelectedComponentFamilyState';
+import { recordSelectionRangeComponentState } from '@/object-record/record-selection/states/recordSelectionRangeComponentState';
+import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
+import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';
+import { useAtomComponentSelectorCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorCallbackState';
+import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';
+
+type UseRecordSelectionArrowKeyNavigationProps = {
+ selectableItemsContainerRef: RefObject<HTMLElement | null>;
+ activeRecordId: string | undefined;
+ onActiveRecordChange: (recordId: string) => void;
+ onEndReached: () => void;
+};
+
+export const useRecordSelectionArrowKeyNavigation = ({
+ selectableItemsContainerRef,
+ activeRecordId,
+ onActiveRecordChange,
+ onEndReached,
+}: UseRecordSelectionArrowKeyNavigationProps) => {
+ const instanceId = useAvailableComponentInstanceIdOrThrow(
+ RecordSelectionComponentInstanceContext,
+ );
+
+ const displayedRecordIds = useAtomComponentSelectorCallbackState(
+ recordIndexDisplayedRecordIdsComponentSelector,
+ instanceId,
+ );
+
+ const recordSelectionRange = useAtomComponentStateCallbackState(
+ recordSelectionRangeComponentState,
+ instanceId,
+ );
+
+ const isRecordSelectedFamilyState = useAtomComponentFamilyStateCallbackState(
+ isRecordSelectedComponentFamilyState,
+ instanceId,
+ );
+
+ const { toggleRecordSelection } = useToggleRecordSelection(instanceId);
+ const { resetRecordSelection } = useResetRecordSelection(instanceId);
+
+ const store = useStore();
+
+ const navigateWithArrowKey = useCallback(
+ (keyboardEvent: KeyboardEvent) => {
+ const recordIds = store.get(displayedRecordIds);
+ const range = store.get(recordSelectionRange);
+
+ const cursorRecordId = [range?.headRecordId, activeRecordId].find(
+ (recordId) => isDefined(recordId) && recordIds.includes(recordId),
+ );
+
+ const cursorIndex = isDefined(cursorRecordId)
+ ? recordIds.indexOf(cursorRecordId)
+ : -1;
+
+ const targetRecordId =
+ cursorIndex === -1
+ ? recordIds[0]
+ : recordIds[
+ cursorIndex + (keyboardEvent.key === Key.ArrowUp ? -1 : 1)
+ ];
+
+ if (!isDefined(targetRecordId)) {
+ if (keyboardEvent.key === Key.ArrowDown) {
+ onEndReached();
+ }
+
+ return;
+ }
+
+ if (!keyboardEvent.shiftKey) {
+ resetRecordSelection();
+ onActiveRecordChange(targetRecordId);
+ } else if (isDefined(range) && range.headRecordId === cursorRecordId) {
+ toggleRecordSelection({
+ recordId: targetRecordId,
+ shouldSelectRange: true,
+ });
+ } else {
+ const anchorRecordId = cursorRecordId ?? targetRecordId;
+
+ store.set(isRecordSelectedFamilyState(anchorRecordId), true);
+ store.set(recordSelectionRange, {
+ anchorRecordId,
+ headRecordId: anchorRecordId,
+ addedRecordIds: [],
+ });
+
+ if (anchorRecordId !== targetRecordId) {
+ toggleRecordSelection({
+ recordId: targetRecordId,
+ shouldSelectRange: true,
+ });
+ }
+ }
+
+ selectableItemsContainerRef.current
+ ?.querySelector(`[data-selectable-id="${targetRecordId}"]`)
+ ?.scrollIntoView({ block: 'nearest' });
+ },
+ [
+ activeRecordId,
+ displayedRecordIds,
+ isRecordSelectedFamilyState,
+ onActiveRecordChange,
+ onEndReached,
+ recordSelectionRange,
+ resetRecordSelection,
+ selectableItemsContainerRef,
+ store,
+ toggleRecordSelection,
+ ],
+ );
+
+ return { navigateWithArrowKey };
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-selection/hooks/useToggleRecordSelection.ts b/packages/twenty-front/src/modules/object-record/record-selection/hooks/useToggleRecordSelection.ts
index 3ba15f5a322..398b0da4f4e 100644
--- a/packages/twenty-front/src/modules/object-record/record-selection/hooks/useToggleRecordSelection.ts
+++ b/packages/twenty-front/src/modules/object-record/record-selection/hooks/useToggleRecordSelection.ts
@@ -80,6 +80,7 @@ export const useToggleRecordSelection = (recordIndexId?: string) => {
store.set(recordSelectionRange, {
anchorRecordId: range.anchorRecordId,
+ headRecordId: recordId,
addedRecordIds,
});
@@ -91,7 +92,13 @@ export const useToggleRecordSelection = (recordIndexId?: string) => {
store.set(isRecordSelectedFamilyState(recordId), isSelected);
store.set(
recordSelectionRange,
- isSelected ? { anchorRecordId: recordId, addedRecordIds: [] } : null,
+ isSelected
+ ? {
+ anchorRecordId: recordId,
+ headRecordId: recordId,
+ addedRecordIds: [],
+ }
+ : null,
);
},
[
diff --git a/packages/twenty-front/src/modules/object-record/record-selection/states/recordSelectionRangeComponentState.ts b/packages/twenty-front/src/modules/object-record/record-selection/states/recordSelectionRangeComponentState.ts
index 1b99685dca3..54b8ce92240 100644
--- a/packages/twenty-front/src/modules/object-record/record-selection/states/recordSelectionRangeComponentState.ts
+++ b/packages/twenty-front/src/modules/object-record/record-selection/states/recordSelectionRangeComponentState.ts
@@ -3,6 +3,7 @@ import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/creat
export const recordSelectionRangeComponentState = createAtomComponentState<{
anchorRecordId: string;
+ headRecordId: string;
addedRecordIds: string[];
} | null>({
key: 'recordSelectionRangeComponentState',
diff --git a/packages/twenty-front/src/modules/types/PageFocusId.ts b/packages/twenty-front/src/modules/types/PageFocusId.ts
index 3956eb97383..b81e181e154 100644
--- a/packages/twenty-front/src/modules/types/PageFocusId.ts
+++ b/packages/twenty-front/src/modules/types/PageFocusId.ts
@@ -9,4 +9,5 @@ export enum PageFocusId {
RecordShowPage = 'record-show-page',
RecordIndex = 'record-index',
PageLayoutPage = 'page-layout-page',
+ AiChatInbox = 'ai-chat-inbox',
}
diff --git a/packages/twenty-front/src/modules/ui/utilities/focus/hooks/useResetFocusStackToFocusItem.ts b/packages/twenty-front/src/modules/ui/utilities/focus/hooks/useResetFocusStackToFocusItem.ts
index 385bee64477..511b63c9ab3 100644
--- a/packages/twenty-front/src/modules/ui/utilities/focus/hooks/useResetFocusStackToFocusItem.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/focus/hooks/useResetFocusStackToFocusItem.ts
@@ -2,6 +2,7 @@ import { useCallback } from 'react';
import { DEBUG_FOCUS_STACK } from '@/ui/utilities/focus/constants/DebugFocusStack';
import { focusStackState } from '@/ui/utilities/focus/states/focusStackState';
+import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
import { type FocusStackItem } from '@/ui/utilities/focus/types/FocusStackItem';
import { useStore } from 'jotai';
import { logDebug } from '~/utils/logDebug';
@@ -10,8 +11,26 @@ export const useResetFocusStackToFocusItem = () => {
const store = useStore();
const resetFocusStackToFocusItem = useCallback(
- ({ focusStackItem }: { focusStackItem: FocusStackItem }) => {
- store.set(focusStackState.atom, [focusStackItem]);
+ ({
+ focusStackItem,
+ shouldKeepItemsAbovePage = false,
+ }: {
+ focusStackItem: FocusStackItem;
+ shouldKeepItemsAbovePage?: boolean;
+ }) => {
+ const focusStackItemsAbovePage = shouldKeepItemsAbovePage
+ ? store
+ .get(focusStackState.atom)
+ .filter(
+ ({ componentInstance }) =>
+ componentInstance.componentType !== FocusComponentType.PAGE,
+ )
+ : [];
+
+ store.set(focusStackState.atom, [
+ focusStackItem,
+ ...focusStackItemsAbovePage,
+ ]);
if (DEBUG_FOCUS_STACK) {
logDebug(`DEBUG: reset focus stack to focus item`, {
diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx
index 5e8516bb17c..888b2526637 100644
--- a/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx
@@ -2,6 +2,7 @@ import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
import { type MouseEvent, useId, useRef } from 'react';
import { Navigate, useParams } from 'react-router-dom';
+import { Key } from 'ts-key-enum';
import { AppPath } from 'twenty-shared/types';
import { getAppPath, isDefined, isValidUuid } from 'twenty-shared/utils';
import { IconButton } from 'twenty-ui/components/input';
@@ -20,11 +21,13 @@ import { AiChatInboxThreadList } from '@/ai/components/AiChatInboxThreadList';
import { AiChatInboxThreadPagination } from '@/ai/components/AiChatInboxThreadPagination';
import { useChatThreads } from '@/ai/hooks/useChatThreads';
import { useIsAiChatInboxSplitView } from '@/ai/hooks/useIsAiChatInboxSplitView';
+import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';
import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';
import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';
import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';
import { RecordSelectionDragSelect } from '@/object-record/record-selection/components/RecordSelectionDragSelect';
import { RecordSelectionRecordIdsEffect } from '@/object-record/record-selection/components/RecordSelectionRecordIdsEffect';
+import { useRecordSelectionArrowKeyNavigation } from '@/object-record/record-selection/hooks/useRecordSelectionArrowKeyNavigation';
import { useResetRecordSelection } from '@/object-record/record-selection/hooks/useResetRecordSelection';
import { useToggleRecordSelection } from '@/object-record/record-selection/hooks/useToggleRecordSelection';
import { RecordSelectionComponentInstanceContext } from '@/object-record/record-selection/states/contexts/RecordSelectionComponentInstanceContext';
@@ -33,6 +36,7 @@ import { AnimatedPlaceholder } from '@/ui/feedback/empty-state/components/Animat
import { EmptyState } from '@/ui/feedback/empty-state/components/EmptyState';
import { PageCardHeader } from '@/ui/layout/page/components/PageCardHeader';
import { PageCardLayout } from '@/ui/layout/page/components/PageCardLayout';
+import { useGlobalHotkeys } from '@/ui/utilities/hotkey/hooks/useGlobalHotkeys';
import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { FeatureFlagKey } from '~/generated-metadata/graphql';
@@ -84,6 +88,7 @@ const AiChatInboxPageContent = () => {
const { toggleRecordSelection } = useToggleRecordSelection();
const threadListContainerRef = useRef<HTMLDivElement>(null);
const { resetRecordSelection } = useResetRecordSelection();
+ const { fetchMoreAgentChatThreads } = useRefreshAgentChatThreads();
// Rows hold a menu and a rename input, which a link cannot contain
const selectThread = (nextThreadId: string | null) =>
@@ -120,6 +125,13 @@ const AiChatInboxPageContent = () => {
toggleRecordSelection({ recordId: id, shouldSelectRange: event.shiftKey });
};
+ const { navigateWithArrowKey } = useRecordSelectionArrowKeyNavigation({
+ selectableItemsContainerRef: threadListContainerRef,
+ activeRecordId: selectedThreadId,
+ onActiveRecordChange: selectThread,
+ onEndReached: fetchMoreAgentChatThreads,
+ });
+
const handleThreadCheckboxClick = (
{ id }: AgentChatThreadRecord,
event: MouseEvent<HTMLDivElement>,
@@ -145,6 +157,20 @@ const AiChatInboxPageContent = () => {
const openThreadIds =
isDefined(selectedThreadId) && !isSelectionShown ? [selectedThreadId] : [];
+ useGlobalHotkeys({
+ keys: [
+ Key.ArrowUp,
+ Key.ArrowDown,
+ ...(isListShown
+ ? [`${Key.Shift}+${Key.ArrowUp}`, `${Key.Shift}+${Key.ArrowDown}`]
+ : []),
+ ],
+ callback: navigateWithArrowKey,
+ containsModifier: false,
+ dependencies: [navigateWithArrowKey],
+ options: { enableOnContentEditable: false, enableOnFormTags: false },
+ });
+
return (
<StyledInbox>
<RecordSelectionRecordIdsEffect records={threads} />
diff --git a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx
index 73d419596bb..c73261c1a09 100644
--- a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx
@@ -88,7 +88,7 @@ jest.mock('@/ai/components/AiChatThreadList', () => ({
) => void;
}) =>
threads.map((thread) => (
- <div key={thread.id}>
+ <div key={thread.id} data-selectable-id={thread.id}>
<input
type="checkbox"
aria-label={`Select ${thread.title}`}
@@ -227,6 +227,10 @@ const getTargetedThreadIds = (contextStoreInstanceId: string) =>
);
describe('AiChatInboxPage', () => {
+ beforeAll(() => {
+ Element.prototype.scrollIntoView = jest.fn();
+ });
+
beforeEach(() => {
// The list filter is kept in local storage
localStorage.clear();
@@ -438,6 +442,31 @@ describe('AiChatInboxPage', () => {
expect(screen.getByText('3 chats selected')).toBeInTheDocument();
});
+ it('moves between chats with the arrow keys', async () => {
+ renderInbox();
+
+ await userEvent.keyboard('{ArrowDown}{ArrowDown}');
+ expect(screen.getByText(`Chat page ${thirdThread.id}`)).toBeInTheDocument();
+
+ await userEvent.keyboard('{ArrowUp}');
+ expect(
+ screen.getByText(`Chat page ${secondThread.id}`),
+ ).toBeInTheDocument();
+ });
+
+ it('selects chats from the one on screen with shift+arrow keys', async () => {
+ renderInbox();
+
+ await userEvent.keyboard('{Shift>}{ArrowDown}{ArrowDown}{/Shift}');
+ expect(screen.getByText('3 chats selected')).toBeInTheDocument();
+
+ await userEvent.keyboard('{Shift>}{ArrowUp}{/Shift}');
+ expect(screen.getByText('2 chats selected')).toBeInTheDocument();
+
+ await userEvent.keyboard('{ArrowDown}');
+ expect(screen.getByText(`Chat page ${thirdThread.id}`)).toBeInTheDocument();
+ });
+
it('goes back to the chat on screen once the selection is cleared', () => {
renderInbox();
@@ -530,6 +559,23 @@ describe('AiChatInboxPage', () => {
).toBeInTheDocument();
});
+ it('moves between chats with the arrow keys without selecting any from the chat', async () => {
+ renderInbox(`/inbox/${firstThread.id}`);
+
+ await userEvent.keyboard('{Shift>}{ArrowDown}{/Shift}');
+
+ expect(
+ screen.getByText(`Chat page ${firstThread.id}`),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/selected/)).not.toBeInTheDocument();
+
+ await userEvent.keyboard('{ArrowDown}');
+
+ expect(
+ screen.getByText(`Chat page ${secondThread.id}`),
+ ).toBeInTheDocument();
+ });
+
it('selects chats in the list, with the command menu acting on them', () => {
renderInbox('/inbox');