Files
twenty/packages/twenty-front/src/modules/object-metadata/utils/formatFieldMetadataItemInput.ts
Jérémy M a802338996 fix: options value can't contain special characters (#3738)
* fix: options value can't contain special characters

* add tests for formatFieldMetadataItemInput util

* fix test

* fix: add emoji test

---------

Co-authored-by: corentin <corentin@twenty.com>
2024-02-05 15:12:08 +01:00

46 lines
1.3 KiB
TypeScript

import toCamelCase from 'lodash.camelcase';
import toSnakeCase from 'lodash.snakecase';
import { Field } from '~/generated-metadata/graphql';
import { FieldMetadataOption } from '../types/FieldMetadataOption';
export const getOptionValueFromLabel = (label: string) => {
// Remove accents
const unaccentedLabel = label
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '');
// Remove special characters
const noSpecialCharactersLabel = unaccentedLabel.replace(
/[^a-zA-Z0-9 ]/g,
'',
);
return toSnakeCase(noSpecialCharactersLabel).toUpperCase();
};
export const formatFieldMetadataItemInput = (
input: Pick<Field, 'label' | 'icon' | 'description' | 'defaultValue'> & {
options?: FieldMetadataOption[];
},
) => {
const defaultOption = input.options?.find((option) => option.isDefault);
return {
defaultValue: defaultOption
? getOptionValueFromLabel(defaultOption.label)
: undefined,
description: input.description?.trim() ?? null,
icon: input.icon,
label: input.label.trim(),
name: toCamelCase(input.label.trim()),
options: input.options?.map((option, index) => ({
color: option.color,
id: option.id,
label: option.label.trim(),
position: index,
value: getOptionValueFromLabel(option.label),
})),
};
};