Skip to content

Commit

Permalink
refactor: use react-hook-form for Field type config forms
Browse files Browse the repository at this point in the history
Closes #4295
  • Loading branch information
thaisguigon committed May 7, 2024
1 parent 8074aae commit 44ecc28
Show file tree
Hide file tree
Showing 29 changed files with 673 additions and 1,033 deletions.
2 changes: 2 additions & 0 deletions packages/twenty-front/src/generated-metadata/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1034,7 +1034,9 @@ export type User = {
id: Scalars['UUID']['output'];
lastName: Scalars['String']['output'];
passwordHash?: Maybe<Scalars['String']['output']>;
/** @deprecated field migrated into the AppTokens Table ref: https://github.com/twentyhq/twenty/issues/5021 */
passwordResetToken?: Maybe<Scalars['String']['output']>;
/** @deprecated field migrated into the AppTokens Table ref: https://github.com/twentyhq/twenty/issues/5021 */
passwordResetTokenExpiresAt?: Maybe<Scalars['DateTime']['output']>;
supportUserHash?: Maybe<Scalars['String']['output']>;
updatedAt: Scalars['DateTime']['output'];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,7 @@ export const variables = {
disableMetadataField: {
idToUpdate: fieldId,
updatePayload: { isActive: false, label: undefined },
},
editMetadataField: {
idToUpdate: '2c43466a-fe9e-4005-8d08-c5836067aa6c',
updatePayload: {
defaultValue: undefined,
description: null,
icon: undefined,
label: 'New label',
name: 'newLabel',
options: undefined,
},
},
}
};

const defaultResponseData = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,17 +68,6 @@ const mocks = [
},
})),
},
{
request: {
query: queries.activateMetadataField,
variables: variables.editMetadataField,
},
result: jest.fn(() => ({
data: {
updateOneField: responseData.default,
},
})),
},
];

const Wrapper = ({ children }: { children: ReactNode }) => (
Expand Down Expand Up @@ -149,22 +138,4 @@ describe('useFieldMetadataItem', () => {
});
});
});

it('should editMetadataField', async () => {
const { result } = renderHook(() => useFieldMetadataItem(), {
wrapper: Wrapper,
});

await act(async () => {
const res = await result.current.editMetadataField({
id: fieldMetadataItem.id,
label: 'New label',
type: FieldMetadataType.Text,
});

expect(res.data).toEqual({
updateOneField: responseData.default,
});
});
});
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { v4 } from 'uuid';

import { FieldMetadataOption } from '@/object-metadata/types/FieldMetadataOption';
import { getDefaultValueForBackend } from '@/object-metadata/utils/getDefaultValueForBackend';
import { Field } from '~/generated/graphql';

Expand Down Expand Up @@ -36,39 +33,8 @@ export const useFieldMetadataItem = () => {
defaultValue,
objectMetadataId: input.objectMetadataId,
type: input.type,
});
};

const editMetadataField = (
input: Pick<
Field,
| 'id'
| 'label'
| 'icon'
| 'description'
| 'defaultValue'
| 'type'
| 'options'
>,
) => {
// In Edit mode, all options need an id,
// so we generate an id for newly created options.
const inputOptions = input.options?.map((option: FieldMetadataOption) =>
option.id ? option : { ...option, id: v4() },
);
const formattedInput = formatFieldMetadataItemInput({
...input,
options: inputOptions,
});

const defaultValue = input.defaultValue ?? formattedInput.defaultValue;

return updateOneFieldMetadataItem({
fieldMetadataIdToUpdate: input.id,
updatePayload: {
...formattedInput,
defaultValue,
},
label: formattedInput.label ?? '',
name: formattedInput.name ?? '',
});
};

