@open-formulieren/formio-builder
Version:
An opinionated Formio webform builder for Open Forms
67 lines (66 loc) • 2.87 kB
JavaScript
import { z } from 'zod';
import { buildCommonSchema, buildKeySchema } from '../../registry/validation';
const dateSchema = z.coerce.date().optional();
// case for when component.multiple=false
const singleValueSchema = z
.object({ multiple: z.literal(false) })
.and(z.object({ defaultValue: dateSchema }));
// case for when component.multiple=true
const multipleValueSchema = z
.object({ multiple: z.literal(true) })
.and(z.object({ defaultValue: dateSchema.array() }));
const defaultValueSchema = singleValueSchema.or(multipleValueSchema);
// formik (deliberately) turns empty string into undefined
const noMode = z.object({ mode: z.union([z.literal(undefined), z.literal('')]) });
const future = z.object({
mode: z.literal('future'),
});
const past = z.object({
mode: z.literal('past'),
});
// XXX: requires superRefine to enforce datePicker.maxDate etc. to be set!
const fixedValue = z.object({ mode: z.literal('fixedValue') });
const date = z.null().or(z.coerce.date());
const buildRelativeToVariable = (intl) => z.object({
mode: z.literal('relativeToVariable'),
operator: z.literal('add').or(z.literal('subtract')),
variable: buildKeySchema(intl),
delta: z.object({
years: z.null().or(z.number().int().gte(0)).optional(),
months: z.null().or(z.number().int().gte(0)).optional(),
days: z.null().or(z.number().int().gte(0)).optional(),
}),
});
const buildDateTimeSpecific = (intl) => z
.object({
openForms: z
.object({
minDate: z.union([noMode, fixedValue, future, buildRelativeToVariable(intl)]).optional(),
maxDate: z.union([noMode, fixedValue, past, buildRelativeToVariable(intl)]).optional(),
})
.optional(),
datePicker: z
.object({
minDate: date.optional(),
maxDate: date.optional(),
})
.optional(),
})
.superRefine((component, ctx) => {
var _a, _b, _c;
for (const constraint of ['minDate', 'maxDate']) {
const isFixedMode = ((_b = (_a = component === null || component === void 0 ? void 0 : component.openForms) === null || _a === void 0 ? void 0 : _a[constraint]) === null || _b === void 0 ? void 0 : _b.mode) === 'fixedValue';
if (!isFixedMode)
continue;
const datePickerValue = (_c = component === null || component === void 0 ? void 0 : component.datePicker) === null || _c === void 0 ? void 0 : _c[constraint];
if (datePickerValue)
continue;
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['datePicker', constraint],
message: intl.formatMessage({ id: "6Xhq/T", defaultMessage: [{ type: 0, value: "You must specify a datetime." }] }),
});
}
});
const schema = ({ intl }) => buildCommonSchema(intl).and(defaultValueSchema).and(buildDateTimeSpecific(intl));
export default schema;