UNPKG

zod-form-kit

Version:

UI-agnostic form generation library based on Zod schemas with extensible adapter pattern

32 lines (31 loc) 2.03 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { FieldRenderer } from '../FieldRenderer'; export function ArrayField({ value = [], onChange, error, required, label, itemSchema, form, path, options }) { const minItems = options?.minItems || 0; const maxItems = options?.maxItems || Infinity; const canAdd = value.length < maxItems; const canRemove = value.length > minItems; const addItem = () => { if (canAdd) { const newItem = getDefaultValue(itemSchema); onChange([...value, newItem]); } }; const removeItem = (index) => { if (canRemove) { const newValue = value.filter((_, i) => i !== index); onChange(newValue); } }; const getDefaultValue = (schema) => { switch (schema.type) { case 'string': return ''; case 'number': return 0; case 'boolean': return false; case 'array': return []; case 'object': return {}; default: return null; } }; return (_jsxs("div", { className: "array-field", children: [_jsxs("div", { className: "array-header", children: [_jsxs("label", { className: "array-label", children: [label, " ", required && _jsx("span", { className: "required", children: "*" })] }), canAdd && (_jsx("button", { type: "button", onClick: addItem, className: "add-button", children: "Add Item" }))] }), error && _jsx("div", { className: "error-message", children: error }), _jsx("div", { className: "array-items", children: value.map((_, index) => (_jsxs("div", { className: "array-item", children: [_jsx(FieldRenderer, { schema: itemSchema, form: form, path: `${path}.${index}`, label: `Item ${index + 1}` }), canRemove && (_jsx("button", { type: "button", onClick: () => removeItem(index), className: "remove-button", children: "Remove" }))] }, index))) }), value.length === 0 && (_jsx("div", { className: "array-empty", children: "No items. Click \"Add Item\" to get started." }))] })); }