feat: add Relation field form (#2572)

* feat: add useCreateOneRelationMetadata and useRelationMetadata

Closes #2423

* feat: add Relation field form

Closes #2003

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
Thaïs
2023-11-17 23:38:39 +01:00
committed by GitHub
parent fea0bbeb2a
commit 18dac1a2b6
34 changed files with 1285 additions and 643 deletions

View File

@ -1,30 +1,25 @@
import { useEffect } from 'react';
import { useTheme } from '@emotion/react';
import styled from '@emotion/styled';
import { useRecoilState } from 'recoil';
import { parseFieldType } from '@/object-metadata/utils/parseFieldType';
import { useFindManyObjectRecords } from '@/object-record/hooks/useFindManyObjectRecords';
import { Tag } from '@/ui/display/tag/components/Tag';
import { useLazyLoadIcon } from '@/ui/input/hooks/useLazyLoadIcon';
import { FieldDisplay } from '@/ui/object/field/components/FieldDisplay';
import { FieldContext } from '@/ui/object/field/contexts/FieldContext';
import { BooleanFieldInput } from '@/ui/object/field/meta-types/input/components/BooleanFieldInput';
import { entityFieldsFamilySelector } from '@/ui/object/field/states/selectors/entityFieldsFamilySelector';
import { FieldMetadataType } from '~/generated/graphql';
import { assertNotNull } from '~/utils/assert';
import { Field } from '~/generated/graphql';
import { FieldMetadataType } from '~/generated-metadata/graphql';
import { SettingsObjectFieldPreviewValueEffect } from '../components/SettingsObjectFieldPreviewValueEffect';
import { dataTypes } from '../constants/dataTypes';
import { useFieldPreview } from '../hooks/useFieldPreview';
import { useRelationFieldPreview } from '../hooks/useRelationFieldPreview';
export type SettingsObjectFieldPreviewProps = {
fieldIconKey?: string | null;
fieldLabel: string;
fieldName?: string;
fieldType: FieldMetadataType;
isObjectCustom: boolean;
objectIconKey?: string | null;
objectLabelPlural: string;
objectNamePlural: string;
className?: string;
fieldMetadata: Pick<Field, 'icon' | 'label' | 'type'> & { id?: string };
objectMetadataId: string;
relationObjectMetadataId?: string;
shrink?: boolean;
};
const StyledContainer = styled.div`
@ -52,7 +47,7 @@ const StyledObjectName = styled.div`
gap: ${({ theme }) => theme.spacing(1)};
`;
const StyledFieldPreview = styled.div`
const StyledFieldPreview = styled.div<{ shrink?: boolean }>`
align-items: center;
background-color: ${({ theme }) => theme.background.primary};
border: 1px solid ${({ theme }) => theme.border.color.medium};
@ -61,7 +56,8 @@ const StyledFieldPreview = styled.div`
gap: ${({ theme }) => theme.spacing(2)};
height: ${({ theme }) => theme.spacing(8)};
overflow: hidden;
padding: 0 ${({ theme }) => theme.spacing(2)};
padding: 0
${({ shrink, theme }) => (shrink ? theme.spacing(1) : theme.spacing(2))};
white-space: nowrap;
`;
@ -73,41 +69,41 @@ const StyledFieldLabel = styled.div`
`;
export const SettingsObjectFieldPreview = ({
fieldIconKey,
fieldLabel,
fieldName,
fieldType,
isObjectCustom,
objectIconKey,
objectLabelPlural,
objectNamePlural,
className,
fieldMetadata,
objectMetadataId,
relationObjectMetadataId,
shrink,
}: SettingsObjectFieldPreviewProps) => {
const theme = useTheme();
const { Icon: ObjectIcon } = useLazyLoadIcon(objectIconKey ?? '');
const { Icon: FieldIcon } = useLazyLoadIcon(fieldIconKey ?? '');
const { objects } = useFindManyObjectRecords({
objectNamePlural,
skip: !fieldName,
const {
entityId,
FieldIcon,
fieldName,
hasValue,
ObjectIcon,
objectMetadataItem,
value,
} = useFieldPreview({
fieldMetadata,
objectMetadataId,
});
const [fieldValue, setFieldValue] = useRecoilState(
entityFieldsFamilySelector({
entityId: objects[0]?.id ?? objectNamePlural,
fieldName: fieldName || 'new-field',
}),
);
const { defaultValue: relationDefaultValue, entityChipDisplayMapper } =
useRelationFieldPreview({
relationObjectMetadataId,
skipDefaultValue:
fieldMetadata.type !== FieldMetadataType.Relation || hasValue,
});
useEffect(() => {
setFieldValue(
fieldName && assertNotNull(objects[0]?.[fieldName])
? objects[0][fieldName]
: dataTypes[fieldType].defaultValue,
);
}, [fieldName, fieldType, fieldValue, objects, setFieldValue]);
const defaultValue =
fieldMetadata.type === FieldMetadataType.Relation
? relationDefaultValue
: dataTypes[fieldMetadata.type].defaultValue;
return (
<StyledContainer>
<StyledContainer className={className}>
<StyledObjectSummary>
<StyledObjectName>
{!!ObjectIcon && (
@ -116,15 +112,20 @@ export const SettingsObjectFieldPreview = ({
stroke={theme.icon.stroke.sm}
/>
)}
{objectLabelPlural}
{objectMetadataItem?.labelPlural}
</StyledObjectName>
{isObjectCustom ? (
{objectMetadataItem?.isCustom ? (
<Tag color="orange" text="Custom" />
) : (
<Tag color="blue" text="Standard" />
)}
</StyledObjectSummary>
<StyledFieldPreview>
<SettingsObjectFieldPreviewValueEffect
entityId={entityId}
fieldName={fieldName}
value={value ?? defaultValue}
/>
<StyledFieldPreview shrink={shrink}>
<StyledFieldLabel>
{!!FieldIcon && (
<FieldIcon
@ -132,22 +133,26 @@ export const SettingsObjectFieldPreview = ({
stroke={theme.icon.stroke.sm}
/>
)}
{fieldLabel}:
{fieldMetadata.label}:
</StyledFieldLabel>
<FieldContext.Provider
value={{
entityId: objects[0]?.id ?? objectNamePlural,
entityId,
fieldDefinition: {
type: parseFieldType(fieldType as FieldMetadataType),
type: parseFieldType(fieldMetadata.type),
Icon: FieldIcon,
fieldMetadataId: '',
label: fieldLabel,
metadata: { fieldName: fieldName || 'new-field' },
fieldMetadataId: fieldMetadata.id || '',
label: fieldMetadata.label,
metadata: { fieldName },
entityChipDisplayMapper:
fieldMetadata.type === FieldMetadataType.Relation
? entityChipDisplayMapper
: undefined,
},
hotkeyScope: 'field-preview',
}}
>
{fieldType === 'BOOLEAN' ? (
{fieldMetadata.type === FieldMetadataType.Boolean ? (
<BooleanFieldInput readonly />
) : (
<FieldDisplay />

View File

@ -0,0 +1,29 @@
import { useEffect } from 'react';
import { useRecoilState } from 'recoil';
import { entityFieldsFamilySelector } from '@/ui/object/field/states/selectors/entityFieldsFamilySelector';
type SettingsObjectFieldPreviewValueEffectProps = {
entityId: string;
fieldName: string;
value: unknown;
};
export const SettingsObjectFieldPreviewValueEffect = ({
entityId,
fieldName,
value,
}: SettingsObjectFieldPreviewValueEffectProps) => {
const [, setFieldValue] = useRecoilState(
entityFieldsFamilySelector({
entityId,
fieldName,
}),
);
useEffect(() => {
setFieldValue(value);
}, [value, setFieldValue]);
return null;
};

View File

@ -0,0 +1,123 @@
import styled from '@emotion/styled';
import { useObjectMetadataItemForSettings } from '@/object-metadata/hooks/useObjectMetadataItemForSettings';
import { validateMetadataLabel } from '@/object-metadata/utils/validateMetadataLabel';
import { IconPicker } from '@/ui/input/components/IconPicker';
import { Select } from '@/ui/input/components/Select';
import { TextInput } from '@/ui/input/components/TextInput';
import { useLazyLoadIcons } from '@/ui/input/hooks/useLazyLoadIcons';
import { Field } from '~/generated-metadata/graphql';
import { relationTypes } from '../constants/relationTypes';
import { RelationType } from '../types/RelationType';
export type SettingsObjectFieldRelationFormValues = Partial<{
field: Partial<Pick<Field, 'icon' | 'label'>>;
objectMetadataId: string;
type: RelationType;
}>;
type SettingsObjectFieldRelationFormProps = {
disableRelationEdition?: boolean;
onChange: (values: SettingsObjectFieldRelationFormValues) => void;
values?: SettingsObjectFieldRelationFormValues;
};
const StyledSelectsContainer = styled.div`
display: grid;
gap: ${({ theme }) => theme.spacing(4)};
grid-template-columns: 1fr 1fr;
margin-bottom: ${({ theme }) => theme.spacing(4)};
`;
const StyledInputsLabel = styled.span`
color: ${({ theme }) => theme.font.color.light};
display: block;
font-size: ${({ theme }) => theme.font.size.xs};
font-weight: ${({ theme }) => theme.font.weight.semiBold};
margin-bottom: ${({ theme }) => theme.spacing(1)};
text-transform: uppercase;
`;
const StyledInputsContainer = styled.div`
display: flex;
gap: ${({ theme }) => theme.spacing(2)};
width: 100%;
`;
export const SettingsObjectFieldRelationForm = ({
disableRelationEdition,
onChange,
values,
}: SettingsObjectFieldRelationFormProps) => {
const { icons } = useLazyLoadIcons();
const { objectMetadataItems, findObjectMetadataItemById } =
useObjectMetadataItemForSettings();
const selectedObjectMetadataItem =
(values?.objectMetadataId
? findObjectMetadataItemById(values.objectMetadataId)
: undefined) || objectMetadataItems[0];
return (
<div>
<StyledSelectsContainer>
<Select
label="Relation type"
dropdownScopeId="relation-type-select"
disabled={disableRelationEdition}
value={values?.type}
options={Object.entries(relationTypes).map(
([value, { label, Icon }]) => ({
label,
value: value as RelationType,
Icon,
}),
)}
onChange={(value) => onChange({ type: value })}
/>
<Select
label="Object destination"
dropdownScopeId="object-destination-select"
disabled={disableRelationEdition}
value={values?.objectMetadataId}
options={objectMetadataItems.map((objectMetadataItem) => ({
label: objectMetadataItem.labelPlural,
value: objectMetadataItem.id,
Icon: objectMetadataItem.icon
? icons[objectMetadataItem.icon]
: undefined,
}))}
onChange={(value) => onChange({ objectMetadataId: value })}
/>
</StyledSelectsContainer>
<StyledInputsLabel>
Field on {selectedObjectMetadataItem?.labelPlural}
</StyledInputsLabel>
<StyledInputsContainer>
<IconPicker
dropdownScopeId="field-destination-icon-picker"
selectedIconKey={values?.field?.icon || undefined}
onChange={(value) =>
onChange({
field: { ...values?.field, icon: value.iconKey },
})
}
variant="primary"
/>
<TextInput
placeholder="Field name"
value={values?.field?.label || ''}
onChange={(value) => {
if (!value || validateMetadataLabel(value)) {
onChange({
field: { ...values?.field, label: value },
});
}
}}
fullWidth
/>
</StyledInputsContainer>
</div>
);
};

View File

@ -27,6 +27,11 @@ const StyledTitle = styled.h3`
margin-bottom: ${({ theme }) => theme.spacing(4)};
`;
const StyledPreviewContent = styled.div`
display: flex;
gap: 6px;
`;
const StyledFormContainer = styled.div`
background-color: ${({ theme }) => theme.background.secondary};
border: 1px solid ${({ theme }) => theme.border.color.medium};
@ -46,7 +51,7 @@ export const SettingsObjectFieldTypeCard = ({
<div className={className}>
<StyledPreviewContainer>
<StyledTitle>Preview</StyledTitle>
{preview}
<StyledPreviewContent>{preview}</StyledPreviewContent>
</StyledPreviewContainer>
{!!form && <StyledFormContainer>{form}</StyledFormContainer>}
</div>

View File

@ -3,82 +3,142 @@ import styled from '@emotion/styled';
import { H2Title } from '@/ui/display/typography/components/H2Title';
import { Select } from '@/ui/input/components/Select';
import { Section } from '@/ui/layout/section/components/Section';
import { FieldMetadataType } from '~/generated-metadata/graphql';
import { Field, FieldMetadataType } from '~/generated-metadata/graphql';
import { dataTypes } from '../constants/dataTypes';
import { relationTypes } from '../constants/relationTypes';
import {
SettingsObjectFieldPreview,
SettingsObjectFieldPreviewProps,
} from './SettingsObjectFieldPreview';
import {
SettingsObjectFieldRelationForm,
SettingsObjectFieldRelationFormValues,
} from './SettingsObjectFieldRelationForm';
import { SettingsObjectFieldTypeCard } from './SettingsObjectFieldTypeCard';
export type SettingsObjectFieldTypeSelectSectionFormValues = Partial<{
type: FieldMetadataType;
relation: SettingsObjectFieldRelationFormValues;
}>;
type SettingsObjectFieldTypeSelectSectionProps = {
disabled?: boolean;
onChange?: (value: FieldMetadataType) => void;
} & Pick<
SettingsObjectFieldPreviewProps,
| 'fieldIconKey'
| 'fieldLabel'
| 'fieldName'
| 'fieldType'
| 'isObjectCustom'
| 'objectIconKey'
| 'objectLabelPlural'
| 'objectNamePlural'
>;
fieldMetadata: Pick<Field, 'icon' | 'label'> & { id?: string };
relationFieldMetadataId?: string;
onChange: (values: SettingsObjectFieldTypeSelectSectionFormValues) => void;
values?: SettingsObjectFieldTypeSelectSectionFormValues;
} & Pick<SettingsObjectFieldPreviewProps, 'objectMetadataId'>;
const StyledSettingsObjectFieldTypeCard = styled(SettingsObjectFieldTypeCard)`
margin-top: ${({ theme }) => theme.spacing(4)};
`;
// TODO: remove "enum" and "relation" types for now, add them back when the backend is ready.
const { ENUM: _ENUM, RELATION: _RELATION, ...allowedDataTypes } = dataTypes;
const StyledSettingsObjectFieldPreview = styled(SettingsObjectFieldPreview)`
display: grid;
flex: 1 1 100%;
`;
const StyledRelationImage = styled.img<{ flip?: boolean }>`
transform: ${({ flip }) => (flip ? 'scaleX(-1)' : 'none')};
width: 54px;
`;
export const SettingsObjectFieldTypeSelectSection = ({
disabled,
fieldIconKey,
fieldLabel,
fieldName,
fieldType,
isObjectCustom,
objectIconKey,
objectLabelPlural,
objectNamePlural,
fieldMetadata,
relationFieldMetadataId,
objectMetadataId,
onChange,
}: SettingsObjectFieldTypeSelectSectionProps) => (
<Section>
<H2Title
title="Type and values"
description="The field's type and values."
/>
<Select
disabled={disabled}
dropdownScopeId="object-field-type-select"
value={fieldType}
onChange={onChange}
options={Object.entries(allowedDataTypes).map(([key, dataType]) => ({
value: key as FieldMetadataType,
...dataType,
}))}
/>
{['BOOLEAN', 'DATE', 'MONEY', 'NUMBER', 'TEXT', 'URL'].includes(
fieldType,
) && (
<StyledSettingsObjectFieldTypeCard
preview={
<SettingsObjectFieldPreview
fieldIconKey={fieldIconKey}
fieldLabel={fieldLabel}
fieldName={fieldName}
fieldType={fieldType}
isObjectCustom={isObjectCustom}
objectIconKey={objectIconKey}
objectLabelPlural={objectLabelPlural}
objectNamePlural={objectNamePlural}
/>
}
values,
}: SettingsObjectFieldTypeSelectSectionProps) => {
const relationFormConfig = values?.relation;
const allowedFieldTypes = Object.entries(dataTypes).filter(
([key]) => key !== FieldMetadataType.Relation,
);
return (
<Section>
<H2Title
title="Type and values"
description="The field's type and values."
/>
)}
</Section>
);
<Select
disabled={!!fieldMetadata.id}
dropdownScopeId="object-field-type-select"
value={values?.type}
onChange={(value) => onChange({ type: value })}
options={allowedFieldTypes.map(([key, dataType]) => ({
value: key as FieldMetadataType,
...dataType,
}))}
/>
{!!values?.type &&
[
FieldMetadataType.Boolean,
FieldMetadataType.Currency,
FieldMetadataType.Date,
FieldMetadataType.Link,
FieldMetadataType.Number,
FieldMetadataType.Relation,
FieldMetadataType.Text,
].includes(values.type) && (
<StyledSettingsObjectFieldTypeCard
preview={
<>
<StyledSettingsObjectFieldPreview
fieldMetadata={{
...fieldMetadata,
type: values.type,
}}
shrink={values.type === FieldMetadataType.Relation}
objectMetadataId={objectMetadataId}
relationObjectMetadataId={
relationFormConfig?.objectMetadataId
}
/>
{values.type === FieldMetadataType.Relation &&
!!relationFormConfig?.type &&
!!relationFormConfig.objectMetadataId && (
<>
<StyledRelationImage
src={relationTypes[relationFormConfig.type].imageSrc}
flip={
relationTypes[relationFormConfig.type].isImageFlipped
}
alt={relationTypes[relationFormConfig.type].label}
/>
<StyledSettingsObjectFieldPreview
fieldMetadata={{
...relationFormConfig.field,
label:
relationFormConfig.field?.label || 'Field name',
type: FieldMetadataType.Relation,
id: relationFieldMetadataId,
}}
shrink
objectMetadataId={relationFormConfig.objectMetadataId}
relationObjectMetadataId={objectMetadataId}
/>
</>
)}
</>
}
form={
values.type === FieldMetadataType.Relation && (
<SettingsObjectFieldRelationForm
disableRelationEdition={!!relationFieldMetadataId}
values={relationFormConfig}
onChange={(nextValues) =>
onChange({
relation: { ...relationFormConfig, ...nextValues },
})
}
/>
)
}
/>
)}
</Section>
);
};

