Mathis c51e4fcc77
feat(auto-form): add new fields and form files to AutoForm component
Added several files to the AutoForm component for better form functionality including a file for each type of input field (checkbox, date, enum, file, number, radio-group, switch, etc). Managed the configurations in a separate file and handled dependencies to control form behaviours. This commit enhances form handling capabilities and simplifies the process for creating versatile forms.
2024-06-12 14:59:35 +02:00

58 lines
1.4 KiB
TypeScript

import type { FieldValues, UseFormWatch } from "react-hook-form";
import type * as z from "zod";
import { type Dependency, DependencyType, type EnumValues } from "./types";
export default function resolveDependencies<
SchemaType extends z.infer<z.ZodObject<any, any>>,
>(
dependencies: Dependency<SchemaType>[],
currentFieldName: keyof SchemaType,
watch: UseFormWatch<FieldValues>,
) {
let isDisabled = false;
let isHidden = false;
let isRequired = false;
let overrideOptions: EnumValues | undefined;
const currentFieldValue = watch(currentFieldName as string);
const currentFieldDependencies = dependencies.filter(
(dependency) => dependency.targetField === currentFieldName,
);
for (const dependency of currentFieldDependencies) {
const watchedValue = watch(dependency.sourceField as string);
const conditionMet = dependency.when(watchedValue, currentFieldValue);
switch (dependency.type) {
case DependencyType.DISABLES:
if (conditionMet) {
isDisabled = true;
}
break;
case DependencyType.REQUIRES:
if (conditionMet) {
isRequired = true;
}
break;
case DependencyType.HIDES:
if (conditionMet) {
isHidden = true;
}
break;
case DependencyType.SETS_OPTIONS:
if (conditionMet) {
overrideOptions = dependency.options;
}
break;
}
}
return {
isDisabled,
isHidden,
isRequired,
overrideOptions,
};
}