(null)
const [editValue, setEditValue] = useState('')
const [isAddingNew, setIsAddingNew] = useState(false)
const [newValue, setNewValue] = useState('')
const handleStartEdit = (index: number) => {
setEditingIndex(index)
setEditValue(items[index])
}
const handleSaveEdit = () => {
if (editingIndex !== null) {
const newItems = [...items]
if (editValue.trim()) {
newItems[editingIndex] = editValue.trim()
} else {
newItems.splice(editingIndex, 1)
}
onSave(newItems)
setEditingIndex(null)
}
}
const handleDeleteItem = (index: number) => {
const newItems = items.filter((_, i) => i !== index)
onSave(newItems)
}
const handleAddNew = () => {
if (newValue.trim()) {
onSave([...items, newValue.trim()])
setNewValue('')
setIsAddingNew(false)
}
}
const handleKeyDown = (e: React.KeyboardEvent, action: 'edit' | 'add') => {
if (e.key === 'Enter') {
if (action === 'edit') handleSaveEdit()
else handleAddNew()
} else if (e.key === 'Escape') {
if (action === 'edit') {
setEditingIndex(null)
setEditValue('')
} else {
setIsAddingNew(false)
setNewValue('')
}
}
}
return (
{items.map((item, idx) =>
editingIndex === idx ? (
setEditValue(e.target.value)}
onKeyDown={(e) => handleKeyDown(e, 'edit')}
onBlur={handleSaveEdit}
autoFocus
/>
) : (
handleStartEdit(idx)}
title="Click to edit"
>
{item}
)
)}
{isAddingNew ? (
setNewValue(e.target.value)}
onKeyDown={(e) => handleKeyDown(e, 'add')}
onBlur={() => {
if (newValue.trim()) handleAddNew()
else { setIsAddingNew(false); setNewValue('') }
}}
placeholder={`${label}...`}
autoFocus
/>
) : (
)}
)
}