Files
twenty_crm/packages/twenty-front/src/modules/object-metadata/validation-schemas/selectOptionsSchema.ts

61 lines
1.7 KiB
TypeScript

import { z } from 'zod';
import { FieldMetadataItemOption } from '@/object-metadata/types/FieldMetadataItem';
import { getOptionValueFromLabel } from '@/settings/data-model/fields/forms/select/utils/getOptionValueFromLabel';
import { themeColorSchema } from '@/ui/theme/utils/themeColorSchema';
import { computeOptionValueFromLabelOrThrow } from '~/pages/settings/data-model/utils/compute-option-value-from-label.utils';
const selectOptionSchema = z
.object({
color: themeColorSchema,
id: z.string(),
label: z.string().trim().min(1),
position: z.number(),
value: z.string(),
})
.refine((option) => option.value === getOptionValueFromLabel(option.label), {
message: 'Value does not match label',
})
.refine(
(option) => {
try {
computeOptionValueFromLabelOrThrow(option.label);
return true;
} catch (error) {
return false;
}
},
{
message: 'Label is not transliterable',
},
) satisfies z.ZodType<FieldMetadataItemOption>;
export const selectOptionsSchema = z
.array(selectOptionSchema)
.min(1)
.refine(
(options) => {
const optionIds = options.map(({ id }) => id);
return new Set(optionIds).size === options.length;
},
{
message: 'Options must have unique ids',
},
)
.refine(
(options) => {
const optionValues = options.map(({ value }) => value);
return new Set(optionValues).size === options.length;
},
{
message: 'Options must have unique values',
},
)
.refine(
(options) =>
[...options].sort().every((option, index) => option.position === index),
{
message: 'Options positions must be sequential',
},
);