Expand All @@ -92,6 +58,5 @@ export const useFieldMetadataItem = () => {
createMetadataField,
disableMetadataField,
eraseMetadataField,
editMetadataField,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@ import { FieldMetadataItem } from '../types/FieldMetadataItem';
export const useGetRelationMetadata = () =>
useRecoilCallback(
({ snapshot }) =>
({ fieldMetadataItem }: { fieldMetadataItem: FieldMetadataItem }) => {
({
fieldMetadataItem,
}: {
fieldMetadataItem: Pick<
FieldMetadataItem,
'fromRelationMetadata' | 'toRelationMetadata' | 'type'
>;
}) => {
if (fieldMetadataItem.type !== FieldMetadataType.Relation) return null;

const relationMetadata =
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import toSnakeCase from 'lodash.snakecase';

import { Field, FieldMetadataType } from '~/generated-metadata/graphql';
import { FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
import { FieldMetadataType } from '~/generated-metadata/graphql';
import { formatMetadataLabelToMetadataNameOrThrows } from '~/pages/settings/data-model/utils/format-metadata-label-to-name.util';
import { isDefined } from '~/utils/isDefined';

Expand All @@ -21,12 +22,14 @@ export const getOptionValueFromLabel = (label: string) => {
};

export const formatFieldMetadataItemInput = (
input: Pick<
Field,
'label' | 'icon' | 'description' | 'defaultValue' | 'options'
> & { type?: FieldMetadataType },
input: Partial<
Pick<
FieldMetadataItem,
'type' | 'label' | 'defaultValue' | 'icon' | 'description'
>
> & { options?: FieldMetadataOption[] },
) => {
const options = input.options as FieldMetadataOption[];
const options = input.options as FieldMetadataOption[] | undefined;
let defaultValue = input.defaultValue;
if (input.type === FieldMetadataType.MultiSelect) {
const defaultOptions = options?.filter((option) => option.isDefault);
Expand Down Expand Up @@ -59,12 +62,14 @@ export const formatFieldMetadataItemInput = (
}
}

const label = input.label?.trim();

return {
defaultValue,
description: input.description?.trim() ?? null,
icon: input.icon,
label: input.label.trim(),
name: formatMetadataLabelToMetadataNameOrThrows(input.label.trim()),
label,
name: label ? formatMetadataLabelToMetadataNameOrThrows(label) : undefined,
options: options?.map((option, index) => ({
color: option.color,
id: option.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ export const formatRelationMetadataInput = (
const {
description: fromDescription,
icon: fromIcon,
label: fromLabel,
name: fromName,
label: fromLabel = '',
name: fromName = '',
} = formatFieldMetadataItemInput(fromField);
const {
description: toDescription,
icon: toIcon,
label: toLabel,
name: toName,
label: toLabel = '',
name: toName = '',
} = formatFieldMetadataItemInput(toField);

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const getDefaultValueForBackend = (
currencyCode: `'${currencyDefaultValue.currencyCode}'` as CurrencyCode,
} satisfies FieldCurrencyValue;
} else if (fieldMetadataType === FieldMetadataType.Select) {
return `'${defaultValue}'`;
return defaultValue ? `'${defaultValue}'` : null;
} else if (fieldMetadataType === FieldMetadataType.MultiSelect) {
return defaultValue.map((value: string) => `'${value}'`);
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
import { Controller, useFormContext } from 'react-hook-form';
import styled from '@emotion/styled';
import { IconCheck, IconX } from 'twenty-ui';
import { z } from 'zod';

import { FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
import { Select } from '@/ui/input/components/Select';
import { CardContent } from '@/ui/layout/card/components/CardContent';

type SettingsDataModelDefaultValueFormProps = {
// TODO: rename to SettingsDataModelFieldBooleanForm and move to settings/data-model/fields/forms/components

export const settingsDataModelFieldBooleanFormSchema = z.object({
defaultValue: z.boolean(),
});

type SettingsDataModelFieldBooleanFormValues = z.infer<
typeof settingsDataModelFieldBooleanFormSchema
>;

type SettingsDataModelFieldBooleanFormProps = {
className?: string;
disabled?: boolean;
onChange?: (defaultValue: SettingsDataModelDefaultValue) => void;
value?: SettingsDataModelDefaultValue;
fieldMetadataItem?: Pick<FieldMetadataItem, 'defaultValue'>;
};

export type SettingsDataModelDefaultValue = any;

const StyledContainer = styled(CardContent)`
padding-bottom: ${({ theme }) => theme.spacing(3.5)};
`;
Expand All @@ -26,34 +35,42 @@ const StyledLabel = styled.span`
margin-top: ${({ theme }) => theme.spacing(1)};
`;

export const SettingsDataModelDefaultValueForm = ({
export const SettingsDataModelFieldBooleanForm = ({
className,
disabled,
onChange,
value,
}: SettingsDataModelDefaultValueFormProps) => {
fieldMetadataItem,
}: SettingsDataModelFieldBooleanFormProps) => {
const { control } = useFormContext<SettingsDataModelFieldBooleanFormValues>();

const initialValue = fieldMetadataItem?.defaultValue ?? true;

return (
<StyledContainer>
<StyledLabel>Default Value</StyledLabel>
<Select
className={className}
fullWidth
disabled={disabled}
dropdownId="object-field-default-value-select"
value={value}
onChange={(value) => onChange?.(value)}
options={[
{
value: true,
label: 'True',
Icon: IconCheck,
},
{
value: false,
label: 'False',
Icon: IconX,
},
]}
<Controller
name="defaultValue"
control={control}
defaultValue={initialValue}
render={({ field: { onChange, value } }) => (
<Select
className={className}
fullWidth
dropdownId="object-field-default-value-select"
value={value}
onChange={onChange}
options={[
{
value: true,
label: 'True',
Icon: IconCheck,
},
{
value: false,
label: 'False',
Icon: IconX,
},
]}
/>
)}
/>
</StyledContainer>
);
Expand Down

0 comments on commit 44ecc28

Please sign in to comment.