|
| 1 | +import { useState } from 'react' |
| 2 | +import Button from '../common/Button' |
| 3 | +import FormInput from './FormInput' |
| 4 | + |
| 5 | +export default function KeyValueArrayManager({ |
| 6 | + items = [], |
| 7 | + onUpdate, |
| 8 | + keyLabel = 'Key', |
| 9 | + valueLabel = 'Value', |
| 10 | + keyPlaceholder = 'key', |
| 11 | + valuePlaceholder = 'value', |
| 12 | + addButtonText = 'Add Item', |
| 13 | + emptyMessage = 'No items added yet.' |
| 14 | +}) { |
| 15 | + const handleAdd = () => { |
| 16 | + const newItems = [...items, { name: '', value: '' }] |
| 17 | + onUpdate(newItems) |
| 18 | + } |
| 19 | + |
| 20 | + const handleRemove = (index) => { |
| 21 | + const newItems = items.filter((_, i) => i !== index) |
| 22 | + onUpdate(newItems) |
| 23 | + } |
| 24 | + |
| 25 | + const handleUpdate = (index, field, value) => { |
| 26 | + const newItems = items.map((item, i) => |
| 27 | + i === index ? { ...item, [field]: value } : item |
| 28 | + ) |
| 29 | + onUpdate(newItems) |
| 30 | + } |
| 31 | + |
| 32 | + return ( |
| 33 | + <div className="space-y-3"> |
| 34 | + {items.length === 0 ? ( |
| 35 | + <div className="text-center py-4 bg-gray-50 rounded-lg border border-dashed border-gray-300"> |
| 36 | + <p className="text-sm text-gray-500">{emptyMessage}</p> |
| 37 | + </div> |
| 38 | + ) : ( |
| 39 | + <div className="space-y-3"> |
| 40 | + {items.map((item, index) => ( |
| 41 | + <div key={index} className="flex gap-3 items-start"> |
| 42 | + <div className="flex-1"> |
| 43 | + <FormInput |
| 44 | + name={`key-${index}`} |
| 45 | + label={keyLabel} |
| 46 | + value={item.name || ''} |
| 47 | + onChange={(e) => handleUpdate(index, 'name', e.target.value)} |
| 48 | + placeholder={keyPlaceholder} |
| 49 | + /> |
| 50 | + </div> |
| 51 | + <div className="flex-1"> |
| 52 | + <FormInput |
| 53 | + name={`value-${index}`} |
| 54 | + label={valueLabel} |
| 55 | + value={item.value || ''} |
| 56 | + onChange={(e) => handleUpdate(index, 'value', e.target.value)} |
| 57 | + placeholder={valuePlaceholder} |
| 58 | + /> |
| 59 | + </div> |
| 60 | + <div className="pt-7"> |
| 61 | + <Button |
| 62 | + variant="danger" |
| 63 | + onClick={() => handleRemove(index)} |
| 64 | + className="text-xs px-2 py-1" |
| 65 | + > |
| 66 | + Remove |
| 67 | + </Button> |
| 68 | + </div> |
| 69 | + </div> |
| 70 | + ))} |
| 71 | + </div> |
| 72 | + )} |
| 73 | + <Button |
| 74 | + variant="outline" |
| 75 | + onClick={handleAdd} |
| 76 | + className="w-full text-sm" |
| 77 | + > |
| 78 | + {addButtonText} |
| 79 | + </Button> |
| 80 | + </div> |
| 81 | + ) |
| 82 | +} |
0 commit comments