import { Plus, X } from "lucide-react"; import React, { useCallback, useMemo } from "react"; import { Button, FormLayout, Input, Label, Switch, type LayoutType } from "../../index"; import { useDialSchema } from "../DialProvider"; import { IconRenderer } from "../IconRenderer"; import { LabelPositionT } from "../types"; interface DialArrayInputProps { name: string; label?: string; labelPosition?: LabelPositionT; icon?: string; } /** * Array input component for primitive types (string, number, boolean) * Supports add/remove operations for dynamic arrays * * Note: Currently only supports primitive element types. * Complex types (objects, nested arrays) are not supported. */ export const DialArrayInput: React.FC = ({ name, label, labelPosition = "top", icon, }) => { const { getValue, setValue, schemas } = useDialSchema(); const schema = schemas.find((s) => s.name === name); const arrayValue = useMemo( () => (getValue(name) || []) as Array, [getValue, name], ); const elementType = schema?.arrayElementType || "string"; const handleAddItem = useCallback(() => { const newValue = [...arrayValue]; // Add default value based on element type switch (elementType) { case "number": newValue.push(0); break; case "boolean": newValue.push(false); break; default: // string newValue.push(""); break; } setValue(name, newValue); }, [arrayValue, elementType, name, setValue]); const handleRemoveItem = useCallback( (index: number) => { const newValue = arrayValue.filter((_, i) => i !== index); setValue(name, newValue); }, [arrayValue, name, setValue], ); const handleItemChange = useCallback( (index: number, value: string | number | boolean) => { const newValue = [...arrayValue]; newValue[index] = value; setValue(name, newValue); }, [arrayValue, name, setValue], ); if (!schema) { return null; } const renderItemInput = (item: string | number | boolean, index: number) => { const itemKey = `${name}-${index}`; switch (elementType) { case "boolean": return ( handleItemChange(index, checked)} /> ); case "number": return ( handleItemChange(index, Number(e.target.value))} className="flex-1" step={schema.step || 0.1} min={schema.min} max={schema.max} /> ); default: // string return ( handleItemChange(index, e.target.value)} className="flex-1" placeholder={schema.placeholder} /> ); } }; const arrayContent = (
{/* Array items */} {arrayValue.map((item, index) => (
{index + 1}. {renderItemInput(item, index)}
))} {/* Add button */} {/* Empty state */} {arrayValue.length === 0 && (
No items. Click "Add {elementType}" to start.
)}
); if (!label) { return arrayContent; } return (
{schema.helpText && ( ⓘ {schema.helpText} )}
{arrayContent}
); };