import { useCallback, useEffect, useState } from 'react'; import { useRequestUpdate } from '../hooks/useRequest'; import type { HttpHeader, HttpRequest } from '../lib/models'; import { IconButton } from './IconButton'; import { Input } from './Input'; import { VStack } from './Stacks'; interface Props { request: HttpRequest; } type PairWithId = { header: Partial; id: string }; export function HeaderEditor({ request }: Props) { const updateRequest = useRequestUpdate(request); const saveHeaders = useCallback( (pairs: PairWithId[]) => { const headers = pairs.map((p) => ({ name: '', value: '', ...p.header })); updateRequest.mutate({ headers }); }, [updateRequest], ); const newPair = () => { return { header: { name: '', value: '' }, id: Math.random().toString() }; }; const [pairs, setPairs] = useState( request.headers.map((h) => ({ header: h, id: Math.random().toString() })), ); const setPairsAndSave = useCallback( (fn: (pairs: PairWithId[]) => PairWithId[]) => { setPairs((oldPairs) => { const newPairs = fn(oldPairs); saveHeaders(newPairs); return newPairs; }); }, [saveHeaders], ); const handleChangeHeader = (pair: PairWithId) => { setPairsAndSave((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 !== '') { setPairsAndSave((pairs) => [...pairs, newPair()]); } }, [pairs, setPairsAndSave]); const handleDelete = (pair: PairWithId) => { setPairsAndSave((oldPairs) => oldPairs.filter((p) => p.id !== pair.id)); }; return (
{pairs.map((p, i) => ( ))}
); } function FormRow({ pair, onChange, onDelete, }: { 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="invisible group-hover:visible" /> )}
); }