import { useState } from 'preact/hooks'; import type { Book } from '../../shared/types.ts'; import { api } from '../api.ts'; import { upsertBook, dispatch } from '../live.ts'; import { parseYear } from '../year.ts'; export function BookEditor({ book, onClose }: { book: Book; onClose: () => void }) { const [title, setTitle] = useState(book.title); const [authors, setAuthors] = useState(book.authors.join('; ')); const [publisher, setPublisher] = useState(book.publisher ?? ''); const [year, setYear] = useState(book.year?.toString() ?? ''); const [callNumber, setCallNumber] = useState(book.callNumber ?? ''); const [msg, setMsg] = useState(''); const [yearError, setYearError] = useState(''); const [busy, setBusy] = useState(false); async function run(fn: () => Promise) { setBusy(true); setMsg(''); try { await fn(); } catch (e) { setMsg((e as Error).message); } setBusy(false); } const save = (ev: Event) => { ev.preventDefault(); const y = parseYear(year); if (!y.ok) { setYearError('Enter the year as digits, for example 2018, or leave it empty.'); return; } setYearError(''); void run(async () => { const patch: Record = { title: title.trim(), authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean), publisher: publisher.trim() || null, year: y.value, }; if (callNumber.trim() !== (book.callNumber ?? '')) patch.callNumber = callNumber.trim(); upsertBook(await api.patchBook(book.id, patch)); onClose(); }); }; return (
{yearError ? : null} {book.attentionReason ?

{book.attentionReason}

: null} {msg ? : null}
); }