import { IconLibraryPlus, IconTrash } from "@tabler/icons-react"; import type { JSONSchema } from "json-schema-to-ts"; import { Button } from "ui/components/buttons/Button"; import { IconButton } from "ui/components/buttons/IconButton"; import * as Formy from "ui/components/form/Formy"; import { Dropdown } from "ui/components/overlay/Dropdown"; import { FieldComponent } from "./Field"; import { FieldWrapper } from "./FieldWrapper"; import { useFieldContext } from "./Form"; import { coerce, getMultiSchema, getMultiSchemaMatched } from "./utils"; export const ArrayField = ({ path = "", schema: _schema }: { path?: string; schema?: Exclude }) => { const { setValue, value, pointer, required, ...ctx } = useFieldContext(path); const schema = _schema ?? ctx.schema; if (!schema || typeof schema === "undefined") return `ArrayField(${path}): no schema ${pointer}`; const itemsMultiSchema = getMultiSchema(schema.items); function handleAdd(template?: any) { const currentIndex = value?.length ?? 0; const newPointer = `${path}/${currentIndex}`.replace(/\/+/g, "/"); setValue(newPointer, template ?? ctx.lib.getTemplate(undefined, schema!.items)); } function handleUpdate(pointer: string, value: any) { setValue(pointer, value); } function handleDelete(pointer: string) { return () => { ctx.deleteValue(pointer); }; } // if unique items with enum if (schema.uniqueItems && typeof schema.items === "object" && "enum" in schema.items) { return ( { // @ts-ignore const selected = Array.from(e.target.selectedOptions).map((o) => o.value); setValue(pointer, selected); }} /> ); } return ( {value?.map((v, index: number) => { const pointer = `${path}/${index}`.replace(/\/+/g, "/"); let subschema = schema.items; if (itemsMultiSchema) { const [, , _subschema] = getMultiSchemaMatched(schema.items, v); subschema = _subschema; } return (
{ handleUpdate(pointer, coerce(e.target.value, subschema!)); }} className="w-full" />
); })}
{itemsMultiSchema ? ( ({ label: s!.title ?? `Option ${i + 1}`, onClick: () => handleAdd(ctx.lib.getTemplate(undefined, s!)) }))} onClickItem={console.log} > ) : ( )}
); };