UNPKG

@basictech/cli

Version:

Basic CLI for creating & managing your projects

69 lines 3.62 kB
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; import { useState } from 'react'; import { Box, Text, useInput } from 'ink'; export function Form({ title, fields, onSubmit, onCancel }) { const [currentFieldIndex, setCurrentFieldIndex] = useState(0); const [formData, setFormData] = useState({}); const [errors, setErrors] = useState({}); const currentField = fields[currentFieldIndex]; const currentValue = formData[currentField.name] || ''; useInput((input, key) => { if (key.escape) { onCancel(); return; } if (key.return) { // Validate current field if (currentField.required && !currentValue.trim()) { setErrors(prev => ({ ...prev, [currentField.name]: `${currentField.label} is required` })); return; } // Clear error for this field setErrors(prev => { const newErrors = { ...prev }; delete newErrors[currentField.name]; return newErrors; }); // Move to next field or submit if (currentFieldIndex < fields.length - 1) { setCurrentFieldIndex(prev => prev + 1); } else { // All fields completed, submit form const result = onSubmit(formData); // Handle both sync and async onSubmit if (result instanceof Promise) { result.catch(console.error); } } return; } if (key.backspace || key.delete) { setFormData(prev => ({ ...prev, [currentField.name]: currentValue.slice(0, -1) })); return; } // Add character to current field if (input && input.length === 1) { setFormData(prev => ({ ...prev, [currentField.name]: currentValue + input })); } }); return (_jsxs(Box, { flexDirection: "column", padding: 1, children: [_jsx(Box, { marginBottom: 2, children: _jsx(Text, { bold: true, color: "blue", children: title }) }), fields.map((field, index) => { const isActive = index === currentFieldIndex; const value = formData[field.name] || ''; const error = errors[field.name]; const isCompleted = index < currentFieldIndex || (index === currentFieldIndex && value.trim()); return (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Box, { children: _jsxs(Text, { color: isCompleted ? 'green' : isActive ? 'blue' : 'gray', children: [isCompleted ? '✓' : isActive ? '>' : ' ', " ", field.label, ":"] }) }), _jsx(Box, { marginLeft: 2, children: _jsx(Text, { children: isActive ? (_jsxs(_Fragment, { children: [value, _jsx(Text, { backgroundColor: "white", color: "black", children: "\u2588" })] })) : (value || (field.placeholder && index > currentFieldIndex ? `(${field.placeholder})` : '')) }) }), error && (_jsx(Box, { marginLeft: 2, marginTop: 0, children: _jsxs(Text, { color: "red", children: ["Error: ", error] }) }))] }, field.name)); }), _jsx(Box, { marginTop: 2, children: _jsx(Text, { color: "gray", children: currentFieldIndex < fields.length - 1 ? 'Enter to continue • esc to cancel' : 'Enter to submit • esc to cancel' }) })] })); } //# sourceMappingURL=Form.js.map