Files
booksorter/src/web/components/BookEditor.tsx
T
2026-11-18 09:46:46 -07:00

62 lines
3.1 KiB
TypeScript

import { useState } from 'preact/hooks';
import type { Book } from '../../shared/types.ts';
import { api } from '../api.ts';
import { upsertBook, dispatch } from '../live.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 [busy, setBusy] = useState(false);
async function run(fn: () => Promise<void>) {
setBusy(true); setMsg('');
try { await fn(); } catch (e) { setMsg((e as Error).message); }
setBusy(false);
}
const save = (ev: Event) => { ev.preventDefault(); void run(async () => {
const patch: Record<string, unknown> = {
title: title.trim(),
authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean),
publisher: publisher.trim() || null,
year: year.trim() ? Number(year) : null,
};
if (callNumber.trim() !== (book.callNumber ?? '')) patch.callNumber = callNumber.trim();
upsertBook(await api.patchBook(book.id, patch));
onClose();
}); };
return (
<form class="card editor" onSubmit={save}>
<label>Title<input value={title} onInput={e => setTitle(e.currentTarget.value)} required /></label>
<label>Authors (separate with ;)<input value={authors} onInput={e => setAuthors(e.currentTarget.value)} /></label>
<div class="row">
<label class="grow">Publisher<input value={publisher} onInput={e => setPublisher(e.currentTarget.value)} /></label>
<label class="year">Year<input inputMode="numeric" value={year} onInput={e => setYear(e.currentTarget.value)} /></label>
</div>
<label>Call number
<input class="mono" value={callNumber} onInput={e => setCallNumber(e.currentTarget.value)} />
<small>Changing this locks the number</small>
</label>
{book.attentionReason ? <p class="warn">{book.attentionReason}</p> : null}
{msg ? <p class="error" role="alert">{msg}</p> : null}
<div class="row wrap">
<button type="submit" class="primary" disabled={busy}>Save</button>
<button type="button" disabled={busy} onClick={() => run(async () => { upsertBook(await api.queueBook(book.id)); })}>Queue reprint</button>
<button type="button" disabled={busy || book.manualOverride}
title={book.manualOverride ? 'This number was set by hand' : undefined}
onClick={() => run(async () => { upsertBook(await api.retryBook(book.id)); })}>Look up again</button>
<button type="button" class="danger" disabled={busy} onClick={() => {
if (!confirm(`Delete "${book.title}"?`)) return;
void run(async () => { await api.deleteBook(book.id); dispatch({ type: 'delete', id: book.id }); onClose(); });
}}>Delete</button>
<button type="button" class="quiet" onClick={onClose}>Close</button>
</div>
</form>
);
}