import { typeboxResolver } from "@hookform/resolvers/typebox"; import { Select, Switch, Tabs, TextInput, Textarea, Tooltip } from "@mantine/core"; import { useDisclosure } from "@mantine/hooks"; import { Type } from "@sinclair/typebox"; import { StringEnum, StringIdentifier, transformObject } from "core/utils"; import { FieldClassMap } from "data"; import { omit } from "lodash-es"; import { type FieldArrayWithId, type FieldValues, type UseControllerProps, type UseFormReturn, useController, useFieldArray, useForm, } from "react-hook-form"; import { TbChevronDown, TbChevronUp, TbGripVertical, TbTrash } from "react-icons/tb"; import { Button } from "../../../components/buttons/Button"; import { IconButton } from "../../../components/buttons/IconButton"; import { MantineSelect } from "../../../components/form/hook-form-mantine/MantineSelect"; const fieldSchemas = transformObject(omit(FieldClassMap, ["primary"]), (value) => value.schema); const fieldSchema = Type.Union( Object.entries(fieldSchemas).map(([type, schema]) => Type.Object( { type: Type.Const(type), name: StringIdentifier, config: Type.Optional(schema), }, { additionalProperties: false, }, ), ), ); const schema = Type.Object({ fields: Type.Array(fieldSchema), }); const fieldSchema2 = Type.Object({ type: StringEnum(Object.keys(fieldSchemas)), name: StringIdentifier, }); function specificFieldSchema(type: keyof typeof fieldSchemas) { return Type.Omit(fieldSchemas[type], [ "label", "description", "required", "fillable", "hidden", "virtual", ]); } export default function EntityFieldsForm() { const { control, formState: { isValid, errors }, getValues, handleSubmit, watch, register, setValue, } = useForm({ mode: "onTouched", resolver: typeboxResolver(schema), defaultValues: { fields: [{ type: "text", name: "", config: {} }], sort: { by: "-1", dir: "asc" }, }, }); const defaultType = Object.keys(fieldSchemas)[0]; const { fields, append, prepend, remove, swap, move, insert, update } = useFieldArray({ control, // control props comes from useForm (optional: if you are using FormProvider) name: "fields", // unique name for your Field Array }); function handleAppend() { append({ type: "text", name: "", config: {} }); } return (
{JSON.stringify(watch(), null, 2)}