|
| 1 | +import type z from "zod"; |
| 2 | + |
| 3 | +import type { useLocale } from "@calcom/lib/hooks/useLocale"; |
| 4 | + |
| 5 | +import { fieldTypesConfigMap } from "../fieldTypes"; |
| 6 | +import type { fieldSchema } from "../schema"; |
| 7 | + |
| 8 | +type ConfigVariants = NonNullable<ReturnType<typeof getConfig>>["variants"]; |
| 9 | +type Field = z.infer<typeof fieldSchema>; |
| 10 | +type Translate = ReturnType<typeof useLocale>["t"]; |
| 11 | + |
| 12 | +function getTranslatedConfigVariants(configVariants: ConfigVariants, translate: Translate) { |
| 13 | + return Object.entries(configVariants).reduce((variantsConfigVariants, [variantName, variant]) => { |
| 14 | + const translatedFields = variant.fields.map((field) => { |
| 15 | + const label = field.label ?? ""; |
| 16 | + const placeholder = field.placeholder ?? ""; |
| 17 | + return { |
| 18 | + ...field, |
| 19 | + label: translate(label), |
| 20 | + placeholder: translate(placeholder), |
| 21 | + }; |
| 22 | + }); |
| 23 | + variantsConfigVariants[variantName] = { |
| 24 | + ...variant, |
| 25 | + fields: translatedFields, |
| 26 | + }; |
| 27 | + |
| 28 | + return variantsConfigVariants; |
| 29 | + }, {} as typeof configVariants); |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Get's the field's variantsConfig and if not available, then it will get the default variantsConfig from the fieldTypesConfigMap |
| 34 | + */ |
| 35 | +export const getConfig = (field: Pick<Field, "variantsConfig" | "type">) => { |
| 36 | + const fieldVariantsConfig = field.variantsConfig; |
| 37 | + const fieldTypeConfig = fieldTypesConfigMap[field.type as keyof typeof fieldTypesConfigMap]; |
| 38 | + |
| 39 | + if (!fieldTypeConfig) throw new Error(`Invalid field.type ${field.type}}`); |
| 40 | + |
| 41 | + const defaultVariantsConfig = fieldTypeConfig?.variantsConfig?.defaultValue; |
| 42 | + const variantsConfig = fieldVariantsConfig || defaultVariantsConfig; |
| 43 | + |
| 44 | + if (fieldTypeConfig.propsType === "variants" && !variantsConfig) { |
| 45 | + throw new Error(`propsType variants must have variantsConfig`); |
| 46 | + } |
| 47 | + return variantsConfig; |
| 48 | +}; |
| 49 | + |
| 50 | +export const getTranslatedConfig = (field: Pick<Field, "variantsConfig" | "type">, translate: Translate) => { |
| 51 | + const variantsConfig = getConfig(field); |
| 52 | + if (!variantsConfig) return variantsConfig; |
| 53 | + const newVariantsConfigVariants = getTranslatedConfigVariants(variantsConfig.variants, translate); |
| 54 | + |
| 55 | + return { |
| 56 | + ...variantsConfig, |
| 57 | + variants: newVariantsConfigVariants, |
| 58 | + }; |
| 59 | +}; |
0 commit comments