import type { JSONSchema } from "json-schema-to-ts"; import type { ChangeEvent, ComponentPropsWithoutRef } from "react"; import * as Formy from "ui/components/form/Formy"; import { useEvent } from "ui/hooks/use-event"; import { ArrayField } from "./ArrayField"; import { FieldWrapper } from "./FieldWrapper"; import { useFieldContext } from "./Form"; import { ObjectField } from "./ObjectField"; import { coerce, enumToOptions, isType, isTypeSchema } from "./utils"; export type FieldProps = { name: string; schema?: Exclude; onChange?: (e: ChangeEvent) => void; label?: string | false; hidden?: boolean; }; export const Field = ({ name, schema: _schema, onChange, label: _label, hidden }: FieldProps) => { const { pointer, value, errors, setValue, required, ...ctx } = useFieldContext(name); const schema = _schema ?? ctx.schema; if (!isTypeSchema(schema)) return
{pointer} has no schema
; //console.log("field", name, schema); if (isType(schema.type, "object")) { return ; } if (isType(schema.type, "array")) { return ; } const disabled = schema.readOnly ?? "const" in schema ?? false; //console.log("field", name, disabled, schema, ctx.schema, _schema); const handleChange = useEvent((e: ChangeEvent) => { // don't remove for now, causes issues in anyOf /*const value = coerce(e.target.value, schema as any); setValue(pointer, value as any);*/ const value = coerce(e.target.value, schema as any, { required }); //console.log("handleChange", pointer, e.target.value, { value }, ctx.options); if (typeof value === "undefined" && !required && ctx.options?.keepEmpty !== true) { ctx.deleteValue(pointer); } else { //console.log("setValue", pointer, value); setValue(pointer, value); } }); return ( ); }; export const Pre = ({ children }) => (
{children}
); export const FieldComponent = ({ schema, ...props }: { schema: JSONSchema } & ComponentPropsWithoutRef<"input">) => { if (!isTypeSchema(schema)) return null; if (schema.enum) { return ( ); } if (isType(schema.type, ["number", "integer"])) { return ; } if (isType(schema.type, "boolean")) { return ; } return ; };