View File

@ -1,91 +0,0 @@
import { MemoryRouter } from 'react-router-dom';
import { Meta, StoryObj } from '@storybook/react';
import { FieldMetadataType } from '~/generated-metadata/graphql';
import { ComponentDecorator } from '~/testing/decorators/ComponentDecorator';
import { SettingsObjectFieldPreview } from '../SettingsObjectFieldPreview';
const meta: Meta<typeof SettingsObjectFieldPreview> = {
title: 'Modules/Settings/DataModel/SettingsObjectFieldPreview',
component: SettingsObjectFieldPreview,
decorators: [ComponentDecorator],
args: {
fieldIconKey: 'IconNotes',
fieldLabel: 'Description',
fieldType: FieldMetadataType.Text,
isObjectCustom: false,
objectIconKey: 'IconBuildingSkyscraper',
objectLabelPlural: 'Companies',
objectNamePlural: 'companies',
},
};
export default meta;
type Story = StoryObj<typeof SettingsObjectFieldPreview>;
export const Text: Story = {};
export const Boolean: Story = {
args: {
fieldIconKey: 'IconHeadphones',
fieldLabel: 'Priority Support',
fieldType: FieldMetadataType.Boolean,
},
};
export const Currency: Story = {
args: {
fieldIconKey: 'IconCurrencyDollar',
fieldLabel: 'Amount',
fieldType: FieldMetadataType.Currency,
},
};
export const Date: Story = {
args: {
fieldIconKey: 'IconCalendarEvent',
fieldLabel: 'Registration Date',
fieldType: FieldMetadataType.Date,
},
};
export const Link: Story = {
decorators: [
(Story) => (
<MemoryRouter>
<Story />
</MemoryRouter>
),
],
args: {
fieldIconKey: 'IconWorldWww',
fieldLabel: 'Website',
fieldType: FieldMetadataType.Link,
},
};
export const Number: Story = {
args: {
fieldIconKey: 'IconUsers',
fieldLabel: 'Employees',
fieldType: FieldMetadataType.Number,
},
};
export const Select: Story = {
args: {
fieldIconKey: 'IconBuildingFactory2',
fieldLabel: 'Industry',
fieldType: FieldMetadataType.Enum,
},
};
export const CustomObject: Story = {
args: {
isObjectCustom: true,
objectIconKey: 'IconApps',
objectLabelPlural: 'Workspaces',
objectNamePlural: 'workspaces',
},
};

