The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Show address details on demand in the record form (#28765)
Charles Bochet6f4bd66b8b3f
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.tsxnew file mode 100644index 00000000000..32f0f0fddb7--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormAddressFieldInput.tsx@@ -0,0 +1,177 @@+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 { StyledRecordFormFieldBox } from '@/object-record/record-form/components/StyledRecordFormFieldBox';+import { StyledRecordFormFieldDetails } from '@/object-record/record-form/components/StyledRecordFormFieldDetails';+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 { useLingui } from '@lingui/react/macro';+import { isNonEmptyString } from '@sniptt/guards';+import { useId, useState } from 'react';+import { type AllowedAddressSubField } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { Field } from 'twenty-ui/primitives/input';++type AddressTextSubField = Exclude<+ AllowedAddressSubField,+ 'addressLat' | 'addressLng'+>;++const ADDRESS_DETAIL_SUB_FIELDS: AddressTextSubField[] = [+ 'addressStreet2',+ 'addressCity',+ 'addressState',+ 'addressPostcode',+ 'addressCountry',+];++const EMPTY_ADDRESS: FieldAddressValue = {+ addressStreet1: '',+ addressStreet2: '',+ addressCity: '',+ addressState: '',+ addressPostcode: '',+ addressCountry: '',+ addressLat: null,+ addressLng: null,+};++const StyledFullWidthDetail = styled.div`+ grid-column: 1 / -1;+`;++type RecordFormAddressFieldInputProps = {+ label?: string;+ defaultValue?: FieldAddressValue;+ subFields?: AllowedAddressSubField[] | null;+ subFieldPlaceholders?: FormFieldInputSubFieldPlaceholders;+ onChange: (value: FieldAddressValue) => void;+};++export const RecordFormAddressFieldInput = ({+ label,+ defaultValue,+ subFields,+ subFieldPlaceholders,+ onChange,+}: RecordFormAddressFieldInputProps) => {+ const { t } = useLingui();+ const instanceId = useId();++ const [address, setAddress] = useState<FieldAddressValue>({+ ...EMPTY_ADDRESS,+ ...defaultValue,+ });++ const hasSubField = (subField: AllowedAddressSubField) =>+ !isDefined(subFields) || subFields.includes(subField);++ const hasStreet1 = hasSubField('addressStreet1');+ const hasDetails = ADDRESS_DETAIL_SUB_FIELDS.some(hasSubField);++ const [isExpanded, setIsExpanded] = useState(() =>+ ADDRESS_DETAIL_SUB_FIELDS.some((subField) =>+ isNonEmptyString(address[subField]),+ ),+ );++ const shouldShowDetails = hasDetails && (!hasStreet1 || isExpanded);++ const handleSubFieldChange =+ (subField: AddressTextSubField) => (subFieldValue: string) => {+ const updatedAddress = { ...address, [subField]: subFieldValue };++ setAddress(updatedAddress);+ onChange(normalizeAddressFieldValueForPersist(updatedAddress));+ };++ return (+ <FormFieldInputContainer>+ {isNonEmptyString(label) ? (+ <Field.Label htmlFor={hasStreet1 ? instanceId : undefined}>+ {label}+ </Field.Label>+ ) : null}+ <StyledRecordFormFieldBox>+ {hasStreet1 && (+ <RecordFormFieldDetailsToggleRow+ isExpanded={isExpanded}+ toggleLabel={t`Address details`}+ hasToggle={hasDetails}+ onToggle={() => setIsExpanded(!isExpanded)}+ >+ <StyledTextInput+ id={instanceId}+ autoComplete="off"+ placeholder={+ subFieldPlaceholders?.addressStreet1 ?? t`Street address`+ }+ value={address.addressStreet1 ?? ''}+ onChange={(event) =>+ handleSubFieldChange('addressStreet1')(event.target.value)+ }+ />+ </RecordFormFieldDetailsToggleRow>+ )}+ {shouldShowDetails && (+ <StyledRecordFormFieldDetails hasSeparator={hasStreet1}>+ {hasSubField('addressStreet2') && (+ <StyledFullWidthDetail>+ <TextInput+ label={t`Address 2`}+ placeholder={+ subFieldPlaceholders?.addressStreet2 ?? t`Street address 2`+ }+ value={address.addressStreet2 ?? ''}+ fullWidth+ onChange={handleSubFieldChange('addressStreet2')}+ />+ </StyledFullWidthDetail>+ )}+ {hasSubField('addressCity') && (+ <TextInput+ label={t`City`}+ placeholder={subFieldPlaceholders?.addressCity ?? t`City`}+ value={address.addressCity ?? ''}+ fullWidth+ onChange={handleSubFieldChange('addressCity')}+ />+ )}+ {hasSubField('addressState') && (+ <TextInput+ label={t`State`}+ placeholder={subFieldPlaceholders?.addressState ?? t`State`}+ value={address.addressState ?? ''}+ fullWidth+ onChange={handleSubFieldChange('addressState')}+ />+ )}+ {hasSubField('addressPostcode') && (+ <TextInput+ label={t`Post Code`}+ placeholder={+ subFieldPlaceholders?.addressPostcode ?? t`Post Code`+ }+ value={address.addressPostcode ?? ''}+ fullWidth+ onChange={handleSubFieldChange('addressPostcode')}+ />+ )}+ {hasSubField('addressCountry') && (+ <CountrySelect+ label={t`Country`}+ selectedCountryName={address.addressCountry ?? ''}+ onChange={handleSubFieldChange('addressCountry')}+ dropdownId={`${instanceId}-country`}+ />+ )}+ </StyledRecordFormFieldDetails>+ )}+ </StyledRecordFormFieldBox>+ </FormFieldInputContainer>+ );+};diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldDetailsToggleRow.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldDetailsToggleRow.tsxnew file mode 100644index 00000000000..bc5e0333a32--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldDetailsToggleRow.tsx@@ -0,0 +1,42 @@+import { styled } from '@linaria/react';+import { type ReactNode } from 'react';+import { LightIconButton } from 'twenty-ui/components/input';+import { IconListDetails } from 'twenty-ui/icon';+import { themeCssVariables } from 'twenty-ui/theme';++const StyledRow = styled.div`+ align-items: center;+ display: flex;+ gap: ${themeCssVariables.spacing[1]};+ height: ${themeCssVariables.spacing[8]};+ padding-right: ${themeCssVariables.spacing[1]};+`;++type RecordFormFieldDetailsToggleRowProps = {+ children: ReactNode;+ isExpanded: boolean;+ toggleLabel: string;+ onToggle: () => void;+ hasToggle?: boolean;+};++export const RecordFormFieldDetailsToggleRow = ({+ children,+ isExpanded,+ toggleLabel,+ onToggle,+ hasToggle = true,+}: RecordFormFieldDetailsToggleRowProps) => (+ <StyledRow>+ {children}+ {hasToggle && (+ <LightIconButton+ aria-label={toggleLabel}+ aria-expanded={isExpanded}+ onClick={onToggle}+ >+ <IconListDetails />+ </LightIconButton>+ )}+ </StyledRow>+);diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldInput.tsxindex a455f2dc9da..7c5864220d0 100644--- a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldInput.tsx+++ b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormFieldInput.tsx@@ -4,6 +4,8 @@ import { recordFieldInputIsFieldInErrorComponentState } from '@/object-record/reimport { type FormFieldInputSubFieldPlaceholders } from '@/object-record/record-field/ui/form-types/types/FormFieldInputSubFieldPlaceholders';import { type FieldDefinition } from '@/object-record/record-field/ui/types/FieldDefinition';import { type FieldMetadata } from '@/object-record/record-field/ui/types/FieldMetadata';+import { isFieldAddress } from '@/object-record/record-field/ui/types/guards/isFieldAddress';+import { isFieldAddressValue } from '@/object-record/record-field/ui/types/guards/isFieldAddressValue';import { isFieldArray } from '@/object-record/record-field/ui/types/guards/isFieldArray';import { isFieldArrayValue } from '@/object-record/record-field/ui/types/guards/isFieldArrayValue';import { isFieldBoolean } from '@/object-record/record-field/ui/types/guards/isFieldBoolean';@@ -22,6 +24,7 @@ import { isFieldNumber } from '@/object-record/record-field/ui/types/guards/isFiimport { isFieldNumberValue } from '@/object-record/record-field/ui/types/guards/isFieldNumberValue';import { isFieldPhones } from '@/object-record/record-field/ui/types/guards/isFieldPhones';import { isFieldPhonesValue } from '@/object-record/record-field/ui/types/guards/isFieldPhonesValue';+import { RecordFormAddressFieldInput } from '@/object-record/record-form/components/RecordFormAddressFieldInput';import { RecordFormArrayFieldInput } from '@/object-record/record-form/components/RecordFormArrayFieldInput';import { RecordFormBooleanFieldInput } from '@/object-record/record-form/components/RecordFormBooleanFieldInput';import { RecordFormCurrencyFieldInput } from '@/object-record/record-form/components/RecordFormCurrencyFieldInput';@@ -35,7 +38,7 @@ import { getRecordFormCurrencyFieldDefaultValue } from '@/object-record/record-fimport { getLinksVariant } from '@/object-record/spreadsheet-import/utils/getLinksVariant';import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';import { isNonEmptyString } from '@sniptt/guards';-import { isValidCountryCode } from 'twenty-shared/utils';+import { isDefined, isValidCountryCode } from 'twenty-shared/utils';import { type JsonValue } from 'type-fest';import { FieldMetadataType } from '~/generated-metadata/graphql';import { stripSimpleQuotesFromString } from '~/utils/string/stripSimpleQuotesFromString';@@ -123,6 +126,26 @@ export const RecordFormFieldInput = ({);}+ if (isFieldAddress(field) && !readonly) {+ const settings = field.metadata.settings;++ return (+ <RecordFormAddressFieldInput+ label={field.label}+ defaultValue={+ isFieldAddressValue(defaultValue) ? defaultValue : undefined+ }+ subFields={+ isDefined(settings) && 'subFields' in settings+ ? settings.subFields+ : undefined+ }+ subFieldPlaceholders={subFieldPlaceholders}+ onChange={onChange}+ />+ );+ }+if (isFieldFullName(field) && !readonly) {return (<RecordFormFullNameFieldInputdiff --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.tsxindex 70e1fc1251c..99c42f78598 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,35 +1,17 @@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 { 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 { StyledTextInput } from '@/ui/field/input/components/TextInput';import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';import { TextInput } from '@/ui/input/components/TextInput';import { PASSWORD_MANAGER_IGNORE_ATTRIBUTES } from '@/ui/input/constants/PasswordManagerIgnoreAttributes';-import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';import { isNonEmptyString } from '@sniptt/guards';import { useId, useState } from 'react';-import { LightIconButton } from 'twenty-ui/components/input';-import { IconListDetails } from 'twenty-ui/icon';import { Field } from 'twenty-ui/primitives/input';-import { themeCssVariables } from 'twenty-ui/theme';--const StyledFullNameRow = styled.div`- align-items: center;- display: flex;- gap: ${themeCssVariables.spacing[1]};- height: ${themeCssVariables.spacing[8]};- padding-right: ${themeCssVariables.spacing[1]};-`;--const StyledNameDetails = styled.div`- border-top: 1px solid ${themeCssVariables.border.color.light};- display: grid;- gap: ${themeCssVariables.spacing[2]};- grid-template-columns: 1fr 1fr;- padding: ${themeCssVariables.spacing[2]};-`;const joinFullName = ({ firstName, lastName }: FieldFullNameValue) =>`${firstName} ${lastName}`.trim();@@ -92,7 +74,11 @@ export const RecordFormFullNameFieldInput = ({<Field.Label htmlFor={instanceId}>{label}</Field.Label>) : null}<StyledRecordFormFieldBox>- <StyledFullNameRow>+ <RecordFormFieldDetailsToggleRow+ isExpanded={isExpanded}+ toggleLabel={t`Name details`}+ onToggle={() => setIsExpanded(!isExpanded)}+ ><StyledTextInputid={instanceId}autoComplete="off"@@ -104,16 +90,9 @@ export const RecordFormFullNameFieldInput = ({value={fullNameText}onChange={(event) => handleFullNameTextChange(event.target.value)}/>- <LightIconButton- aria-label={t`Name details`}- aria-expanded={isExpanded}- onClick={() => setIsExpanded(!isExpanded)}- >- <IconListDetails />- </LightIconButton>- </StyledFullNameRow>+ </RecordFormFieldDetailsToggleRow>{isExpanded && (- <StyledNameDetails>+ <StyledRecordFormFieldDetails><TextInputlabel={t`First name`}value={fullName.firstName}@@ -134,7 +113,7 @@ export const RecordFormFullNameFieldInput = ({handleNamePartChange({ ...fullName, lastName })}/>- </StyledNameDetails>+ </StyledRecordFormFieldDetails>)}</StyledRecordFormFieldBox></FormFieldInputContainer>diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/StyledRecordFormFieldDetails.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/StyledRecordFormFieldDetails.tsxnew file mode 100644index 00000000000..e5147cc668c--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-form/components/StyledRecordFormFieldDetails.tsx@@ -0,0 +1,15 @@+import { styled } from '@linaria/react';+import { themeCssVariables } from 'twenty-ui/theme';++export const StyledRecordFormFieldDetails = styled.div<{+ hasSeparator?: boolean;+}>`+ border-top: ${({ hasSeparator = true }) =>+ hasSeparator+ ? `1px solid ${themeCssVariables.border.color.light}`+ : 'none'};+ display: grid;+ gap: ${themeCssVariables.spacing[2]};+ grid-template-columns: 1fr 1fr;+ padding: ${themeCssVariables.spacing[2]};+`;diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/__stories__/RecordFormFieldInputs.stories.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/__stories__/RecordFormFieldInputs.stories.tsxindex d0bc0bb8d3d..c60aa8ca4f8 100644--- a/packages/twenty-front/src/modules/object-record/record-form/components/__stories__/RecordFormFieldInputs.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-form/components/__stories__/RecordFormFieldInputs.stories.tsx@@ -101,6 +101,15 @@ const nameFieldMetadataItem: FieldMetadataItem = {label: 'Name',};+const addressFieldMetadataItem: FieldMetadataItem = {+ ...getMockFieldMetadataItemOrThrow({+ objectMetadataItem: companyObjectMetadataItem,+ fieldName: 'address',+ }),+ label: 'Address',+ settings: null,+};+type RecordFormFieldInputsWithDraftProps = {fieldMetadataItems: FieldMetadataItem[];initialDraftRecord?: Partial<ObjectRecord>;@@ -727,3 +736,68 @@ export const FullName: Story = {);},};++export const Address: Story = {+ args: {+ fieldMetadataItems: [addressFieldMetadataItem],+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.queryByRole('textbox', { name: 'City' }),+ ).not.toBeInTheDocument();++ await userEvent.type(+ canvas.getByRole('textbox', { name: 'Address' }),+ '12 rue de Rivoli',+ );+ await userEvent.click(+ canvas.getByRole('button', { name: 'Address details' }),+ );+ await userEvent.type(+ canvas.getByRole('textbox', { name: 'City' }),+ 'Paris',+ );++ await expect(args.onFieldValueChange).toHaveBeenLastCalledWith(+ 'address',+ expect.objectContaining({+ addressStreet1: '12 rue de Rivoli',+ addressCity: 'Paris',+ }),+ );+ },+};++export const StoredAddressShowsDetails: Story = {+ args: {+ fieldMetadataItems: [addressFieldMetadataItem],+ initialDraftRecord: {+ address: {+ addressStreet1: '12 rue de Rivoli',+ addressStreet2: '',+ addressCity: 'Paris',+ addressState: '',+ addressPostcode: '75001',+ addressCountry: 'France',+ addressLat: null,+ addressLng: null,+ },+ },+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByRole('textbox', { name: 'Address' })).toHaveValue(+ '12 rue de Rivoli',+ );+ await expect(canvas.getByRole('textbox', { name: 'City' })).toHaveValue(+ 'Paris',+ );+ await expect(+ canvas.getByRole('textbox', { name: 'Post Code' }),+ ).toHaveValue('75001');+ await expect(args.onFieldValueChange).not.toHaveBeenCalled();+ },+};diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/CountrySelect.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/CountrySelect.tsxindex 0ff98938773..cb328f0ce5a 100644--- a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/CountrySelect.tsx+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/CountrySelect.tsx@@ -22,21 +22,23 @@ type CountrySelectProps = {label: string;selectedCountryName: string;onChange: (countryName: string) => void;+ dropdownId?: string;};export const CountrySelect = ({label,selectedCountryName,onChange,+ dropdownId = SELECT_COUNTRY_DROPDOWN_ID,}: CountrySelectProps) => {const countries = useCountries();const parentClickOutsideId = useContext(ParentClickOutsideIdContext);const isDropdownOpen = useAtomComponentStateValue(isDropdownOpenComponentState,- SELECT_COUNTRY_DROPDOWN_ID,+ dropdownId,);const { handleDropdownOpenChange } = useHandleDropdownOpenChange({- dropdownId: SELECT_COUNTRY_DROPDOWN_ID,+ dropdownId,});const countryChoices = useMemo<CountryChoice[]>(@@ -65,7 +67,7 @@ export const CountrySelect = ({return (<>- <DropdownCleanupEffect dropdownId={SELECT_COUNTRY_DROPDOWN_ID} />+ <DropdownCleanupEffect dropdownId={dropdownId} /><SharedCountrySelectcountries={countryChoices}value={selectedCountryValue}