import { useEffect, useState } from 'preact/hooks'; import type { Book, SearchResult } from '../../shared/types.ts'; import { api } from '../api.ts'; import type { BookPatch } from '../api.ts'; import { getBook, setLastScan, upsertBook, dispatch, useBooks } from '../live.ts'; import { showToast } from '../toast-store.ts'; import { splitTitleAuthor } from '../entry.ts'; import { parseYear } from '../year.ts'; import { rowState } from '../bookstate.ts'; import { Panel } from './Panel.tsx'; import { moveActive, ResultList } from './Results.tsx'; import { Spinner } from './StateMark.tsx'; import { composeNumber, findNeighbours } from '../shelve.ts'; /** `new` may carry what was typed in the entry box. */ export type EditorTarget = { kind: 'edit'; id: number } | { kind: 'new'; title?: string; authors?: string }; const yearValue = (text: string) => { const y = parseYear(text); return y.ok ? y.value : null; }; const splitAuthors = (text: string) => text.split(/[;\n]/).map(a => a.trim()).filter(Boolean); /** A book that has not been found yet is titled with its ISBN or LCCN; that is not worth searching for. */ const knownTitle = (b: Book) => (/^[\d\s-]+$/.test(b.title) ? '' : b.title); export function Editor({ target, onClose }: { target: EditorTarget; onClose: () => void }) { useBooks(); // re-render when the book changes underneath const book = target.kind === 'edit' ? getBook(target.id) : undefined; const missing = target.kind === 'edit' && !book; useEffect(() => { if (missing) onClose(); }, [missing]); if (target.kind === 'edit' && !book) return null; const fixing = !!book && rowState(book).kind === 'attention'; return ( ); } function EditorForm({ book, fixing, initial, onClose }: { book: Book | undefined; fixing: boolean; initial?: { title?: string; authors?: string }; onClose: () => void; }) { const [title, setTitle] = useState(book ? knownTitle(book) || book.title : initial?.title ?? ''); const [authors, setAuthors] = useState(book?.authors.join('; ') ?? initial?.authors ?? ''); const [publisher, setPublisher] = useState(book?.publisher ?? ''); const [year, setYear] = useState(book?.year?.toString() ?? ''); const [callNumber, setCallNumber] = useState(book?.callNumber ?? ''); const [picked, setPicked] = useState(null); const [yearError, setYearError] = useState(''); const [error, setError] = useState(''); const [busy, setBusy] = useState(false); const [confirming, setConfirming] = useState(false); async function run(fn: () => Promise) { setBusy(true); setError(''); try { await fn(); } catch (e) { setError((e as Error).message); } setBusy(false); } function 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 names = splitAuthors(authors); if (!book) { const created = await api.addManual({ title: title.trim(), authors: names, ...(y.value !== null ? { year: y.value } : {}), ...(publisher.trim() ? { publisher: publisher.trim() } : {}), ...(callNumber.trim() ? { callNumber: callNumber.trim() } : {}), }); upsertBook(created); setLastScan(created.id, false); showToast(`Added "${created.title}"`); onClose(); return; } const patch: BookPatch = { title: title.trim(), authors: names, publisher: publisher.trim() || null, year: y.value }; const numberChanged = callNumber.trim() !== (book.callNumber ?? ''); if (numberChanged) patch.callNumber = callNumber.trim(); let saved = await api.patchBook(book.id, patch); // A result without a call number of its own: ask the sources again with the better details. if (picked && picked.lcc.length === 0 && !numberChanged && !book.manualOverride) saved = await api.retryBook(book.id); upsertBook(saved); showToast(saved.status === 'pending' ? `Saved "${saved.title}". Looking up the call number.` : `Saved "${saved.title}"`); onClose(); }); } function pick(r: SearchResult) { setPicked(r); setTitle(r.title); setAuthors(r.authors.join('; ')); setPublisher(r.publisher ?? ''); setYear(r.year ? String(r.year) : ''); if (r.lcc[0]) setCallNumber(r.lcc[0]); } return (
{fixing && book ? ( <>

{book.attentionReason ?? 'This book needs a look.'}

) : null}
{yearError ? : null} composeNumber(neighbour, splitAuthors(authors), title, yearValue(year))} onChoose={setCallNumber} /> {error ? : null}
{book ? ( <> ) : null}
{book ? (
{confirming ? (
Delete this book?
) : ( )}
) : null} ); } /** "Search for it": looks the book up by title (and author) so its details can be copied into the fields. */ function FixSearch({ initial, onPick }: { initial: string; onPick: (r: SearchResult) => void }) { const [text, setText] = useState(initial); const [results, setResults] = useState(null); const [active, setActive] = useState(-1); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(''); async function search() { const { title, author } = splitTitleAuthor(text); if (!title) return; setBusy(true); setMessage(''); setResults(null); setActive(-1); try { const found = await api.search(title, author); setResults(found); if (found.length === 0) setMessage('No matches. Edit the details by hand below.'); } catch (e) { setMessage(`The search failed: ${(e as Error).message}`); } setBusy(false); } useEffect(() => { if (initial) void search(); }, []); const choose = (r: SearchResult) => { onPick(r); setResults(null); setMessage('Details copied below. Check them, then save.'); }; const open = !!results && results.length > 0; return ( ); } /** "Shelve it with…": search the library for a book this one belongs next to, and borrow its class for the call number. */ function ShelveWith({ exclude, compose, onChoose }: { exclude: number | undefined; compose: (neighbour: string) => string | null; onChoose: (n: string) => void }) { const books = useBooks(); const [text, setText] = useState(''); const [active, setActive] = useState(-1); const matches = findNeighbours(books.filter(b => b.id !== exclude), text); const open = matches.length > 0; const choose = (b: Book) => { const n = b.callNumber ? compose(b.callNumber) : null; if (!n) { showToast('Could not make a call number from that book'); return; } onChoose(n); setText(''); setActive(-1); showToast(`Call number set to ${n}. Check it, then save.`); }; return (
= 0 ? `shelve-results-${active}` : undefined} value={text} onInput={e => { setText(e.currentTarget.value); setActive(-1); }} onKeyDown={e => { if (open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) { e.preventDefault(); setActive(moveActive(e.key, active, matches.length)); } else if (e.key === 'Enter') { e.preventDefault(); if (open && active >= 0) choose(matches[active]!); } else if (e.key === 'Escape' && open) { e.preventDefault(); e.stopPropagation(); setText(''); } }} /> Pick a book this one belongs next to {open ? (
    {matches.map((b, i) => (
  • e.preventDefault()} onMouseMove={() => setActive(i)} onClick={() => choose(b)}> {b.title} {b.callNumber}
  • ))}
) : null}
); }