Skip to content

The open alternative to Salesforce, designed for AI.

feat(email-composer): reorder, move and multi-select recipient chips (#23947)

Félix Malfait4bb17535442c
diff --git a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
index 354f06a9bc1..56c413aa120 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
@@ -1,11 +1,20 @@
import { useQuery } from '@apollo/client/react';
+import { DragDropProvider } from '@dnd-kit/react';
import { styled } from '@linaria/react';
import { EmailAttachmentsField } from '@/activities/emails/components/EmailAttachmentsField';
import { EmailRecipientsFieldInput } from '@/activities/emails/recipients/components/EmailRecipientsFieldInput';
+import { useEmailRecipientsDragAndDrop } from '@/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop';
import { type EmailComposerContextRecord } from '@/activities/emails/recipients/types/EmailComposerContextRecord';
+import { type EmailRecipientDragData } from '@/activities/emails/recipients/types/EmailRecipientDragData';
+import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/types/EmailRecipientsFieldId';
import { getEmailRecipientKey } from '@/activities/emails/recipients/utils/getEmailRecipientKey';
+import { type EmailRecipientsByFieldId } from '@/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields';
import { type EmailComposerState } from '@/activities/emails/types/EmailComposerState';
+import { isDefined } from 'twenty-shared/utils';
+import { DND_KIT_PROVIDER_PLUGINS_WITHOUT_DROP_ANIMATION } from '@/ui/utilities/drag-and-drop/constants/DndKitProviderPluginsWithoutDropAnimation';
+import { DND_KIT_SENSORS } from '@/ui/utilities/drag-and-drop/constants/DndKitSensors';
+import { DragDropItemDndContext } from '@/ui/utilities/drag-and-drop/context/DragDropItemDndContext';
import { INLINE_EMAIL_BODY_EDITOR_PROFILE } from '@/activities/emails/editor/constants/InlineEmailBodyEditorProfile';
import { useUploadEmailImage } from '@/activities/emails/hooks/useUploadEmailImage';
import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
@@ -76,6 +85,39 @@ export const EmailComposerFields = ({
...composerState.bcc,
].map((recipient) => getEmailRecipientKey(recipient.address));
+ const recipientsByFieldId: EmailRecipientsByFieldId = {
+ to: composerState.to,
+ cc: composerState.cc,
+ bcc: composerState.bcc,
+ };
+
+ const handleRecipientsByFieldIdChange = (
+ nextRecipientsByFieldId: EmailRecipientsByFieldId,
+ ) => {
+ composerState.setTo(nextRecipientsByFieldId.to);
+ composerState.setCc(nextRecipientsByFieldId.cc);
+ composerState.setBcc(nextRecipientsByFieldId.bcc);
+
+ if (
+ nextRecipientsByFieldId.cc.length > 0 ||
+ nextRecipientsByFieldId.bcc.length > 0
+ ) {
+ composerState.setShowCcBcc(true);
+ }
+ };
+
+ const { contextValues, draggedRecipients, handlers } =
+ useEmailRecipientsDragAndDrop({
+ recipientsByFieldId,
+ onRecipientsByFieldIdChange: handleRecipientsByFieldIdChange,
+ });
+
+ const isDraggingRecipients = isDefined(draggedRecipients);
+
+ const getDraggedIndicesForField = (fieldId: EmailRecipientsFieldId) =>
+ draggedRecipients?.fieldId === fieldId ? draggedRecipients.indices : null;
+ const areCcBccFieldsVisible = composerState.showCcBcc || isDraggingRecipients;
+
return (
<StyledFieldsContainer>
{hasMultipleAccounts && (
@@ -88,44 +130,62 @@ export const EmailComposerFields = ({
onChange={(value) => composerState.setConnectedAccountId(value)}
/>
)}
- <StyledToRow>
- <EmailRecipientsFieldInput
- label={t`To`}
- placeholder={t`Recipients`}
- recipients={composerState.to}
- onChange={composerState.setTo}
- onSubmit={composerState.handleSend}
- excludedSuggestionKeys={allRecipientKeys}
- contextRecord={contextRecord}
- />
- {!composerState.showCcBcc && (
- <StyledCcBccToggle onClick={() => composerState.setShowCcBcc(true)}>
- {t`Cc/Bcc`}
- </StyledCcBccToggle>
- )}
- </StyledToRow>
- {composerState.showCcBcc && (
- <>
- <EmailRecipientsFieldInput
- label={t`Cc`}
- placeholder={t`Cc`}
- recipients={composerState.cc}
- onChange={composerState.setCc}
- onSubmit={composerState.handleSend}
- excludedSuggestionKeys={allRecipientKeys}
- contextRecord={contextRecord}
- />
- <EmailRecipientsFieldInput
- label={t`Bcc`}
- placeholder={t`Bcc`}
- recipients={composerState.bcc}
- onChange={composerState.setBcc}
- onSubmit={composerState.handleSend}
- excludedSuggestionKeys={allRecipientKeys}
- contextRecord={contextRecord}
- />
- </>
- )}
+ <DragDropItemDndContext.Provider value={contextValues}>
+ <DragDropProvider<EmailRecipientDragData>
+ sensors={DND_KIT_SENSORS}
+ plugins={DND_KIT_PROVIDER_PLUGINS_WITHOUT_DROP_ANIMATION}
+ onDragStart={handlers.onDragStart}
+ onDragMove={handlers.onDragMove}
+ onDragEnd={handlers.onDragEnd}
+ >
+ <StyledToRow>
+ <EmailRecipientsFieldInput
+ fieldId="to"
+ draggedSourceIndices={getDraggedIndicesForField('to')}
+ label={t`To`}
+ placeholder={t`Recipients`}
+ recipients={composerState.to}
+ onChange={composerState.setTo}
+ onSubmit={composerState.handleSend}
+ excludedSuggestionKeys={allRecipientKeys}
+ contextRecord={contextRecord}
+ />
+ {!areCcBccFieldsVisible && (
+ <StyledCcBccToggle
+ onClick={() => composerState.setShowCcBcc(true)}
+ >
+ {t`Cc/Bcc`}
+ </StyledCcBccToggle>
+ )}
+ </StyledToRow>
+ {areCcBccFieldsVisible && (
+ <>
+ <EmailRecipientsFieldInput
+ fieldId="cc"
+ draggedSourceIndices={getDraggedIndicesForField('cc')}
+ label={t`Cc`}
+ placeholder={t`Cc`}
+ recipients={composerState.cc}
+ onChange={composerState.setCc}
+ onSubmit={composerState.handleSend}
+ excludedSuggestionKeys={allRecipientKeys}
+ contextRecord={contextRecord}
+ />
+ <EmailRecipientsFieldInput
+ fieldId="bcc"
+ draggedSourceIndices={getDraggedIndicesForField('bcc')}
+ label={t`Bcc`}
+ placeholder={t`Bcc`}
+ recipients={composerState.bcc}
+ onChange={composerState.setBcc}
+ onSubmit={composerState.handleSend}
+ excludedSuggestionKeys={allRecipientKeys}
+ contextRecord={contextRecord}
+ />
+ </>
+ )}
+ </DragDropProvider>
+ </DragDropItemDndContext.Provider>
{composerState.exceedsRecipientLimit && (
<StyledRecipientLimitWarning>
{t`Too many recipients (${composerState.recipientCount}/${composerState.maxRecipients}).`}
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx
new file mode 100644
index 00000000000..1308b355b23
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx
@@ -0,0 +1,142 @@
+import { styled } from '@linaria/react';
+import { type MouseEvent } from 'react';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+import { EMAIL_RECIPIENT_DND_TYPE } from '@/activities/emails/recipients/constants/EmailRecipientDndType';
+import { EmailRecipientsFieldChip } from '@/activities/emails/recipients/components/EmailRecipientsFieldChip';
+import { type EmailRecipientResolution } from '@/activities/emails/recipients/hooks/useEmailRecipientsResolution';
+import { type EmailRecipientDragData } from '@/activities/emails/recipients/types/EmailRecipientDragData';
+import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';
+import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/types/EmailRecipientsFieldId';
+import { DragDropItemSortableCell } from '@/ui/utilities/drag-and-drop/components/DragDropItemSortableCell';
+
+export type EmailRecipientChipDropEdge = 'before' | 'after' | null;
+
+const DROP_INDICATOR_WIDTH = '2px';
+// Centers the bar in the 4px chip gap: half the gap plus half the bar.
+const DROP_INDICATOR_OFFSET = '-3px';
+
+// The insertion bar is absolutely positioned so showing it never reflows the
+// wrapping chip row mid-drag.
+const StyledChipDropZone = styled.div`
+ position: relative;
+
+ &::before,
+ &::after {
+ background-color: ${themeCssVariables.color.blue};
+ border-radius: ${themeCssVariables.border.radius.sm};
+ bottom: 0;
+ content: '';
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ transition: opacity 120ms ease-out;
+ width: ${DROP_INDICATOR_WIDTH};
+ }
+
+ &::before {
+ left: ${DROP_INDICATOR_OFFSET};
+ }
+
+ &::after {
+ right: ${DROP_INDICATOR_OFFSET};
+ }
+
+ &[data-drop-edge='before']::before,
+ &[data-drop-edge='after']::after {
+ opacity: 1;
+ }
+`;
+
+type EmailRecipientsFieldChipCellProps = {
+ chipId: string;
+ chipIndex: number;
+ dropdownId: string;
+ dropEdge: EmailRecipientChipDropEdge;
+ fieldId: EmailRecipientsFieldId;
+ isFlashing: boolean;
+ isInvalid: boolean;
+ isSelected: boolean;
+ onEdit: () => void;
+ onExtendSelectionTo: () => void;
+ onRemove: () => void;
+ onToggleSelection: () => void;
+ recipient: EmailRecipient;
+ resolution: EmailRecipientResolution | undefined;
+ selectedIndices: number[];
+ sortableId: string;
+};
+
+export const EmailRecipientsFieldChipCell = ({
+ chipId,
+ chipIndex,
+ dropdownId,
+ dropEdge,
+ fieldId,
+ isFlashing,
+ isInvalid,
+ isSelected,
+ onEdit,
+ onExtendSelectionTo,
+ onRemove,
+ onToggleSelection,
+ recipient,
+ resolution,
+ selectedIndices,
+ sortableId,
+}: EmailRecipientsFieldChipCellProps) => {
+ const dragData: EmailRecipientDragData = {
+ fieldId,
+ index: chipIndex,
+ selectedIndices,
+ };
+
+ // Intercepting in the capture phase keeps a modified click from reaching the
+ // chip's dropdown, so shift/cmd click selects instead of opening the menu.
+ const handleClickCapture = (event: MouseEvent<HTMLDivElement>) => {
+ if (event.shiftKey) {
+ event.preventDefault();
+ event.stopPropagation();
+ onExtendSelectionTo();
+ return;
+ }
+
+ if (event.metaKey || event.ctrlKey) {
+ event.preventDefault();
+ event.stopPropagation();
+ onToggleSelection();
+ }
+ };
+
+ return (
+ <DragDropItemSortableCell
+ accept={EMAIL_RECIPIENT_DND_TYPE}
+ data={dragData}
+ group={fieldId}
+ id={sortableId}
+ index={chipIndex}
+ orientation="vertical"
+ type={EMAIL_RECIPIENT_DND_TYPE}
+ >
+ <StyledChipDropZone
+ data-drop-edge={dropEdge ?? undefined}
+ onClickCapture={handleClickCapture}
+ // Keeps focus in the text input so chip keyboard navigation survives a
+ // click on a chip.
+ onMouseDown={(event) => event.preventDefault()}
+ >
+ <EmailRecipientsFieldChip
+ chipId={chipId}
+ dropdownId={dropdownId}
+ recipient={recipient}
+ resolution={resolution}
+ isInvalid={isInvalid}
+ selected={isSelected}
+ isFlashing={isFlashing}
+ onEdit={onEdit}
+ onRemove={onRemove}
+ />
+ </StyledChipDropZone>
+ </DragDropItemSortableCell>
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
index 7090b3e895f..8ab94517681 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
@@ -1,3 +1,5 @@
+import { pointerIntersection } from '@dnd-kit/collision';
+import { useDroppable } from '@dnd-kit/react';
import { styled } from '@linaria/react';
import { isNonEmptyString } from '@sniptt/guards';
import { useStore } from 'jotai';
@@ -6,6 +8,7 @@ import {
type KeyboardEvent,
type MouseEvent,
type ReactNode,
+ useContext,
useId,
useMemo,
useRef,
@@ -16,7 +19,11 @@ import { isDefined } from 'twenty-shared/utils';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { useDebouncedCallback } from 'use-debounce';
-import { EmailRecipientsFieldChip } from '@/activities/emails/recipients/components/EmailRecipientsFieldChip';
+import { EMAIL_RECIPIENT_DND_TYPE } from '@/activities/emails/recipients/constants/EmailRecipientDndType';
+import {
+ type EmailRecipientChipDropEdge,
+ EmailRecipientsFieldChipCell,
+} from '@/activities/emails/recipients/components/EmailRecipientsFieldChipCell';
import { EmailRecipientSuggestionsDropdownContent } from '@/activities/emails/recipients/components/EmailRecipientSuggestionsDropdownContent';
import { useEmailRecipientsField } from '@/activities/emails/recipients/hooks/useEmailRecipientsField';
import { useEmailRecipientsResolution } from '@/activities/emails/recipients/hooks/useEmailRecipientsResolution';
@@ -26,6 +33,7 @@ import {
} from '@/activities/emails/recipients/hooks/useEmailRecipientSuggestions';
import { type EmailComposerContextRecord } from '@/activities/emails/recipients/types/EmailComposerContextRecord';
import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';
+import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/types/EmailRecipientsFieldId';
import { getEmailRecipientKey } from '@/activities/emails/recipients/utils/getEmailRecipientKey';
import { isValidEmailRecipientAddress } from '@/activities/emails/recipients/utils/isValidEmailRecipientAddress';
import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';
@@ -38,6 +46,8 @@ import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';
import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';
import { useSelectableList } from '@/ui/layout/selectable-list/hooks/useSelectableList';
import { selectedItemIdComponentState } from '@/ui/layout/selectable-list/states/selectedItemIdComponentState';
+import { DND_KIT_COLLISION_PRIORITY } from '@/ui/utilities/drag-and-drop/constants/DndKitCollisionPriority';
+import { DragDropItemDndContext } from '@/ui/utilities/drag-and-drop/context/DragDropItemDndContext';
import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';
import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';
import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
@@ -47,11 +57,18 @@ import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/use
const SUGGESTIONS_SEARCH_DEBOUNCE_MS = 300;
-const StyledRowContainer = styled.div`
+const StyledRowContainer = styled.div<{ $isDropTarget: boolean }>`
align-content: flex-start;
align-items: center;
- background-color: ${themeCssVariables.background.transparent.lighter};
- border: 1px solid ${themeCssVariables.border.color.medium};
+ background-color: ${({ $isDropTarget }) =>
+ $isDropTarget
+ ? themeCssVariables.background.transparent.blue
+ : themeCssVariables.background.transparent.lighter};
+ border: 1px solid
+ ${({ $isDropTarget }) =>
+ $isDropTarget
+ ? themeCssVariables.color.blue
+ : themeCssVariables.border.color.medium};
border-radius: ${themeCssVariables.border.radius.md};
box-sizing: border-box;
cursor: text;
@@ -62,6 +79,9 @@ const StyledRowContainer = styled.div`
min-height: 32px;
overflow-y: auto;
padding: ${themeCssVariables.spacing[1]} ${themeCssVariables.spacing[2]};
+ transition:
+ background-color 120ms ease-out,
+ border-color 120ms ease-out;
width: 100%;
`;
@@ -84,6 +104,10 @@ const StyledInput = styled.input`
`;
type EmailRecipientsFieldInputProps = {
+ fieldId: EmailRecipientsFieldId;
+ // Indices being dragged out of this field, or null when the drag started
+ // elsewhere.
+ draggedSourceIndices: number[] | null;
label: string;
placeholder: string;
recipients: EmailRecipient[];
@@ -94,6 +118,8 @@ type EmailRecipientsFieldInputProps = {
};
export const EmailRecipientsFieldInput = ({
+ fieldId,
+ draggedSourceIndices,
label,
placeholder,
recipients,
@@ -131,7 +157,8 @@ export const EmailRecipientsFieldInput = ({
setInputValue,
editingIndex,
isEditing,
- selectedChipIndex,
+ selectedChipIndices,
+ selectionFocusIndex,
chipFlash,
commitInput,
addRecipient,
@@ -139,11 +166,28 @@ export const EmailRecipientsFieldInput = ({
beginEditingChip,
cancelEditing,
removeRecipientAtIndex,
- removeRecipientWithKeyboard,
+ removeSelectedRecipients,
clearChipSelection,
+ extendChipSelectionToIndex,
+ toggleChipSelectionAtIndex,
moveChipSelection,
+ extendChipSelection,
} = useEmailRecipientsField({ recipients, onChange });
+ const { activeDropTargetIndex, activeDroppableId } = useContext(
+ DragDropItemDndContext,
+ );
+
+ const isActiveDropField = activeDroppableId === fieldId;
+
+ const { ref: droppableRef } = useDroppable({
+ id: `${focusId}-droppable`,
+ accept: EMAIL_RECIPIENT_DND_TYPE,
+ collisionDetector: pointerIntersection,
+ collisionPriority: DND_KIT_COLLISION_PRIORITY,
+ data: { droppableId: fieldId, index: recipients.length },
+ });
+
const [suggestionsSearchInput, setSuggestionsSearchInput] = useState('');
const debouncedSetSuggestionsSearchInput = useDebouncedCallback(
setSuggestionsSearchInput,
@@ -177,6 +221,11 @@ export const EmailRecipientsFieldInput = ({
[recipients],
);
+ const selectedChipIndexSet = useMemo(
+ () => new Set(selectedChipIndices),
+ [selectedChipIndices],
+ );
+
const openSuggestions = () => {
if (!isDropdownOpen) {
openDropdown({
@@ -194,6 +243,43 @@ export const EmailRecipientsFieldInput = ({
const getChipId = (chipIndex: number) => `${focusId}-chip-${chipIndex}`;
+ // Gaps at either end of the dragged run put the chips back exactly where they
+ // came from, so marking them would promise a reorder that cannot happen.
+ const isNoOpDropGap = (gapIndex: number) => {
+ if (draggedSourceIndices === null || draggedSourceIndices.length === 0) {
+ return false;
+ }
+
+ const lowestIndex = Math.min(...draggedSourceIndices);
+ const highestIndex = Math.max(...draggedSourceIndices);
+ const isContiguousRun =
+ highestIndex - lowestIndex + 1 === draggedSourceIndices.length;
+
+ return (
+ isContiguousRun && gapIndex >= lowestIndex && gapIndex <= highestIndex + 1
+ );
+ };
+
+ const getChipDropEdge = (chipIndex: number): EmailRecipientChipDropEdge => {
+ if (
+ !isActiveDropField ||
+ activeDropTargetIndex === null ||
+ isNoOpDropGap(activeDropTargetIndex)
+ ) {
+ return null;
+ }
+
+ if (activeDropTargetIndex === chipIndex) {
+ return 'before';
+ }
+
+ // Only the trailing chip owns the gap past the end of the row.
+ return chipIndex === recipients.length - 1 &&
+ activeDropTargetIndex === recipients.length
+ ? 'after'
+ : null;
+ };
+
const scrollChipIntoView = (chipIndex: number | null) => {
if (chipIndex === null) {
return;
@@ -317,6 +403,16 @@ export const EmailRecipientsFieldInput = ({
focusInput();
};
+ const handleChipExtendSelectionTo = (chipIndex: number) => {
+ extendChipSelectionToIndex(chipIndex);
+ focusInput();
+ };
+
+ const handleChipToggleSelection = (chipIndex: number) => {
+ toggleChipSelectionAtIndex(chipIndex);
+ focusInput();
+ };
+
const handleSubmitHotkey = () => {
if (inputValue.length > 0) {
commitInputAndCloseSuggestions();
@@ -371,8 +467,8 @@ export const EmailRecipientsFieldInput = ({
}
}
- if (bufferIsEmpty && selectedChipIndex !== null) {
- handleChipEdit(selectedChipIndex);
+ if (bufferIsEmpty && selectionFocusIndex !== null) {
+ handleChipEdit(selectionFocusIndex);
return;
}
@@ -408,8 +504,8 @@ export const EmailRecipientsFieldInput = ({
event.preventDefault();
- if (selectedChipIndex !== null) {
- removeRecipientWithKeyboard();
+ if (selectedChipIndices.length > 0) {
+ removeSelectedRecipients();
return;
}
@@ -417,9 +513,9 @@ export const EmailRecipientsFieldInput = ({
return;
}
case 'Delete': {
- if (bufferIsEmpty && selectedChipIndex !== null) {
+ if (bufferIsEmpty && selectedChipIndices.length > 0) {
event.preventDefault();
- removeRecipientWithKeyboard();
+ removeSelectedRecipients();
}
return;
}
@@ -436,16 +532,20 @@ export const EmailRecipientsFieldInput = ({
}
event.preventDefault();
- scrollChipIntoView(moveChipSelection(-1));
+ scrollChipIntoView(
+ event.shiftKey ? extendChipSelection(-1) : moveChipSelection(-1),
+ );
return;
}
case 'ArrowRight': {
- if (selectedChipIndex === null) {
+ if (selectionFocusIndex === null) {
return;
}
event.preventDefault();
- scrollChipIntoView(moveChipSelection(1));
+ scrollChipIntoView(
+ event.shiftKey ? extendChipSelection(1) : moveChipSelection(1),
+ );
return;
}
case 'Escape': {
@@ -460,7 +560,7 @@ export const EmailRecipientsFieldInput = ({
return;
}
- if (selectedChipIndex !== null) {
+ if (selectedChipIndices.length > 0) {
event.preventDefault();
clearChipSelection();
}
@@ -506,22 +606,25 @@ export const EmailRecipientsFieldInput = ({
: null;
return (
- <div
+ <EmailRecipientsFieldChipCell
key={flashNonce === null ? chipKey : `${chipKey}-flash-${flashNonce}`}
- onMouseDown={(event) => event.preventDefault()}
- >
- <EmailRecipientsFieldChip
- chipId={getChipId(chipIndex)}
- dropdownId={`${focusId}-chip-menu-${chipKey}`}
- recipient={recipient}
- resolution={resolutionByRecipientKey.get(chipKey)}
- isInvalid={invalidRecipientKeys.has(chipKey)}
- selected={chipIndex === selectedChipIndex}
- isFlashing={flashNonce !== null}
- onEdit={() => handleChipEdit(chipIndex)}
- onRemove={() => handleChipRemove(chipIndex)}
- />
- </div>
+ chipId={getChipId(chipIndex)}
+ chipIndex={chipIndex}
+ dropdownId={`${focusId}-chip-menu-${chipKey}`}
+ dropEdge={getChipDropEdge(chipIndex)}
+ fieldId={fieldId}
+ isFlashing={flashNonce !== null}
+ isInvalid={invalidRecipientKeys.has(chipKey)}
+ isSelected={selectedChipIndexSet.has(chipIndex)}
+ onEdit={() => handleChipEdit(chipIndex)}
+ onExtendSelectionTo={() => handleChipExtendSelectionTo(chipIndex)}
+ onRemove={() => handleChipRemove(chipIndex)}
+ onToggleSelection={() => handleChipToggleSelection(chipIndex)}
+ recipient={recipient}
+ resolution={resolutionByRecipientKey.get(chipKey)}
+ selectedIndices={selectedChipIndices}
+ sortableId={`${fieldId}:${chipKey}`}
+ />
);
});
@@ -540,7 +643,12 @@ export const EmailRecipientsFieldInput = ({
clickableComponentWidth="100%"
onClose={resetSelectedItem}
clickableComponent={
- <StyledRowContainer onMouseDown={handleRowMouseDown}>
+ <StyledRowContainer
+ ref={droppableRef}
+ $isDropTarget={isActiveDropField}
+ data-drop-target={isActiveDropField}
+ onMouseDown={handleRowMouseDown}
+ >
{rowChildren}
</StyledRowContainer>
}
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/constants/EmailRecipientDndType.ts b/packages/twenty-front/src/modules/activities/emails/recipients/constants/EmailRecipientDndType.ts
new file mode 100644
index 00000000000..c895c9fae32
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/constants/EmailRecipientDndType.ts
@@ -0,0 +1 @@
+export const EMAIL_RECIPIENT_DND_TYPE = 'email-recipient';
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/constants/EmailRecipientsFieldIds.ts b/packages/twenty-front/src/modules/activities/emails/recipients/constants/EmailRecipientsFieldIds.ts
new file mode 100644
index 00000000000..a26c9627f72
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/constants/EmailRecipientsFieldIds.ts
@@ -0,0 +1,7 @@
+import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/types/EmailRecipientsFieldId';
+
+export const EMAIL_RECIPIENTS_FIELD_IDS: EmailRecipientsFieldId[] = [
+ 'to',
+ 'cc',
+ 'bcc',
+];
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/__tests__/useEmailRecipientsField.test.ts b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/__tests__/useEmailRecipientsField.test.ts
index 385f67e6cea..392d1711853 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/__tests__/useEmailRecipientsField.test.ts
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/__tests__/useEmailRecipientsField.test.ts
@@ -129,14 +129,14 @@ describe('useEmailRecipientsField', () => {
view.result.current.moveChipSelection(-1);
});
- expect(view.result.current.selectedChipIndex).toBe(1);
+ expect(view.result.current.selectedChipIndices).toEqual([1]);
act(() => {
- view.result.current.removeRecipientWithKeyboard();
+ view.result.current.removeSelectedRecipients();
});
expect(onChange).toHaveBeenCalledWith([{ address: '[email protected]' }]);
- expect(view.result.current.selectedChipIndex).toBe(0);
+ expect(view.result.current.selectedChipIndices).toEqual([0]);
});
it('should clear the selection when moving right past the last chip', () => {
@@ -149,7 +149,259 @@ describe('useEmailRecipientsField', () => {
view.result.current.moveChipSelection(1);
});
- expect(view.result.current.selectedChipIndex).toBeNull();
+ expect(view.result.current.selectedChipIndices).toEqual([]);
+ expect(view.result.current.selectionFocusIndex).toBeNull();
+ });
+
+ it('should extend the selection leftwards with shift+arrow', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.extendChipSelection(-1);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([2]);
+
+ act(() => {
+ view.result.current.extendChipSelection(-1);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([1, 2]);
+
+ act(() => {
+ view.result.current.extendChipSelection(-1);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([0, 1, 2]);
+ });
+
+ it('should shrink the extended selection when reversing direction', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.extendChipSelection(-1);
+ });
+ act(() => {
+ view.result.current.extendChipSelection(-1);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([1, 2]);
+
+ act(() => {
+ view.result.current.extendChipSelection(1);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([2]);
+ });
+
+ it('should keep the selection when extending past the last chip', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.extendChipSelection(-1);
+ });
+ act(() => {
+ view.result.current.extendChipSelection(1);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([1]);
+ });
+
+ it('should select a range when shift clicking away from the anchor', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.selectChipAtIndex(1);
+ });
+ act(() => {
+ view.result.current.extendChipSelectionToIndex(3);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([1, 2, 3]);
+ });
+
+ it('should select a backwards range when shift clicking before the anchor', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.selectChipAtIndex(2);
+ });
+ act(() => {
+ view.result.current.extendChipSelectionToIndex(0);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([0, 1, 2]);
+ });
+
+ it('should add and remove single chips when toggling the selection', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.selectChipAtIndex(0);
+ });
+ act(() => {
+ view.result.current.toggleChipSelectionAtIndex(2);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([0, 2]);
+
+ act(() => {
+ view.result.current.toggleChipSelectionAtIndex(0);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([2]);
+ });
+
+ it('should move the cursor off a chip that was toggled out of the selection', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.selectChipAtIndex(1);
+ });
+ act(() => {
+ view.result.current.extendChipSelectionToIndex(2);
+ });
+
+ expect(view.result.current.selectionFocusIndex).toBe(2);
+
+ act(() => {
+ view.result.current.toggleChipSelectionAtIndex(2);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([1]);
+ expect(view.result.current.selectionFocusIndex).toBe(1);
+ });
+
+ it('should remove every selected chip at once', () => {
+ const { view, onChange } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.selectChipAtIndex(1);
+ });
+ act(() => {
+ view.result.current.extendChipSelectionToIndex(2);
+ });
+ act(() => {
+ view.result.current.removeSelectedRecipients();
+ });
+
+ expect(onChange).toHaveBeenCalledWith([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+ expect(view.result.current.selectedChipIndices).toEqual([0]);
+ });
+
+ it('should keep the selection on the same recipients after a reorder', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.selectChipAtIndex(0);
+ });
+ act(() => {
+ view.result.current.extendChipSelectionToIndex(1);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([0, 1]);
+
+ // A drag moved [email protected] to the end; the selection has to follow the
+ // addresses rather than staying on positions 0 and 1.
+ view.rerender({
+ recipients: [
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ],
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([0, 2]);
+ });
+
+ it('should remove the originally selected recipients after a reorder', () => {
+ const { view, onChange } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.selectChipAtIndex(0);
+ });
+
+ view.rerender({
+ recipients: [
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ],
+ });
+
+ act(() => {
+ view.result.current.removeSelectedRecipients();
+ });
+
+ expect(onChange).toHaveBeenCalledWith([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+ });
+
+ it('should drop selected indices that no longer exist after recipients shrink', () => {
+ const { view } = setup([
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ]);
+
+ act(() => {
+ view.result.current.selectChipAtIndex(0);
+ });
+ act(() => {
+ view.result.current.extendChipSelectionToIndex(2);
+ });
+
+ expect(view.result.current.selectedChipIndices).toEqual([0, 1, 2]);
+
+ view.rerender({ recipients: [{ address: '[email protected]' }] });
+
+ expect(view.result.current.selectedChipIndices).toEqual([0]);
});
it('should add a picked suggestion as a recipient', () => {
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop.ts b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop.ts
new file mode 100644
index 00000000000..9e64cdcd8cb
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop.ts
@@ -0,0 +1,143 @@
+import { useState } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
+import { EMAIL_RECIPIENTS_FIELD_IDS } from '@/activities/emails/recipients/constants/EmailRecipientsFieldIds';
+import { type EmailRecipientDragData } from '@/activities/emails/recipients/types/EmailRecipientDragData';
+import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/types/EmailRecipientsFieldId';
+import {
+ type EmailRecipientsByFieldId,
+ moveEmailRecipientsBetweenFields,
+} from '@/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields';
+import { type DragDropItemDndContextValue } from '@/ui/utilities/drag-and-drop/context/DragDropItemDndContext';
+import { type DragDropProviderDragEndEvent } from '@/ui/utilities/drag-and-drop/types/DragDropProviderDragEndEvent';
+import { type DragDropProviderDragMoveEvent } from '@/ui/utilities/drag-and-drop/types/DragDropProviderDragMoveEvent';
+import { type DragDropProviderDragStartEvent } from '@/ui/utilities/drag-and-drop/types/DragDropProviderDragStartEvent';
+import { resolveDropFromPointer } from '@/ui/utilities/drag-and-drop/utils/resolveDropFromPointer';
+
+type DragStartEvent = DragDropProviderDragStartEvent<EmailRecipientDragData>;
+type DragMoveEvent = DragDropProviderDragMoveEvent<EmailRecipientDragData>;
+type DragEndEvent = DragDropProviderDragEndEvent<EmailRecipientDragData>;
+
+type UseEmailRecipientsDragAndDropArgs = {
+ recipientsByFieldId: EmailRecipientsByFieldId;
+ onRecipientsByFieldIdChange: (
+ recipientsByFieldId: EmailRecipientsByFieldId,
+ ) => void;
+};
+
+const isEmailRecipientsFieldId = (
+ value: string,
+): value is EmailRecipientsFieldId =>
+ EMAIL_RECIPIENTS_FIELD_IDS.some((fieldId) => fieldId === value);
+
+export const useEmailRecipientsDragAndDrop = ({
+ recipientsByFieldId,
+ onRecipientsByFieldIdChange,
+}: UseEmailRecipientsDragAndDropArgs) => {
+ const [activeDropTargetIndex, setActiveDropTargetIndex] = useState<
+ number | null
+ >(null);
+ const [activeDroppableId, setActiveDroppableId] = useState<string | null>(
+ null,
+ );
+ const [draggedRecipients, setDraggedRecipients] = useState<{
+ fieldId: EmailRecipientsFieldId;
+ indices: number[];
+ } | null>(null);
+
+ const getDroppableItemCount = (droppableId: string) =>
+ isEmailRecipientsFieldId(droppableId)
+ ? recipientsByFieldId[droppableId].length
+ : 0;
+
+ const clearActiveDropTarget = () => {
+ setActiveDropTargetIndex(null);
+ setActiveDroppableId(null);
+ };
+
+ const getMovedIndices = (sourceData: EmailRecipientDragData): number[] =>
+ sourceData.selectedIndices.includes(sourceData.index)
+ ? sourceData.selectedIndices
+ : [sourceData.index];
+
+ const onDragStart = (event: DragStartEvent) => {
+ clearActiveDropTarget();
+
+ const sourceData = event.operation.source?.data as
+ | EmailRecipientDragData
+ | undefined;
+
+ setDraggedRecipients(
+ isDefined(sourceData)
+ ? {
+ fieldId: sourceData.fieldId,
+ indices: getMovedIndices(sourceData),
+ }
+ : null,
+ );
+ };
+
+ const onDragMove = (event: DragMoveEvent) => {
+ const resolvedDrop = resolveDropFromPointer({
+ target: event.operation.target,
+ pointer: event.operation.position.current,
+ // Chips flow horizontally, so the insertion boundary is a vertical seam
+ // and the pointer's x position decides which side of a chip it lands on.
+ defaultOrientation: 'vertical',
+ getDroppableItemCount,
+ });
+
+ setActiveDropTargetIndex(resolvedDrop?.dropTargetIndex ?? null);
+ setActiveDroppableId(resolvedDrop?.droppableId ?? null);
+ };
+
+ const onDragEnd = (event: DragEndEvent) => {
+ clearActiveDropTarget();
+ setDraggedRecipients(null);
+
+ const sourceData = event.operation.source?.data as
+ | EmailRecipientDragData
+ | undefined;
+
+ if (event.canceled || !isDefined(sourceData)) {
+ return;
+ }
+
+ const resolvedDrop = resolveDropFromPointer({
+ target: event.operation.target,
+ pointer: event.operation.position.current,
+ defaultOrientation: 'vertical',
+ getDroppableItemCount,
+ });
+
+ if (
+ !isDefined(resolvedDrop) ||
+ !isEmailRecipientsFieldId(resolvedDrop.droppableId)
+ ) {
+ return;
+ }
+
+ const movedIndices = getMovedIndices(sourceData);
+
+ const nextRecipientsByFieldId = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId,
+ sourceFieldId: sourceData.fieldId,
+ movedIndices,
+ destinationFieldId: resolvedDrop.droppableId,
+ destinationIndex: resolvedDrop.dropTargetIndex,
+ });
+
+ onRecipientsByFieldIdChange(nextRecipientsByFieldId);
+ };
+
+ const contextValues: DragDropItemDndContextValue = {
+ activeDropTargetIndex,
+ activeDroppableId,
+ };
+
+ return {
+ contextValues,
+ draggedRecipients,
+ handlers: { onDragStart, onDragMove, onDragEnd },
+ };
+};
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsField.ts b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsField.ts
index 31eceac9df4..ffd1e758e79 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsField.ts
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsField.ts
@@ -1,7 +1,8 @@
-import { useState } from 'react';
+import { useMemo, useState } from 'react';
import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';
import { formatEmailRecipient } from '@/activities/emails/recipients/utils/formatEmailRecipient';
+import { getEmailRecipientKey } from '@/activities/emails/recipients/utils/getEmailRecipientKey';
import { mergeEmailRecipients } from '@/activities/emails/recipients/utils/mergeEmailRecipients';
import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';
import { toSpliced } from '~/utils/array/toSpliced';
@@ -16,19 +17,87 @@ type ChipFlash = {
nonce: number;
};
+// The selection is stored as recipient keys rather than array positions: a drag
+// can reorder the field underneath it, and positions would then point at
+// whichever chips happen to have moved into those slots.
+// anchorKey is where a shift-extended range starts and focusKey is the chip the
+// keyboard cursor sits on, so shift+arrow can grow and shrink the same range
+// the way a text selection does.
+type ChipSelection = {
+ anchorKey: string;
+ focusKey: string;
+ keys: string[];
+};
+
export const useEmailRecipientsField = ({
recipients,
onChange,
}: UseEmailRecipientsFieldArgs) => {
const [inputValue, setInputValue] = useState('');
const [editingIndex, setEditingIndex] = useState<number | null>(null);
- const [selectedChipIndex, setSelectedChipIndex] = useState<number | null>(
+ const [chipSelection, setChipSelection] = useState<ChipSelection | null>(
null,
);
const [chipFlash, setChipFlash] = useState<ChipFlash | null>(null);
const isEditing = editingIndex !== null;
+ const recipientKeys = useMemo(
+ () =>
+ recipients.map((recipient) => getEmailRecipientKey(recipient.address)),
+ [recipients],
+ );
+
+ const selectedChipIndices = useMemo(() => {
+ if (chipSelection === null) {
+ return [];
+ }
+
+ const selectedKeys = new Set(chipSelection.keys);
+
+ return recipientKeys.reduce<number[]>((indices, recipientKey, index) => {
+ if (selectedKeys.has(recipientKey)) {
+ indices.push(index);
+ }
+
+ return indices;
+ }, []);
+ }, [chipSelection, recipientKeys]);
+
+ const findKeyIndex = (chipKey: string | undefined): number | null => {
+ if (chipKey === undefined) {
+ return null;
+ }
+
+ const index = recipientKeys.indexOf(chipKey);
+
+ return index === -1 ? null : index;
+ };
+
+ const selectionFocusIndex = findKeyIndex(chipSelection?.focusKey);
+ const selectionAnchorIndex = findKeyIndex(chipSelection?.anchorKey);
+
+ const buildSelection = (
+ anchorIndex: number,
+ focusIndex: number,
+ ): ChipSelection | null => {
+ const anchorKey = recipientKeys[anchorIndex];
+ const focusKey = recipientKeys[focusIndex];
+
+ if (anchorKey === undefined || focusKey === undefined) {
+ return null;
+ }
+
+ return {
+ anchorKey,
+ focusKey,
+ keys: recipientKeys.slice(
+ Math.min(anchorIndex, focusIndex),
+ Math.max(anchorIndex, focusIndex) + 1,
+ ),
+ };
+ };
+
const flashChip = (chipKey: string) => {
setChipFlash((previousFlash) => ({
chipKey,
@@ -81,7 +150,7 @@ export const useEmailRecipientsField = ({
const beginEditingChip = (chipIndex: number) => {
setEditingIndex(chipIndex);
setInputValue(formatEmailRecipient(recipients[chipIndex]));
- setSelectedChipIndex(null);
+ setChipSelection(null);
};
const cancelEditing = () => {
@@ -91,29 +160,101 @@ export const useEmailRecipientsField = ({
const removeRecipientAtIndex = (chipIndex: number) => {
onChange(toSpliced(recipients, chipIndex, 1));
- setSelectedChipIndex(null);
+ setChipSelection(null);
if (editingIndex !== null && chipIndex < editingIndex) {
setEditingIndex(editingIndex - 1);
}
};
- const removeRecipientWithKeyboard = () => {
- if (selectedChipIndex === null) {
+ const removeSelectedRecipients = () => {
+ if (selectedChipIndices.length === 0) {
return;
}
- const removedIndex = selectedChipIndex;
- onChange(toSpliced(recipients, removedIndex, 1));
+ const removedIndices = new Set(selectedChipIndices);
+
+ onChange(
+ recipients.filter((_recipient, index) => !removedIndices.has(index)),
+ );
+
+ // Selection collapses onto the chip just before the removed run, matching
+ // how a text cursor lands after deleting a selection. That chip sits before
+ // the lowest removed index, so it always survives the removal.
+ const indexBeforeRemoved = Math.min(...selectedChipIndices) - 1;
+ const keyBeforeRemoved = recipientKeys[indexBeforeRemoved];
- const remainingCount = recipients.length - 1;
- setSelectedChipIndex(
- removedIndex > 0 && remainingCount > 0 ? removedIndex - 1 : null,
+ setChipSelection(
+ keyBeforeRemoved === undefined
+ ? null
+ : {
+ anchorKey: keyBeforeRemoved,
+ focusKey: keyBeforeRemoved,
+ keys: [keyBeforeRemoved],
+ },
);
};
const clearChipSelection = () => {
- setSelectedChipIndex(null);
+ setChipSelection(null);
+ };
+
+ const selectChipAtIndex = (chipIndex: number) => {
+ setChipSelection(buildSelection(chipIndex, chipIndex));
+ };
+
+ const extendChipSelectionToIndex = (chipIndex: number) => {
+ setChipSelection(
+ buildSelection(selectionAnchorIndex ?? chipIndex, chipIndex),
+ );
+ };
+
+ const toggleChipSelectionAtIndex = (chipIndex: number) => {
+ const chipKey = recipientKeys[chipIndex];
+
+ if (chipKey === undefined) {
+ return;
+ }
+
+ setChipSelection((previousSelection) => {
+ if (previousSelection === null) {
+ return { anchorKey: chipKey, focusKey: chipKey, keys: [chipKey] };
+ }
+
+ const isAlreadySelected = previousSelection.keys.includes(chipKey);
+
+ if (!isAlreadySelected) {
+ // Adding re-anchors on the clicked chip so a following shift+click
+ // ranges from where the user last pointed.
+ return {
+ anchorKey: chipKey,
+ focusKey: chipKey,
+ keys: [...previousSelection.keys, chipKey],
+ };
+ }
+
+ const nextKeys = previousSelection.keys.filter((key) => key !== chipKey);
+
+ if (nextKeys.length === 0) {
+ return null;
+ }
+
+ // Removing must not leave the anchor or the cursor on a chip that is no
+ // longer selected, or Enter and shift+arrow would act on it.
+ const fallbackKey = nextKeys[nextKeys.length - 1];
+
+ return {
+ anchorKey:
+ previousSelection.anchorKey === chipKey
+ ? fallbackKey
+ : previousSelection.anchorKey,
+ focusKey:
+ previousSelection.focusKey === chipKey
+ ? fallbackKey
+ : previousSelection.focusKey,
+ keys: nextKeys,
+ };
+ });
};
const moveChipSelection = (direction: -1 | 1): number | null => {
@@ -121,34 +262,64 @@ export const useEmailRecipientsField = ({
return null;
}
- if (selectedChipIndex === null) {
+ if (selectionFocusIndex === null) {
if (direction === 1) {
return null;
}
const lastIndex = recipients.length - 1;
- setSelectedChipIndex(lastIndex);
+ selectChipAtIndex(lastIndex);
return lastIndex;
}
- const nextIndex = selectedChipIndex + direction;
+ const nextIndex = selectionFocusIndex + direction;
if (nextIndex >= recipients.length) {
- setSelectedChipIndex(null);
+ setChipSelection(null);
return null;
}
const boundedIndex = Math.max(nextIndex, 0);
- setSelectedChipIndex(boundedIndex);
+ selectChipAtIndex(boundedIndex);
return boundedIndex;
};
+ const extendChipSelection = (direction: -1 | 1): number | null => {
+ if (recipients.length === 0) {
+ return null;
+ }
+
+ if (selectionFocusIndex === null || selectionAnchorIndex === null) {
+ // Shift+Left out of the text input starts a selection on the last chip;
+ // shift+Right has nowhere to go.
+ if (direction === 1) {
+ return null;
+ }
+
+ const lastIndex = recipients.length - 1;
+ selectChipAtIndex(lastIndex);
+ return lastIndex;
+ }
+
+ // Unlike a plain arrow, extending past the last chip keeps the selection
+ // rather than dropping the caret back into the input.
+ const nextFocusIndex = Math.min(
+ Math.max(selectionFocusIndex + direction, 0),
+ recipients.length - 1,
+ );
+
+ setChipSelection(buildSelection(selectionAnchorIndex, nextFocusIndex));
+
+ return nextFocusIndex;
+ };
+
return {
inputValue,
setInputValue,
editingIndex,
isEditing,
- selectedChipIndex,
+ selectedChipIndices,
+ selectionFocusIndex,
chipFlash,
commitInput,
addRecipient,
@@ -156,8 +327,12 @@ export const useEmailRecipientsField = ({
beginEditingChip,
cancelEditing,
removeRecipientAtIndex,
- removeRecipientWithKeyboard,
+ removeSelectedRecipients,
clearChipSelection,
+ selectChipAtIndex,
+ extendChipSelectionToIndex,
+ toggleChipSelectionAtIndex,
moveChipSelection,
+ extendChipSelection,
};
};
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientDragData.ts b/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientDragData.ts
new file mode 100644
index 00000000000..ea1318864a4
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientDragData.ts
@@ -0,0 +1,9 @@
+import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/types/EmailRecipientsFieldId';
+
+export type EmailRecipientDragData = {
+ fieldId: EmailRecipientsFieldId;
+ index: number;
+ // Chips carry the field selection they were rendered with so a drag that
+ // starts on a selected chip moves the whole selection, not just that chip.
+ selectedIndices: number[];
+};
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientsFieldId.ts b/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientsFieldId.ts
new file mode 100644
index 00000000000..23f6f3d8c68
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientsFieldId.ts
@@ -0,0 +1 @@
+export type EmailRecipientsFieldId = 'to' | 'cc' | 'bcc';
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/utils/__tests__/moveEmailRecipientsBetweenFields.test.ts b/packages/twenty-front/src/modules/activities/emails/recipients/utils/__tests__/moveEmailRecipientsBetweenFields.test.ts
new file mode 100644
index 00000000000..5cd47ffdb0d
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/utils/__tests__/moveEmailRecipientsBetweenFields.test.ts
@@ -0,0 +1,223 @@
+import {
+ type EmailRecipientsByFieldId,
+ moveEmailRecipientsBetweenFields,
+} from '@/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields';
+
+const buildRecipientsByFieldId = (
+ overrides: Partial<EmailRecipientsByFieldId> = {},
+): EmailRecipientsByFieldId => ({
+ to: [],
+ cc: [],
+ bcc: [],
+ ...overrides,
+});
+
+const addresses = (recipients: { address: string }[]) =>
+ recipients.map((recipient) => recipient.address);
+
+describe('moveEmailRecipientsBetweenFields', () => {
+ it('should move a chip to the end of its own field', () => {
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId: buildRecipientsByFieldId({
+ to: [
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ],
+ }),
+ sourceFieldId: 'to',
+ movedIndices: [0],
+ destinationFieldId: 'to',
+ destinationIndex: 3,
+ });
+
+ expect(addresses(result.to)).toEqual(['[email protected]', '[email protected]', '[email protected]']);
+ });
+
+ it('should move a chip backwards inside its own field', () => {
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId: buildRecipientsByFieldId({
+ to: [
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ],
+ }),
+ sourceFieldId: 'to',
+ movedIndices: [2],
+ destinationFieldId: 'to',
+ destinationIndex: 0,
+ });
+
+ expect(addresses(result.to)).toEqual(['[email protected]', '[email protected]', '[email protected]']);
+ });
+
+ it('should leave the order untouched when dropping a chip back in place', () => {
+ const recipientsByFieldId = buildRecipientsByFieldId({
+ to: [{ address: '[email protected]' }, { address: '[email protected]' }],
+ });
+
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId,
+ sourceFieldId: 'to',
+ movedIndices: [0],
+ destinationFieldId: 'to',
+ destinationIndex: 1,
+ });
+
+ expect(addresses(result.to)).toEqual(['[email protected]', '[email protected]']);
+ });
+
+ it('should keep a multi-chip selection contiguous and ordered when reordering', () => {
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId: buildRecipientsByFieldId({
+ to: [
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ],
+ }),
+ sourceFieldId: 'to',
+ movedIndices: [0, 2],
+ destinationFieldId: 'to',
+ destinationIndex: 4,
+ });
+
+ expect(addresses(result.to)).toEqual([
+ ]);
+ });
+
+ it('should move a chip from To to Cc at the drop position', () => {
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId: buildRecipientsByFieldId({
+ to: [{ address: '[email protected]' }, { address: '[email protected]' }],
+ cc: [{ address: '[email protected]' }],
+ }),
+ sourceFieldId: 'to',
+ movedIndices: [0],
+ destinationFieldId: 'cc',
+ destinationIndex: 0,
+ });
+
+ expect(addresses(result.to)).toEqual(['[email protected]']);
+ expect(addresses(result.cc)).toEqual(['[email protected]', '[email protected]']);
+ expect(result.bcc).toEqual([]);
+ });
+
+ it('should move a whole selection from To to Bcc', () => {
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId: buildRecipientsByFieldId({
+ to: [
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ],
+ }),
+ sourceFieldId: 'to',
+ movedIndices: [0, 2],
+ destinationFieldId: 'bcc',
+ destinationIndex: 0,
+ });
+
+ expect(addresses(result.to)).toEqual(['[email protected]']);
+ expect(addresses(result.bcc)).toEqual(['[email protected]', '[email protected]']);
+ });
+
+ it('should drop a duplicate instead of adding it twice to the destination', () => {
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId: buildRecipientsByFieldId({
+ to: [{ address: '[email protected]' }],
+ cc: [{ address: '[email protected]' }],
+ }),
+ sourceFieldId: 'to',
+ movedIndices: [0],
+ destinationFieldId: 'cc',
+ destinationIndex: 0,
+ });
+
+ expect(result.to).toEqual([]);
+ expect(addresses(result.cc)).toEqual(['[email protected]']);
+ });
+
+ it('should keep both copies when reordering a field that holds the same address twice', () => {
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId: buildRecipientsByFieldId({
+ to: [
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ { address: '[email protected]' },
+ ],
+ }),
+ sourceFieldId: 'to',
+ movedIndices: [0],
+ destinationFieldId: 'to',
+ destinationIndex: 3,
+ });
+
+ expect(addresses(result.to)).toEqual(['[email protected]', '[email protected]', '[email protected]']);
+ });
+
+ it('should return the original state when a drop does not change the order', () => {
+ const recipientsByFieldId = buildRecipientsByFieldId({
+ to: [{ address: '[email protected]' }, { address: '[email protected]' }],
+ });
+
+ expect(
+ moveEmailRecipientsBetweenFields({
+ recipientsByFieldId,
+ sourceFieldId: 'to',
+ movedIndices: [0],
+ destinationFieldId: 'to',
+ destinationIndex: 0,
+ }),
+ ).toBe(recipientsByFieldId);
+
+ expect(
+ moveEmailRecipientsBetweenFields({
+ recipientsByFieldId,
+ sourceFieldId: 'to',
+ movedIndices: [0],
+ destinationFieldId: 'to',
+ destinationIndex: 1,
+ }),
+ ).toBe(recipientsByFieldId);
+ });
+
+ it('should keep the untouched field reference stable', () => {
+ const recipientsByFieldId = buildRecipientsByFieldId({
+ to: [{ address: '[email protected]' }],
+ bcc: [{ address: '[email protected]' }],
+ });
+
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId,
+ sourceFieldId: 'to',
+ movedIndices: [0],
+ destinationFieldId: 'cc',
+ destinationIndex: 0,
+ });
+
+ expect(result.bcc).toBe(recipientsByFieldId.bcc);
+ });
+
+ it('should ignore indices that fall outside the source field', () => {
+ const recipientsByFieldId = buildRecipientsByFieldId({
+ to: [{ address: '[email protected]' }],
+ });
+
+ const result = moveEmailRecipientsBetweenFields({
+ recipientsByFieldId,
+ sourceFieldId: 'to',
+ movedIndices: [7],
+ destinationFieldId: 'cc',
+ destinationIndex: 0,
+ });
+
+ expect(result).toBe(recipientsByFieldId);
+ });
+});
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields.ts b/packages/twenty-front/src/modules/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields.ts
new file mode 100644
index 00000000000..c42523c7b9a
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields.ts
@@ -0,0 +1,88 @@
+import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';
+import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/types/EmailRecipientsFieldId';
+import { mergeEmailRecipients } from '@/activities/emails/recipients/utils/mergeEmailRecipients';
+import { toSpliced } from '~/utils/array/toSpliced';
+
+export type EmailRecipientsByFieldId = Record<
+ EmailRecipientsFieldId,
+ EmailRecipient[]
+>;
+
+// Both lists are built from the same recipient objects, so identity comparison
+// is enough to tell a real reorder from a drop that landed back in place.
+const areRecipientListsEqual = (
+ recipients: EmailRecipient[],
+ otherRecipients: EmailRecipient[],
+) =>
+ recipients.length === otherRecipients.length &&
+ recipients.every((recipient, index) => recipient === otherRecipients[index]);
+
+type MoveEmailRecipientsBetweenFieldsArgs = {
+ recipientsByFieldId: EmailRecipientsByFieldId;
+ sourceFieldId: EmailRecipientsFieldId;
+ movedIndices: number[];
+ destinationFieldId: EmailRecipientsFieldId;
+ destinationIndex: number;
+};
+
+export const moveEmailRecipientsBetweenFields = ({
+ recipientsByFieldId,
+ sourceFieldId,
+ movedIndices,
+ destinationFieldId,
+ destinationIndex,
+}: MoveEmailRecipientsBetweenFieldsArgs): EmailRecipientsByFieldId => {
+ const sourceRecipients = recipientsByFieldId[sourceFieldId];
+
+ const sortedMovedIndices = [...new Set(movedIndices)]
+ .filter((index) => index >= 0 && index < sourceRecipients.length)
+ .sort((a, b) => a - b);
+
+ if (sortedMovedIndices.length === 0) {
+ return recipientsByFieldId;
+ }
+
+ const movedIndexSet = new Set(sortedMovedIndices);
+ const movedRecipients = sortedMovedIndices.map(
+ (index) => sourceRecipients[index],
+ );
+ const remainingSourceRecipients = sourceRecipients.filter(
+ (_recipient, index) => !movedIndexSet.has(index),
+ );
+
+ if (sourceFieldId === destinationFieldId) {
+ // Removing the dragged chips first shifts every later slot left, so the
+ // drop index has to lose the chips that used to sit before it.
+ const removedBeforeDestinationCount = sortedMovedIndices.filter(
+ (index) => index < destinationIndex,
+ ).length;
+ const adjustedDestinationIndex =
+ destinationIndex - removedBeforeDestinationCount;
+
+ // Spliced back in directly rather than merged: a field seeded from a draft
+ // can already hold the same address twice, and a reorder must never change
+ // the recipient count.
+ const reorderedRecipients = toSpliced(
+ remainingSourceRecipients,
+ adjustedDestinationIndex,
+ 0,
+ ...movedRecipients,
+ );
+
+ return areRecipientListsEqual(sourceRecipients, reorderedRecipients)
+ ? recipientsByFieldId
+ : { ...recipientsByFieldId, [sourceFieldId]: reorderedRecipients };
+ }
+
+ const { mergedRecipients } = mergeEmailRecipients(
+ recipientsByFieldId[destinationFieldId],
+ movedRecipients,
+ destinationIndex,
+ );
+
+ return {
+ ...recipientsByFieldId,
+ [sourceFieldId]: remainingSourceRecipients,
+ [destinationFieldId]: mergedRecipients,
+ };
+};
diff --git a/packages/twenty-front/src/modules/ui/input/components/BaseChip.tsx b/packages/twenty-front/src/modules/ui/input/components/BaseChip.tsx
index c534c29faec..c38516a08c7 100644
--- a/packages/twenty-front/src/modules/ui/input/components/BaseChip.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/BaseChip.tsx
@@ -134,6 +134,7 @@ export const BaseChip = ({
deletable={isDeletable}
danger={danger}
selected={selected}
+ data-selected={selected}
data-flashing={isFlashing}
onDoubleClick={onDoubleClick}
>