View File

@ -1,36 +0,0 @@
import { Meta, StoryObj } from '@storybook/react';
import { TextInput } from '@/ui/input/components/TextInput';
import { FieldMetadataType } from '~/generated/graphql';
import { ComponentDecorator } from '~/testing/decorators/ComponentDecorator';
import { SettingsObjectFieldPreview } from '../SettingsObjectFieldPreview';
import { SettingsObjectFieldTypeCard } from '../SettingsObjectFieldTypeCard';
const meta: Meta<typeof SettingsObjectFieldTypeCard> = {
title: 'Modules/Settings/DataModel/SettingsObjectFieldTypeCard',
component: SettingsObjectFieldTypeCard,
decorators: [ComponentDecorator],
args: {
preview: (
<SettingsObjectFieldPreview
fieldIconKey="IconNotes"
fieldLabel="Description"
fieldType={FieldMetadataType.Text}
isObjectCustom={false}
objectIconKey="IconUser"
objectLabelPlural="People"
objectNamePlural="people"
/>
),
},
};
export default meta;
type Story = StoryObj<typeof SettingsObjectFieldTypeCard>;
export const Default: Story = {};
export const WithForm: Story = {
args: { form: <TextInput label="Lorem ipsum" placeholder="Lorem ipsum" /> },
};

