import React, { useEffect, useState } from 'react'; import type { HttpHeader } from '../lib/models'; import { IconButton } from './IconButton'; import { Input } from './Input'; import { VStack } from './Stacks'; type PairWithId = { header: Partial; id: string }; export function HeaderEditor() { const newPair = () => { return { header: { name: '', value: '' }, id: Math.random().toString() }; }; const [pairs, setPairs] = useState([newPair()]); const handleChangeHeader = (pair: PairWithId) => { setPairs((pairs) => pairs.map((p) => pair.id !== p.id ? p : { id: p.id, header: { ...p.header, ...pair.header } }, ), ); }; useEffect(() => { const lastPair = pairs[pairs.length - 1]; if (lastPair === undefined) { setPairs([newPair()]); return; } if (lastPair.header.name !== '' || lastPair.header.value !== '') { setPairs((pairs) => [...pairs, newPair()]); } }, [pairs]); const handleDelete = (pair: PairWithId) => { setPairs((headers) => headers.filter((p) => p.id !== pair.id)); }; return ( {pairs.map((p, i) => ( ))} ); } function FormRow({ autoFocus, pair, onChange, onDelete, }: { autoFocus?: boolean; pair: PairWithId; onChange: (pair: PairWithId) => void; onDelete?: (pair: PairWithId) => void; }) { return (
onChange({ id: pair.id, header: { name }, }) } /> onChange({ id: pair.id, header: { value }, }) } /> {onDelete && onDelete(pair)} className="w-auto" />}
); }