Skip to content

The open alternative to Salesforce, designed for AI.

Edit the full name in one input and show address details on demand in cell editors (#28773)

Charles Bochet6b1062ff4dc1
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FullNameFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FullNameFieldInput.tsx
index 72aee15ce7e..86cffeed803 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FullNameFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FullNameFieldInput.tsx
@@ -1,15 +1,30 @@
+import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
import { useFullNameField } from '@/object-record/record-field/ui/meta-types/hooks/useFullNameField';
-import { type FieldDoubleText } from '@/object-record/record-field/ui/types/FieldDoubleText';
-import { DoubleTextInput } from '@/ui/field/input/components/DoubleTextInput';
-
import { addCharactersToAvoidPasswordManagers } from '@/object-record/record-field/ui/meta-types/input/utils/addCharactersToAvoidPasswordManagers';
-import { isDoubleTextFieldEmpty } from '@/object-record/record-field/ui/meta-types/input/utils/isDoubleTextFieldEmpty';
+import { joinFullName } from '@/object-record/record-field/ui/meta-types/input/utils/joinFullName';
+import { trimFullName } from '@/object-record/record-field/ui/meta-types/input/utils/trimFullName';
+import { splitFullNameInputText } from '@/object-record/record-field/ui/meta-types/input/utils/splitFullNameInputText';
import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
-
-import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
+import { type FieldFullNameValue } from '@/object-record/record-field/ui/types/FieldMetadata';
+import { FieldInputContainer } from '@/ui/field/input/components/FieldInputContainer';
+import { FieldInputDetailsToggleRow } from '@/ui/field/input/components/FieldInputDetailsToggleRow';
+import { StyledFieldInputDetails } from '@/ui/field/input/components/StyledFieldInputDetails';
+import { StyledTextInput } from '@/ui/field/input/components/TextInput';
+import { TextInput } from '@/ui/input/components/TextInput';
+import { PASSWORD_MANAGER_IGNORE_ATTRIBUTES } from '@/ui/input/constants/PasswordManagerIgnoreAttributes';
+import { useRegisterInputEvents } from '@/ui/input/hooks/useRegisterInputEvents';
import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
+import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { useContext } from 'react';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useContext, useRef, useState } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
+const StyledFullNameContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+`;
export const FullNameFieldInput = () => {
const { t } = useLingui();
@@ -19,74 +34,143 @@ export const FullNameFieldInput = () => {
FieldInputEventContext,
);
- const convertToFullName = (newDoubleText: FieldDoubleText) => {
- return {
- firstName: newDoubleText.firstValue.trim(),
- lastName: newDoubleText.secondValue.trim(),
- };
- };
+ const instanceId = useAvailableComponentInstanceIdOrThrow(
+ RecordFieldComponentInstanceContext,
+ );
- const getRequiredDraftValueFromDoubleText = (
- newDoubleText: FieldDoubleText,
- ) => {
- return isDoubleTextFieldEmpty(newDoubleText)
- ? undefined
- : convertToFullName(newDoubleText);
- };
+ const [fullName, setFullName] = useState<FieldFullNameValue>({
+ firstName: draftValue?.firstName ?? '',
+ lastName: draftValue?.lastName ?? '',
+ });
+ const [fullNameText, setFullNameText] = useState(() =>
+ joinFullName(fullName),
+ );
+ const [isExpanded, setIsExpanded] = useState(false);
+ const [focusedInputIndex, setFocusedInputIndex] = useState(0);
- const handleEnter = (newDoubleText: FieldDoubleText) => {
- onEnter?.({ newValue: convertToFullName(newDoubleText) });
- };
+ const containerRef = useRef<HTMLDivElement>(null);
+ const fullNameInputRef = useRef<HTMLInputElement>(null);
+ const firstNameInputRef = useRef<HTMLInputElement>(null);
+ const lastNameInputRef = useRef<HTMLInputElement>(null);
- const handleEscape = (newDoubleText: FieldDoubleText) => {
- onEscape?.({ newValue: convertToFullName(newDoubleText) });
- };
+ const focusableInputRefs = isExpanded
+ ? [fullNameInputRef, firstNameInputRef, lastNameInputRef]
+ : [fullNameInputRef];
+
+ const updateFullName = (nextFullName: FieldFullNameValue) => {
+ const trimmedFullName = trimFullName(nextFullName);
- const handleClickOutside = (
- event: MouseEvent | TouchEvent,
- newDoubleText: FieldDoubleText,
- ) => {
- onClickOutside?.({ newValue: convertToFullName(newDoubleText), event });
+ setFullName(nextFullName);
+ setDraftValue(
+ isNonEmptyString(trimmedFullName.firstName) ||
+ isNonEmptyString(trimmedFullName.lastName)
+ ? trimmedFullName
+ : undefined,
+ );
};
- const handleTab = (newDoubleText: FieldDoubleText) => {
- onTab?.({ newValue: convertToFullName(newDoubleText) });
+ const handleFullNameTextChange = (text: string) => {
+ setFullNameText(text);
+ updateFullName(splitFullNameInputText({ text, currentFullName: fullName }));
};
- const handleShiftTab = (newDoubleText: FieldDoubleText) => {
- onShiftTab?.({ newValue: convertToFullName(newDoubleText) });
+ const handleNamePartChange = (nextFullName: FieldFullNameValue) => {
+ setFullNameText(joinFullName(nextFullName));
+ updateFullName(nextFullName);
};
- const handleChange = (newDoubleText: FieldDoubleText) => {
- setDraftValue(getRequiredDraftValueFromDoubleText(newDoubleText));
+ const handleTab = (currentFullName: FieldFullNameValue) => {
+ const nextInputRef = focusableInputRefs[focusedInputIndex + 1];
+
+ if (isDefined(nextInputRef)) {
+ nextInputRef.current?.focus();
+ return;
+ }
+
+ onTab?.({ newValue: trimFullName(currentFullName) });
};
- const handlePaste = (newDoubleText: FieldDoubleText) => {
- setDraftValue(getRequiredDraftValueFromDoubleText(newDoubleText));
+ const handleShiftTab = (currentFullName: FieldFullNameValue) => {
+ const previousInputRef = focusableInputRefs[focusedInputIndex - 1];
+
+ if (isDefined(previousInputRef)) {
+ previousInputRef.current?.focus();
+ return;
+ }
+
+ onShiftTab?.({ newValue: trimFullName(currentFullName) });
};
- const instanceId = useAvailableComponentInstanceIdOrThrow(
- RecordFieldComponentInstanceContext,
- );
+ useRegisterInputEvents({
+ focusId: instanceId,
+ inputRef: containerRef,
+ inputValue: fullName,
+ onEnter: (currentFullName) =>
+ onEnter?.({ newValue: trimFullName(currentFullName) }),
+ onEscape: (currentFullName) =>
+ onEscape?.({ newValue: trimFullName(currentFullName) }),
+ onTab: handleTab,
+ onShiftTab: handleShiftTab,
+ onClickOutside: (event, currentFullName) =>
+ onClickOutside?.({ newValue: trimFullName(currentFullName), event }),
+ });
return (
- <DoubleTextInput
- instanceId={instanceId}
- firstValue={draftValue?.firstName ?? ''}
- secondValue={draftValue?.lastName ?? ''}
- firstValuePlaceholder={addCharactersToAvoidPasswordManagers(
- t`First name`,
- )}
- secondValuePlaceholder={addCharactersToAvoidPasswordManagers(
- t`Last name`,
- )}
- onClickOutside={handleClickOutside}
- onEnter={handleEnter}
- onEscape={handleEscape}
- onShiftTab={handleShiftTab}
- onTab={handleTab}
- onPaste={handlePaste}
- onChange={handleChange}
- />
+ <FieldInputContainer>
+ <StyledFullNameContainer ref={containerRef}>
+ <FieldInputDetailsToggleRow
+ isExpanded={isExpanded}
+ toggleLabel={t`Name details`}
+ onToggle={() => {
+ if (isExpanded) {
+ fullNameInputRef.current?.focus();
+ }
+ setIsExpanded(!isExpanded);
+ }}
+ >
+ <StyledTextInput
+ ref={fullNameInputRef}
+ autoFocus
+ autoComplete="off"
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...PASSWORD_MANAGER_IGNORE_ATTRIBUTES}
+ aria-label={t`Full name`}
+ placeholder={addCharactersToAvoidPasswordManagers(t`Full name`)}
+ value={fullNameText}
+ onChange={(event) => handleFullNameTextChange(event.target.value)}
+ onFocus={() => setFocusedInputIndex(0)}
+ onClick={(event) => event.stopPropagation()}
+ />
+ </FieldInputDetailsToggleRow>
+ {isExpanded && (
+ <StyledFieldInputDetails>
+ <TextInput
+ ref={firstNameInputRef}
+ label={t`First name`}
+ value={fullName.firstName}
+ placeholder={addCharactersToAvoidPasswordManagers(t`First name`)}
+ fullWidth
+ ignorePasswordManagers
+ onChange={(firstName) =>
+ handleNamePartChange({ ...fullName, firstName })
+ }
+ onFocus={() => setFocusedInputIndex(1)}
+ />
+ <TextInput
+ ref={lastNameInputRef}
+ label={t`Last name`}
+ value={fullName.lastName}
+ placeholder={addCharactersToAvoidPasswordManagers(t`Last name`)}
+ fullWidth
+ ignorePasswordManagers
+ onChange={(lastName) =>
+ handleNamePartChange({ ...fullName, lastName })
+ }
+ onFocus={() => setFocusedInputIndex(2)}
+ />
+ </StyledFieldInputDetails>
+ )}
+ </StyledFullNameContainer>
+ </FieldInputContainer>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/AddressFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/AddressFieldInput.stories.tsx
index 0f9fcfc5503..02cf073e058 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/AddressFieldInput.stories.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/AddressFieldInput.stories.tsx
@@ -254,6 +254,9 @@ export const AutofillsAndPersistsAddress: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const screen = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Address details' }),
+ );
const input = canvas.getByRole('combobox', { name: 'Address 1' });
await userEvent.clear(input);
@@ -302,6 +305,9 @@ export const SelectsCityWithoutReplacingStreet: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const screen = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Address details' }),
+ );
const cityInput = canvas.getByRole('combobox', { name: 'City' });
await userEvent.type(cityInput, 'Par');
@@ -347,6 +353,9 @@ export const KeepsSelectionWhileDetailsLoad: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const screen = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Address details' }),
+ );
const input = canvas.getByRole('combobox', { name: 'Address 1' });
const outsideButton = canvas.getByRole('button', { name: 'Outside' });
@@ -456,6 +465,9 @@ export const CountryOnMainSurface: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const screen = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Address details' }),
+ );
await userEvent.click(canvas.getByText('No country'));
await userEvent.type(screen.getByPlaceholderText('Search'), 'France');
@@ -484,6 +496,9 @@ export const CountryOpensWithEnter: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const screen = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Address details' }),
+ );
const trigger = canvas.getByRole('button', { name: 'Country' });
trigger.focus();
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/FullNameFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/FullNameFieldInput.stories.tsx
new file mode 100644
index 00000000000..5845c1ae3ff
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/FullNameFieldInput.stories.tsx
@@ -0,0 +1,195 @@
+import {
+ type Decorator,
+ type Meta,
+ type StoryObj,
+} from '@storybook/react-vite';
+import { useEffect } from 'react';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+
+import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';
+import {
+ FieldInputEventContext,
+ type FieldInputEventContextType,
+} from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
+import { useFullNameField } from '@/object-record/record-field/ui/meta-types/hooks/useFullNameField';
+import { FullNameFieldInput } from '@/object-record/record-field/ui/meta-types/input/components/FullNameFieldInput';
+import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
+import { type FieldFullNameValue } from '@/object-record/record-field/ui/types/FieldMetadata';
+import { RECORD_TABLE_CELL_INPUT_ID_PREFIX } from '@/object-record/record-table/constants/RecordTableCellInputIdPrefix';
+import { getRecordFieldInputInstanceId } from '@/object-record/utils/getRecordFieldInputId';
+import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';
+import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
+import { isDefined } from 'twenty-shared/utils';
+import { FieldMetadataType } from '~/generated-metadata/graphql';
+
+const FullNameValueSetterEffect = ({
+ value,
+}: {
+ value: FieldFullNameValue;
+}) => {
+ const { setFieldValue, setDraftValue } = useFullNameField();
+
+ useEffect(() => {
+ setFieldValue(value);
+ setDraftValue(value);
+ }, [setDraftValue, setFieldValue, value]);
+
+ return <></>;
+};
+
+const InitializedFullNameFieldInput = () => {
+ const { draftValue } = useFullNameField();
+
+ if (!isDefined(draftValue)) {
+ return null;
+ }
+
+ return <FullNameFieldInput />;
+};
+
+const OpenedFieldInputFocusEffect = ({
+ instanceId,
+}: {
+ instanceId: string;
+}) => {
+ const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();
+
+ useEffect(() => {
+ pushFocusItemToFocusStack({
+ focusId: instanceId,
+ component: {
+ type: FocusComponentType.OPENED_FIELD_INPUT,
+ instanceId,
+ },
+ });
+ }, [instanceId, pushFocusItemToFocusStack]);
+
+ return <></>;
+};
+
+type FullNameInputWithContextProps = FieldInputEventContextType & {
+ value: FieldFullNameValue;
+};
+
+const FullNameInputWithContext = ({
+ value,
+ onEnter,
+ onEscape,
+ onClickOutside,
+ onTab,
+ onShiftTab,
+}: FullNameInputWithContextProps) => {
+ const instanceId = getRecordFieldInputInstanceId({
+ recordId: '123',
+ fieldName: 'name',
+ prefix: RECORD_TABLE_CELL_INPUT_ID_PREFIX,
+ });
+
+ return (
+ <RecordFieldComponentInstanceContext.Provider value={{ instanceId }}>
+ <OpenedFieldInputFocusEffect instanceId={instanceId} />
+ <FieldContext.Provider
+ value={{
+ fieldDefinition: {
+ fieldMetadataId: 'name',
+ label: 'Name',
+ type: FieldMetadataType.FULL_NAME,
+ iconName: 'IconUser',
+ metadata: {
+ fieldName: 'name',
+ objectMetadataNameSingular: 'person',
+ },
+ },
+ recordId: '123',
+ isLabelIdentifier: false,
+ isRecordFieldReadOnly: false,
+ }}
+ >
+ <FullNameValueSetterEffect value={value} />
+ <FieldInputEventContext.Provider
+ value={{ onEnter, onEscape, onClickOutside, onTab, onShiftTab }}
+ >
+ <InitializedFullNameFieldInput />
+ </FieldInputEventContext.Provider>
+ </FieldContext.Provider>
+ </RecordFieldComponentInstanceContext.Provider>
+ );
+};
+
+const enterJestFn = fn();
+const tabJestFn = fn();
+
+const clearMocksDecorator: Decorator = (Story) => {
+ enterJestFn.mockClear();
+ tabJestFn.mockClear();
+
+ return <Story />;
+};
+
+const meta: Meta<typeof FullNameInputWithContext> = {
+ title: 'UI/Data/Field/Input/FullNameFieldInput',
+ component: FullNameInputWithContext,
+ args: {
+ value: { firstName: 'Jean', lastName: 'Martin' },
+ onEnter: enterJestFn,
+ onTab: tabJestFn,
+ },
+ argTypes: {
+ onEnter: { control: false },
+ onTab: { control: false },
+ },
+ decorators: [clearMocksDecorator],
+};
+
+export default meta;
+
+type Story = StoryObj<typeof FullNameInputWithContext>;
+
+export const TypeFullName: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const input = await canvas.findByRole('textbox', { name: 'Full name' });
+
+ await expect(input).toHaveValue('Jean Martin');
+
+ await userEvent.tripleClick(input);
+ await userEvent.keyboard('Jean de la Fontaine{Enter}');
+
+ await waitFor(() =>
+ expect(enterJestFn).toHaveBeenLastCalledWith({
+ newValue: { firstName: 'Jean', lastName: 'de la Fontaine' },
+ }),
+ );
+ },
+};
+
+export const EditNameDetails: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const input = await canvas.findByRole('textbox', { name: 'Full name' });
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Name details' }));
+
+ const firstNameInput = canvas.getByRole('textbox', { name: 'First name' });
+
+ await expect(firstNameInput).toHaveValue('Jean');
+
+ await userEvent.click(input);
+ await userEvent.tab();
+
+ await waitFor(() => expect(firstNameInput).toHaveFocus());
+
+ await userEvent.type(firstNameInput, ' Paul');
+
+ await expect(input).toHaveValue('Jean Paul Martin');
+
+ await userEvent.tab();
+ await userEvent.tab();
+
+ await waitFor(() =>
+ expect(tabJestFn).toHaveBeenLastCalledWith({
+ newValue: { firstName: 'Jean Paul', lastName: 'Martin' },
+ }),
+ );
+ },
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-form/utils/__tests__/splitFullNameInputText.test.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/splitFullNameInputText.test.ts
similarity index 96%
rename from packages/twenty-front/src/modules/object-record/record-form/utils/__tests__/splitFullNameInputText.test.ts
rename to packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/splitFullNameInputText.test.ts
index e8f40c5821c..b57d0dae245 100644
--- a/packages/twenty-front/src/modules/object-record/record-form/utils/__tests__/splitFullNameInputText.test.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/splitFullNameInputText.test.ts
@@ -1,4 +1,4 @@
-import { splitFullNameInputText } from '@/object-record/record-form/utils/splitFullNameInputText';
+import { splitFullNameInputText } from '@/object-record/record-field/ui/meta-types/input/utils/splitFullNameInputText';
const EMPTY_FULL_NAME = { firstName: '', lastName: '' };
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/joinFullName.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/joinFullName.ts
new file mode 100644
index 00000000000..a397d304832
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/joinFullName.ts
@@ -0,0 +1,4 @@
+import { type FieldFullNameValue } from '@/object-record/record-field/ui/types/FieldMetadata';
+
+export const joinFullName = ({ firstName, lastName }: FieldFullNameValue) =>
+ `${firstName} ${lastName}`.trim();
diff --git a/packages/twenty-front/src/modules/object-record/record-form/utils/splitFullNameInputText.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/splitFullNameInputText.ts
similarity index 100%
rename from packages/twenty-front/src/modules/object-record/record-form/utils/splitFullNameInputText.ts
rename to packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/splitFullNameInputText.ts
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/trimFullName.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/trimFullName.ts
new file mode 100644
index 00000000000..e76852008ee
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/trimFullName.ts
@@ -0,0 +1,9 @@
+import { type FieldFullNameValue } from '@/object-record/record-field/ui/types/FieldMetadata';
+
+export const trimFullName = ({
+ firstName,
+ lastName,
+}: FieldFullNameValue): FieldFullNameValue => ({
+ firstName: firstName.trim(),
+ lastName: lastName.trim(),
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormAddressFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormAddressFieldInput.tsx
index 32f0f0fddb7..50a4d9ff9d5 100644
--- a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormAddressFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormAddressFieldInput.tsx
@@ -1,14 +1,16 @@
import { type FormFieldInputSubFieldPlaceholders } from '@/object-record/record-field/ui/form-types/types/FormFieldInputSubFieldPlaceholders';
import { type FieldAddressValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { normalizeAddressFieldValueForPersist } from '@/object-record/record-field/ui/utils/normalizeAddressFieldValueForPersist';
-import { RecordFormFieldDetailsToggleRow } from '@/object-record/record-form/components/RecordFormFieldDetailsToggleRow';
+import { FieldInputDetailsToggleRow } from '@/ui/field/input/components/FieldInputDetailsToggleRow';
import { StyledRecordFormFieldBox } from '@/object-record/record-form/components/StyledRecordFormFieldBox';
-import { StyledRecordFormFieldDetails } from '@/object-record/record-form/components/StyledRecordFormFieldDetails';
+import { StyledFieldInputDetails } from '@/ui/field/input/components/StyledFieldInputDetails';
import { StyledTextInput } from '@/ui/field/input/components/TextInput';
import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { CountrySelect } from '@/ui/input/components/internal/country/components/CountrySelect';
import { TextInput } from '@/ui/input/components/TextInput';
-import { styled } from '@linaria/react';
+import { ADDRESS_DETAIL_SUB_FIELDS } from '@/ui/field/input/constants/AddressDetailSubFields';
+import { hasAddressDetailValue } from '@/ui/field/input/utils/hasAddressDetailValue';
+import { StyledFieldInputFullWidthDetail } from '@/ui/field/input/components/StyledFieldInputFullWidthDetail';
import { useLingui } from '@lingui/react/macro';
import { isNonEmptyString } from '@sniptt/guards';
import { useId, useState } from 'react';
@@ -21,14 +23,6 @@ type AddressTextSubField = Exclude<
'addressLat' | 'addressLng'
>;
-const ADDRESS_DETAIL_SUB_FIELDS: AddressTextSubField[] = [
- 'addressStreet2',
- 'addressCity',
- 'addressState',
- 'addressPostcode',
- 'addressCountry',
-];
-
const EMPTY_ADDRESS: FieldAddressValue = {
addressStreet1: '',
addressStreet2: '',
@@ -40,10 +34,6 @@ const EMPTY_ADDRESS: FieldAddressValue = {
addressLng: null,
};
-const StyledFullWidthDetail = styled.div`
- grid-column: 1 / -1;
-`;
-
type RecordFormAddressFieldInputProps = {
label?: string;
defaultValue?: FieldAddressValue;
@@ -74,9 +64,7 @@ export const RecordFormAddressFieldInput = ({
const hasDetails = ADDRESS_DETAIL_SUB_FIELDS.some(hasSubField);
const [isExpanded, setIsExpanded] = useState(() =>
- ADDRESS_DETAIL_SUB_FIELDS.some((subField) =>
- isNonEmptyString(address[subField]),
- ),
+ hasAddressDetailValue({ address, subFields }),
);
const shouldShowDetails = hasDetails && (!hasStreet1 || isExpanded);
@@ -98,7 +86,7 @@ export const RecordFormAddressFieldInput = ({
) : null}
<StyledRecordFormFieldBox>
{hasStreet1 && (
- <RecordFormFieldDetailsToggleRow
+ <FieldInputDetailsToggleRow
isExpanded={isExpanded}
toggleLabel={t`Address details`}
hasToggle={hasDetails}
@@ -115,12 +103,12 @@ export const RecordFormAddressFieldInput = ({
handleSubFieldChange('addressStreet1')(event.target.value)
}
/>
- </RecordFormFieldDetailsToggleRow>
+ </FieldInputDetailsToggleRow>
)}
{shouldShowDetails && (
- <StyledRecordFormFieldDetails hasSeparator={hasStreet1}>
+ <StyledFieldInputDetails hasSeparator={hasStreet1}>
{hasSubField('addressStreet2') && (
- <StyledFullWidthDetail>
+ <StyledFieldInputFullWidthDetail>
<TextInput
label={t`Address 2`}
placeholder={
@@ -130,7 +118,7 @@ export const RecordFormAddressFieldInput = ({
fullWidth
onChange={handleSubFieldChange('addressStreet2')}
/>
- </StyledFullWidthDetail>
+ </StyledFieldInputFullWidthDetail>
)}
{hasSubField('addressCity') && (
<TextInput
@@ -169,7 +157,7 @@ export const RecordFormAddressFieldInput = ({
dropdownId={`${instanceId}-country`}
/>
)}
- </StyledRecordFormFieldDetails>
+ </StyledFieldInputDetails>
)}
</StyledRecordFormFieldBox>
</FormFieldInputContainer>
diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFullNameFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFullNameFieldInput.tsx
index 99c42f78598..95dee647b64 100644
--- a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFullNameFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFullNameFieldInput.tsx
@@ -1,9 +1,11 @@
import { addCharactersToAvoidPasswordManagers } from '@/object-record/record-field/ui/meta-types/input/utils/addCharactersToAvoidPasswordManagers';
import { type FieldFullNameValue } from '@/object-record/record-field/ui/types/FieldMetadata';
-import { RecordFormFieldDetailsToggleRow } from '@/object-record/record-form/components/RecordFormFieldDetailsToggleRow';
+import { FieldInputDetailsToggleRow } from '@/ui/field/input/components/FieldInputDetailsToggleRow';
import { StyledRecordFormFieldBox } from '@/object-record/record-form/components/StyledRecordFormFieldBox';
-import { StyledRecordFormFieldDetails } from '@/object-record/record-form/components/StyledRecordFormFieldDetails';
-import { splitFullNameInputText } from '@/object-record/record-form/utils/splitFullNameInputText';
+import { StyledFieldInputDetails } from '@/ui/field/input/components/StyledFieldInputDetails';
+import { joinFullName } from '@/object-record/record-field/ui/meta-types/input/utils/joinFullName';
+import { trimFullName } from '@/object-record/record-field/ui/meta-types/input/utils/trimFullName';
+import { splitFullNameInputText } from '@/object-record/record-field/ui/meta-types/input/utils/splitFullNameInputText';
import { StyledTextInput } from '@/ui/field/input/components/TextInput';
import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { TextInput } from '@/ui/input/components/TextInput';
@@ -13,17 +15,6 @@ import { isNonEmptyString } from '@sniptt/guards';
import { useId, useState } from 'react';
import { Field } from 'twenty-ui/primitives/input';
-const joinFullName = ({ firstName, lastName }: FieldFullNameValue) =>
- `${firstName} ${lastName}`.trim();
-
-const trimFullName = ({
- firstName,
- lastName,
-}: FieldFullNameValue): FieldFullNameValue => ({
- firstName: firstName.trim(),
- lastName: lastName.trim(),
-});
-
type RecordFormFullNameFieldInputProps = {
label?: string;
defaultValue?: FieldFullNameValue;
@@ -42,9 +33,10 @@ export const RecordFormFullNameFieldInput = ({
const { t } = useLingui();
const instanceId = useId();
- const [fullName, setFullName] = useState<FieldFullNameValue>(
- defaultValue ?? { firstName: '', lastName: '' },
- );
+ const [fullName, setFullName] = useState<FieldFullNameValue>({
+ firstName: defaultValue?.firstName ?? '',
+ lastName: defaultValue?.lastName ?? '',
+ });
const [fullNameText, setFullNameText] = useState(() =>
joinFullName(fullName),
);
@@ -74,7 +66,7 @@ export const RecordFormFullNameFieldInput = ({
<Field.Label htmlFor={instanceId}>{label}</Field.Label>
) : null}
<StyledRecordFormFieldBox>
- <RecordFormFieldDetailsToggleRow
+ <FieldInputDetailsToggleRow
isExpanded={isExpanded}
toggleLabel={t`Name details`}
onToggle={() => setIsExpanded(!isExpanded)}
@@ -90,9 +82,9 @@ export const RecordFormFullNameFieldInput = ({
value={fullNameText}
onChange={(event) => handleFullNameTextChange(event.target.value)}
/>
- </RecordFormFieldDetailsToggleRow>
+ </FieldInputDetailsToggleRow>
{isExpanded && (
- <StyledRecordFormFieldDetails>
+ <StyledFieldInputDetails>
<TextInput
label={t`First name`}
value={fullName.firstName}
@@ -113,7 +105,7 @@ export const RecordFormFullNameFieldInput = ({
handleNamePartChange({ ...fullName, lastName })
}
/>
- </StyledRecordFormFieldDetails>
+ </StyledFieldInputDetails>
)}
</StyledRecordFormFieldBox>
</FormFieldInputContainer>
diff --git a/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx b/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx
index 2d0cc512dec..10898af7567 100644
--- a/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx
+++ b/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx
@@ -1,3 +1,6 @@
+import { ADDRESS_DETAIL_SUB_FIELDS } from '@/ui/field/input/constants/AddressDetailSubFields';
+import { hasAddressDetailValue } from '@/ui/field/input/utils/hasAddressDetailValue';
+import { StyledFieldInputFullWidthDetail } from '@/ui/field/input/components/StyledFieldInputFullWidthDetail';
import { styled } from '@linaria/react';
import { atom, useAtomValue, useStore } from 'jotai';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -10,7 +13,10 @@ import { TextInput } from '@/ui/input/components/TextInput';
import { AutocompleteRoot } from '@/ui/input/components/AutocompleteRoot';
import { type AddressInputProps } from '@/ui/field/input/types/AddressInputProps';
import { CountrySelect } from '@/ui/input/components/internal/country/components/CountrySelect';
-import { isDefined } from 'twenty-shared/utils';
+import { isDefined, typedObjectEntries } from 'twenty-shared/utils';
+import { FieldInputDetailsToggleRow } from '@/ui/field/input/components/FieldInputDetailsToggleRow';
+import { StyledFieldInputDetails } from '@/ui/field/input/components/StyledFieldInputDetails';
+import { StyledTextInput } from '@/ui/field/input/components/TextInput';
import { Autocomplete } from 'twenty-ui/primitives/input';
import { MOBILE_VIEWPORT } from 'twenty-ui/theme';
import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmptyStringIfWhitespacesOnly';
@@ -25,27 +31,13 @@ import { useFocusManagement } from '@/ui/field/input/hooks/useFocusManagement';
const StyledAddressContainer = styled.div`
display: flex;
flex-direction: column;
- gap: 6px;
- padding: 4px 8px;
-
width: 344px;
@media (max-width: ${MOBILE_VIEWPORT}px) {
- gap: 8px;
- width: auto;
- min-width: 100px;
max-width: 200px;
+ min-width: 100px;
overflow: hidden;
- }
-`;
-
-const StyledHalfRowContainer = styled.div`
- display: grid;
- gap: 8px;
- grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
-
- @media (max-width: ${MOBILE_VIEWPORT}px) {
- grid-template-columns: minmax(0, 1fr);
+ width: auto;
}
`;
@@ -116,8 +108,29 @@ export const AddressInput = ({
[subFields],
);
+ const hasStreet1 = isFieldInputInSubFieldsAddress('addressStreet1');
+ const hasDetails = ADDRESS_DETAIL_SUB_FIELDS.some(
+ isFieldInputInSubFieldsAddress,
+ );
+ const [isExpanded, setIsExpanded] = useState(() =>
+ hasAddressDetailValue({ address: value, subFields }),
+ );
+ const shouldShowDetails = hasDetails && (!hasStreet1 || isExpanded);
+
+ const displayedInputRefs = useMemo(
+ () =>
+ Object.fromEntries(
+ typedObjectEntries(inputRefs).filter(([field]) =>
+ field === 'addressStreet1'
+ ? hasStreet1
+ : shouldShowDetails && isFieldInputInSubFieldsAddress(field),
+ ),
+ ),
+ [inputRefs, hasStreet1, shouldShowDetails, isFieldInputInSubFieldsAddress],
+ );
+
const { getFocusHandler, handleTab, handleShiftTab } = useFocusManagement(
- inputRefs,
+ displayedInputRefs,
internalValue,
onTab,
onShiftTab,
@@ -184,6 +197,10 @@ export const AddressInput = ({
}
setInternalValue(updatedAddress);
+
+ if (hasAddressDetailValue({ address: updatedAddress, subFields })) {
+ setIsExpanded(true);
+ }
},
[
placeAutocompleteData,
@@ -193,6 +210,7 @@ export const AddressInput = ({
internalValueAtom,
setInternalValue,
store,
+ subFields,
],
);
@@ -237,10 +255,12 @@ export const AddressInput = ({
fieldType,
label,
autoFocus = false,
+ isInline = false,
}: {
fieldType: 'addressStreet1' | 'addressCity';
label: string;
autoFocus?: boolean;
+ isInline?: boolean;
}) => (
<StyledInputWithDropdownContainer>
<AutocompleteRoot
@@ -258,19 +278,33 @@ export const AddressInput = ({
}
onClose={closeDropdownOfAutocomplete}
>
- <Autocomplete.Input
- aria-label={label}
- render={(inputProps) => (
- <TextInput
- inputProps={inputProps}
- autoFocus={autoFocus}
- ref={inputRefs[fieldType]}
- label={label}
- fullWidth
- onFocus={getFocusHandler(fieldType)}
- />
- )}
- />
+ {isInline ? (
+ <Autocomplete.Input
+ ref={inputRefs[fieldType]}
+ aria-label={label}
+ placeholder={label}
+ autoFocus={autoFocus}
+ onFocus={getFocusHandler(fieldType)}
+ render={(inputProps) => (
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ <StyledTextInput {...inputProps} />
+ )}
+ />
+ ) : (
+ <Autocomplete.Input
+ aria-label={label}
+ render={(inputProps) => (
+ <TextInput
+ inputProps={inputProps}
+ autoFocus={autoFocus}
+ ref={inputRefs[fieldType]}
+ label={label}
+ fullWidth
+ onFocus={getFocusHandler(fieldType)}
+ />
+ )}
+ />
+ )}
<PlaceAutocompleteSelect
list={placeAutocompleteData}
onChange={handlePlaceSelection}
@@ -281,58 +315,75 @@ export const AddressInput = ({
return (
<StyledAddressContainer ref={wrapperRef}>
- {isFieldInputInSubFieldsAddress('addressStreet1') &&
- renderInputWithAutocomplete({
- fieldType: 'addressStreet1',
- label: t`Address 1`,
- autoFocus: true,
- })}
- {isFieldInputInSubFieldsAddress('addressStreet2') && (
- <TextInput
- value={internalValue.addressStreet2 ?? ''}
- ref={inputRefs.addressStreet2}
- label={t`Address 2`}
- fullWidth
- onChange={getChangeHandler('addressStreet2')}
- onFocus={getFocusHandler('addressStreet2')}
- />
- )}
- <StyledHalfRowContainer>
- {isFieldInputInSubFieldsAddress('addressCity') &&
- renderInputWithAutocomplete({
- fieldType: 'addressCity',
- label: t`City`,
+ {hasStreet1 && (
+ <FieldInputDetailsToggleRow
+ isExpanded={isExpanded}
+ toggleLabel={t`Address details`}
+ hasToggle={hasDetails}
+ onToggle={() => {
+ if (isExpanded) {
+ getFocusHandler('addressStreet1')();
+ }
+ setIsExpanded(!isExpanded);
+ }}
+ >
+ {renderInputWithAutocomplete({
+ fieldType: 'addressStreet1',
+ label: t`Address 1`,
+ autoFocus: true,
+ isInline: true,
})}
- {isFieldInputInSubFieldsAddress('addressState') && (
- <TextInput
- value={internalValue.addressState ?? ''}
- ref={inputRefs.addressState}
- label={t`State`}
- fullWidth
- onChange={getChangeHandler('addressState')}
- onFocus={getFocusHandler('addressState')}
- />
- )}
- </StyledHalfRowContainer>
- <StyledHalfRowContainer>
- {isFieldInputInSubFieldsAddress('addressPostcode') && (
- <TextInput
- value={internalValue.addressPostcode ?? ''}
- ref={inputRefs.addressPostcode}
- label={t`Post Code`}
- fullWidth
- onChange={getChangeHandler('addressPostcode')}
- onFocus={getFocusHandler('addressPostcode')}
- />
- )}
- {isFieldInputInSubFieldsAddress('addressCountry') && (
- <CountrySelect
- label={t`Country`}
- onChange={getChangeHandler('addressCountry')}
- selectedCountryName={internalValue.addressCountry ?? ''}
- />
- )}
- </StyledHalfRowContainer>
+ </FieldInputDetailsToggleRow>
+ )}
+ {shouldShowDetails && (
+ <StyledFieldInputDetails hasSeparator={hasStreet1}>
+ {isFieldInputInSubFieldsAddress('addressStreet2') && (
+ <StyledFieldInputFullWidthDetail>
+ <TextInput
+ value={internalValue.addressStreet2 ?? ''}
+ ref={inputRefs.addressStreet2}
+ label={t`Address 2`}
+ fullWidth
+ onChange={getChangeHandler('addressStreet2')}
+ onFocus={getFocusHandler('addressStreet2')}
+ />
+ </StyledFieldInputFullWidthDetail>
+ )}
+ {isFieldInputInSubFieldsAddress('addressCity') &&
+ renderInputWithAutocomplete({
+ fieldType: 'addressCity',
+ label: t`City`,
+ autoFocus: !hasStreet1,
+ })}
+ {isFieldInputInSubFieldsAddress('addressState') && (
+ <TextInput
+ value={internalValue.addressState ?? ''}
+ ref={inputRefs.addressState}
+ label={t`State`}
+ fullWidth
+ onChange={getChangeHandler('addressState')}
+ onFocus={getFocusHandler('addressState')}
+ />
+ )}
+ {isFieldInputInSubFieldsAddress('addressPostcode') && (
+ <TextInput
+ value={internalValue.addressPostcode ?? ''}
+ ref={inputRefs.addressPostcode}
+ label={t`Post Code`}
+ fullWidth
+ onChange={getChangeHandler('addressPostcode')}
+ onFocus={getFocusHandler('addressPostcode')}
+ />
+ )}
+ {isFieldInputInSubFieldsAddress('addressCountry') && (
+ <CountrySelect
+ label={t`Country`}
+ onChange={getChangeHandler('addressCountry')}
+ selectedCountryName={internalValue.addressCountry ?? ''}
+ />
+ )}
+ </StyledFieldInputDetails>
+ )}
</StyledAddressContainer>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldDetailsToggleRow.tsx b/packages/twenty-front/src/modules/ui/field/input/components/FieldInputDetailsToggleRow.tsx
similarity index 83%
rename from packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldDetailsToggleRow.tsx
rename to packages/twenty-front/src/modules/ui/field/input/components/FieldInputDetailsToggleRow.tsx
index bc5e0333a32..adeef2feff7 100644
--- a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldDetailsToggleRow.tsx
+++ b/packages/twenty-front/src/modules/ui/field/input/components/FieldInputDetailsToggleRow.tsx
@@ -12,7 +12,7 @@ const StyledRow = styled.div`
padding-right: ${themeCssVariables.spacing[1]};
`;
-type RecordFormFieldDetailsToggleRowProps = {
+type FieldInputDetailsToggleRowProps = {
children: ReactNode;
isExpanded: boolean;
toggleLabel: string;
@@ -20,19 +20,20 @@ type RecordFormFieldDetailsToggleRowProps = {
hasToggle?: boolean;
};
-export const RecordFormFieldDetailsToggleRow = ({
+export const FieldInputDetailsToggleRow = ({
children,
isExpanded,
toggleLabel,
onToggle,
hasToggle = true,
-}: RecordFormFieldDetailsToggleRowProps) => (
+}: FieldInputDetailsToggleRowProps) => (
<StyledRow>
{children}
{hasToggle && (
<LightIconButton
aria-label={toggleLabel}
aria-expanded={isExpanded}
+ onMouseDown={(event) => event.preventDefault()}
onClick={onToggle}
>
<IconListDetails />
diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/StyledRecordFormFieldDetails.tsx b/packages/twenty-front/src/modules/ui/field/input/components/StyledFieldInputDetails.tsx
similarity index 87%
rename from packages/twenty-front/src/modules/object-record/record-form/components/StyledRecordFormFieldDetails.tsx
rename to packages/twenty-front/src/modules/ui/field/input/components/StyledFieldInputDetails.tsx
index e5147cc668c..8d74e96f9f2 100644
--- a/packages/twenty-front/src/modules/object-record/record-form/components/StyledRecordFormFieldDetails.tsx
+++ b/packages/twenty-front/src/modules/ui/field/input/components/StyledFieldInputDetails.tsx
@@ -1,7 +1,7 @@
import { styled } from '@linaria/react';
import { themeCssVariables } from 'twenty-ui/theme';
-export const StyledRecordFormFieldDetails = styled.div<{
+export const StyledFieldInputDetails = styled.div<{
hasSeparator?: boolean;
}>`
border-top: ${({ hasSeparator = true }) =>
diff --git a/packages/twenty-front/src/modules/ui/field/input/components/StyledFieldInputFullWidthDetail.tsx b/packages/twenty-front/src/modules/ui/field/input/components/StyledFieldInputFullWidthDetail.tsx
new file mode 100644
index 00000000000..53f6d629e05
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/field/input/components/StyledFieldInputFullWidthDetail.tsx
@@ -0,0 +1,5 @@
+import { styled } from '@linaria/react';
+
+export const StyledFieldInputFullWidthDetail = styled.div`
+ grid-column: 1 / -1;
+`;
diff --git a/packages/twenty-front/src/modules/ui/field/input/constants/AddressDetailSubFields.ts b/packages/twenty-front/src/modules/ui/field/input/constants/AddressDetailSubFields.ts
new file mode 100644
index 00000000000..e3542036833
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/field/input/constants/AddressDetailSubFields.ts
@@ -0,0 +1,9 @@
+import { type AllowedAddressSubField } from 'twenty-shared/types';
+
+export const ADDRESS_DETAIL_SUB_FIELDS = [
+ 'addressStreet2',
+ 'addressCity',
+ 'addressState',
+ 'addressPostcode',
+ 'addressCountry',
+] as const satisfies readonly AllowedAddressSubField[];
diff --git a/packages/twenty-front/src/modules/ui/field/input/utils/hasAddressDetailValue.ts b/packages/twenty-front/src/modules/ui/field/input/utils/hasAddressDetailValue.ts
new file mode 100644
index 00000000000..e9ca801489b
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/field/input/utils/hasAddressDetailValue.ts
@@ -0,0 +1,21 @@
+import { type FieldAddressDraftValue } from '@/object-record/record-field/ui/types/FieldInputDraftValue';
+import { ADDRESS_DETAIL_SUB_FIELDS } from '@/ui/field/input/constants/AddressDetailSubFields';
+import { isNonEmptyString } from '@sniptt/guards';
+import { type AllowedAddressSubField } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+export const hasAddressDetailValue = ({
+ address,
+ subFields,
+}: {
+ address: Pick<
+ FieldAddressDraftValue,
+ (typeof ADDRESS_DETAIL_SUB_FIELDS)[number]
+ >;
+ subFields?: AllowedAddressSubField[] | null;
+}) =>
+ ADDRESS_DETAIL_SUB_FIELDS.some(
+ (subField) =>
+ (!isDefined(subFields) || subFields.includes(subField)) &&
+ isNonEmptyString(address[subField]),
+ );