Files
booksorter/src/web/components/Editor.tsx
T

267 lines
13 KiB
TypeScript

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 (
<Panel title={!book ? 'Add a book' : fixing ? 'Fix this book' : 'Edit book'} onClose={onClose}>
<EditorForm book={book} fixing={fixing} initial={target.kind === 'new' ? target : undefined} onClose={onClose} />
</Panel>
);
}
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<SearchResult | null>(null);
const [yearError, setYearError] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const [confirming, setConfirming] = useState(false);
async function run(fn: () => Promise<void>) {
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 (
<form class="editor" onSubmit={save}>
{fixing && book ? (
<>
<p class="state-text state-attention">{book.attentionReason ?? 'This book needs a look.'}</p>
<FixSearch initial={knownTitle(book)} onPick={pick} />
</>
) : null}
<label class="field">Title
<input value={title} onInput={e => setTitle(e.currentTarget.value)} required data-autofocus={!fixing ? '' : undefined} />
</label>
<label class="field">Authors
<input value={authors} onInput={e => setAuthors(e.currentTarget.value)} />
<span class="help">Separate several with ;</span>
</label>
<div class="field-pair">
<label class="field">Publisher
<input value={publisher} onInput={e => setPublisher(e.currentTarget.value)} />
</label>
<label class="field">Year
<input inputMode="numeric" value={year} aria-invalid={yearError ? 'true' : undefined}
onInput={e => { setYear(e.currentTarget.value); setYearError(''); }} />
</label>
</div>
{yearError ? <p class="error" role="alert">{yearError}</p> : null}
<label class="field">Call number
<input class="mono" value={callNumber} onInput={e => setCallNumber(e.currentTarget.value)} />
<span class="help">{book ? 'Changing this locks the number' : 'Optional. Leave it empty to have it looked up.'}</span>
</label>
<ShelveWith exclude={book?.id} compose={neighbour => composeNumber(neighbour, splitAuthors(authors), title, yearValue(year))}
onChoose={setCallNumber} />
{error ? <p class="error" role="alert">{error}</p> : null}
<div class="actions">
<button type="submit" class="btn btn-primary" disabled={busy || !title.trim()}>Save</button>
{book ? (
<>
<button type="button" class="btn" disabled={busy || book.inQueue} title={book.inQueue ? 'Already in Cards to print' : undefined}
onClick={() => run(async () => {
upsertBook(await api.queueBook(book.id));
showToast(`Queued a card for "${book.title}"`);
onClose();
})}>Print another card</button>
<button type="button" class="btn" disabled={busy || book.manualOverride}
title={book.manualOverride ? 'This number was set by hand, so there is nothing to look up' : undefined}
onClick={() => run(async () => {
upsertBook(await api.retryBook(book.id));
showToast(`Looking up "${book.title}" again`);
onClose();
})}>Look up again</button>
</>
) : null}
</div>
{book ? (
<div class="danger-zone">
{confirming ? (
<div class="confirm" role="group" aria-label="Delete this book?">
<span class="confirm-text">Delete this book?</span>
<button type="button" class="btn btn-danger" disabled={busy} ref={el => { el?.focus(); }}
onClick={() => run(async () => {
await api.deleteBook(book.id);
dispatch({ type: 'delete', id: book.id });
showToast(`Deleted "${book.title}"`);
onClose();
})}>Delete</button>
<button type="button" class="btn" onClick={() => setConfirming(false)}>Keep</button>
</div>
) : (
<button type="button" class="btn btn-text btn-danger" disabled={busy} onClick={() => setConfirming(true)}>Delete</button>
)}
</div>
) : null}
</form>
);
}
/** "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<SearchResult[] | null>(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 (
<div class="fix-search">
<label class="field">Search for it
<span class="search-row">
<input type="text" role="combobox" aria-expanded={open} aria-controls="fix-results" aria-autocomplete="list"
aria-activedescendant={open && active >= 0 ? `fix-results-${active}` : undefined}
value={text} data-autofocus="" autocomplete="off"
onInput={e => { setText(e.currentTarget.value); setActive(-1); }}
onKeyDown={e => {
if (e.key === 'Enter') {
e.preventDefault();
if (open && active >= 0) choose(results![active]!); else void search();
} else if (open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
e.preventDefault(); setActive(moveActive(e.key, active, results!.length));
} else if (e.key === 'Escape' && open) {
e.preventDefault(); e.stopPropagation(); setResults(null);
}
}} />
<button type="button" class="btn" disabled={busy || !text.trim()} onClick={() => void search()}>Search</button>
</span>
</label>
{busy ? <p class="help"><Spinner /> Searching…</p> : null}
{message ? <p class="help" role="status">{message}</p> : null}
{open ? <ResultList id="fix-results" label="Search results" results={results!} active={active} onPick={choose} onHover={setActive} /> : null}
</div>
);
}
/** "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 (
<div class="field">
<label for="shelve-with">Shelve it with…</label>
<input id="shelve-with" type="text" role="combobox" autocomplete="off" aria-expanded={open} aria-controls="shelve-results" aria-autocomplete="list"
aria-activedescendant={open && active >= 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(''); }
}} />
<span class="help">Pick a book this one belongs next to</span>
{open ? (
<ul class="results" role="listbox" id="shelve-results" aria-label="Books in your library">
{matches.map((b, i) => (
<li role="option" id={`shelve-results-${i}`} aria-selected={i === active} class={'result' + (i === active ? ' active' : '')}
onMouseDown={e => e.preventDefault()} onMouseMove={() => setActive(i)} onClick={() => choose(b)}>
<span class="result-title">{b.title}</span>
<span class="result-sub mono">{b.callNumber}</span>
</li>
))}
</ul>
) : null}
</div>
);
}