View File

@ -1,7 +1,6 @@
import { Meta, StoryObj } from '@storybook/react';
import { userEvent, within } from '@storybook/testing-library';
import { FieldMetadataType } from '~/generated-metadata/graphql';
import { ComponentDecorator } from '~/testing/decorators/ComponentDecorator';
import { SettingsObjectFieldTypeSelectSection } from '../SettingsObjectFieldTypeSelectSection';
@ -10,16 +9,7 @@ const meta: Meta<typeof SettingsObjectFieldTypeSelectSection> = {
title: 'Modules/Settings/DataModel/SettingsObjectFieldTypeSelectSection',
component: SettingsObjectFieldTypeSelectSection,
decorators: [ComponentDecorator],
args: {
fieldType: FieldMetadataType.Number,
fieldIconKey: 'IconUsers',
fieldLabel: 'Employees',
fieldName: 'employees',
isObjectCustom: false,
objectIconKey: 'IconUser',
objectLabelPlural: 'People',
objectNamePlural: 'people',
},
args: {},
};
export default meta;
@ -28,7 +18,7 @@ type Story = StoryObj<typeof SettingsObjectFieldTypeSelectSection>;
export const Default: Story = {};
export const Disabled: Story = {
args: { disabled: true },
args: {},
};
export const WithOpenSelect: Story = {