Redesign the interface around Scan and Library, classify uncatalogued books from similar ones

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-18 11:01:50 -07:00
1 parent 308c0e1ed3
commit 6cec404e21
71 files changed
+8634 -1502

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
import { useEffect, useRef, useState } from 'preact/hooks';
import { startScanner } from '../scanner.ts';
import type { Scanner } from '../scanner.ts';
import { targetBox, ZOOM } from '../frame.ts';
import { beepAccept, beepLow, unlockAudio } from '../sound.ts';
import { getCamera, readFlag, updateCamera, useCamera, writeFlag } from '../camera.ts';
import { showError } from '../toast-store.ts';
const CAMERA_FLAG = 'cameraOn';
/** The video box is always 16:10; the picture fills it and the middle is shown, magnified. */
const BOX = targetBox(16 / 10);
const BOX_STYLE = { left: `${BOX.left}%`, top: `${BOX.top}%`, width: `${BOX.width}%`, height: `${BOX.height}%` };
function cameraMessage(e: unknown): string {
const name = (e as { name?: string })?.name;
if (name === 'NotAllowedError' || name === 'SecurityError') return 'Camera access was blocked. Allow it in the browser, or type below.';
if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'No camera was found. You can still type below.';
if (name === 'NotReadableError') return 'The camera is busy in another program.';
return 'The camera could not be started. You can still type below.';
}
type Cam = 'off' | 'starting' | 'on';
type Tone = 'info' | 'ok' | 'warn';
interface Status { text: string; tone: Tone; hold: boolean }
const NOT_FOUND = 'No barcode found. Try again.';
const NOT_FOUND_SAVED = 'No barcode found. Picture saved.';
const CameraIcon = () => (
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true">
<path d="M1.5 4.5h2.8l1-1.6h5.4l1 1.6h2.8v8h-13z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" />
<circle cx="8" cy="8.5" r="2.4" fill="none" stroke="currentColor" stroke-width="1.5" />
</svg>
);
/**
* The live camera with its controls on a bar along the bottom edge. `onIsbn` gets every ISBN it reads.
* `captureRef.current` is set to a function that takes one careful picture (it returns false when the camera is off).
*/
export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void; captureRef: { current: (() => boolean) | null } }) {
const cam = useCamera();
const video = useRef<HTMLVideoElement>(null);
const scanner = useRef<Scanner | null>(null);
const opening = useRef<AbortController | null>(null);
const statusTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const flashTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const [state, setState] = useState<Cam>('off');
const [problem, setProblem] = useState('');
const [flash, setFlash] = useState(false);
const [status, setStatus] = useState<Status | null>(null);
const [capturing, setCapturing] = useState(false);
/** Show a message on the bar. Unless `hold`, it falls back to "Looking for a barcode…" after a few seconds. */
const say = (text: string, tone: Tone, hold = false) => {
clearTimeout(statusTimer.current);
setStatus({ text, tone, hold });
if (!hold) statusTimer.current = setTimeout(() => setStatus(null), 4000);
};
const gotIsbn = (isbn: string) => {
beepAccept();
setFlash(true);
clearTimeout(flashTimer.current);
flashTimer.current = setTimeout(() => setFlash(false), 600);
say(`Read ${isbn}`, 'ok');
onIsbn(isbn);
};
const handlers = useRef({ onIsbn: gotIsbn, onOther: () => {}, onEnded: () => {} });
handlers.current = {
onIsbn: gotIsbn,
onOther: () => { beepLow(); say('That barcode is not an ISBN', 'warn'); },
onEnded: () => {
scanner.current = null; setState('off'); setStatus(null); updateCamera({ resolution: '' });
setProblem('The camera stopped. Turn it on again to keep scanning.');
},
};
/** `user` is true when the person turned it off: only then is the camera forgotten for the next visit. */
function stopCamera(user: boolean) {
opening.current?.abort(); opening.current = null;
scanner.current?.stop(); scanner.current = null;
setState('off'); setStatus(null); setCapturing(false); updateCamera({ resolution: '' });
if (user) writeFlag(CAMERA_FLAG, null);
}
async function startCamera() {
if (opening.current || scanner.current || !video.current) return; // a second click does nothing
unlockAudio(); // needs the user gesture (a no-op for an automatic start)
const ac = new AbortController();
opening.current = ac;
setState('starting'); setProblem('');
try {
const sc = await startScanner(video.current, getCamera().deviceId || undefined, {
onIsbn: i => handlers.current.onIsbn(i), onOther: c => handlers.current.onOther(), onEnded: () => handlers.current.onEnded(),
}, ac.signal);
if (!sc) return; // turned off or left the screen while the permission prompt was open
if (ac.signal.aborted) { sc.stop(); return; }
scanner.current = sc;
setState('on');
writeFlag(CAMERA_FLAG, '1');
const v = video.current;
if (v?.videoWidth) updateCamera({ resolution: `${v.videoWidth}×${v.videoHeight}` });
const all = (await navigator.mediaDevices.enumerateDevices()).filter(d => d.kind === 'videoinput');
updateCamera({ devices: all.map(d => ({ id: d.deviceId, label: d.label })) });
} catch (e) {
if (ac.signal.aborted) return;
setState('off');
const msg = cameraMessage(e);
setProblem(msg); showError(msg);
if ((e as { name?: string })?.name === 'NotAllowedError') writeFlag(CAMERA_FLAG, null);
} finally {
if (opening.current === ac) opening.current = null;
}
}
async function capture() {
const sc = scanner.current;
if (!sc || capturing) return;
setCapturing(true);
say('Trying… 0 frames', 'info', true);
try {
const r = await sc.capture(n => say(`Trying… ${n} frames`, 'info', true));
if (scanner.current !== sc) return;
if (r.isbn) gotIsbn(r.isbn);
else if (r.other) { beepLow(); say('That barcode is not an ISBN', 'warn', true); }
else { beepLow(); say(r.saved ? NOT_FOUND_SAVED : NOT_FOUND, 'warn', true); }
} catch {
say(NOT_FOUND, 'warn', true);
}
setCapturing(false);
}
captureRef.current = () => {
if (!scanner.current) return false;
void capture();
return true;
};
// Turn the camera off when leaving the screen, and back on when it was on last time and the browser
// already allows it (no prompt).
useEffect(() => {
if (readFlag(CAMERA_FLAG) === '1') {
navigator.permissions?.query({ name: 'camera' as PermissionName })
.then(p => { if (p.state === 'granted') void startCamera(); }, () => {});
}
return () => { stopCamera(false); clearTimeout(statusTimer.current); clearTimeout(flashTimer.current); captureRef.current = null; };
}, []);
// Choosing another camera in the settings restarts a running one.
const lastDevice = useRef(cam.deviceId);
useEffect(() => {
if (lastDevice.current === cam.deviceId) return;
lastDevice.current = cam.deviceId;
if (scanner.current || opening.current) { stopCamera(false); void startCamera(); }
}, [cam.deviceId]);
const shown: Status = status ?? { text: 'Looking for a barcode…', tone: 'info', hold: true };
return (
<div class={'video-frame' + (flash ? ' flash' : '')}>
<video ref={video} playsInline muted aria-label="Camera view" style={{ transform: `scale(${-ZOOM}, ${ZOOM})` }}
onLoadedMetadata={e => { const v = e.currentTarget; if (v.videoWidth) updateCamera({ resolution: `${v.videoWidth}×${v.videoHeight}` }); }} />
{state === 'on' ? (
<>
<div class="target" aria-hidden="true" style={BOX_STYLE} />
<div class="video-bar">
<p class={'video-status tone-' + shown.tone} role="status" aria-live="polite" title={shown.text}>{shown.text}</p>
<button type="button" class="btn btn-video" disabled={capturing} onClick={() => void capture()}
title="Take one careful picture now (Space)">{capturing ? 'Reading…' : 'Capture'}</button>
<button type="button" class="btn btn-video btn-video-icon" onClick={() => stopCamera(true)}
aria-label="Turn camera off" title="Turn camera off"><CameraIcon /></button>
</div>
</>
) : (
<div class="video-empty">
<button type="button" class="btn btn-video" disabled={state === 'starting'} onClick={() => void startCamera()}>
{state === 'starting' ? 'Starting camera…' : 'Turn on camera'}
</button>
{problem ? <p class="video-problem" role="alert">{problem}</p> : null}
</div>
)}
</div>
);
}
+129
View File
@@ -0,0 +1,129 @@
import { useEffect, useRef, useState } from 'preact/hooks';
import { api } from '../api.ts';
import { printStatus } from '../bookstate.ts';
import { useDialog } from '../dialog.ts';
import { useQueue } from '../live.ts';
import { removeWithUndo } from '../removal.ts';
import { sheetCount } from '../sheets.ts';
import { showError, showToast } from '../toast-store.ts';
import { QueueRow } from '../components/BookRow.tsx';
interface MadePdf { ids: number[]; url: string }
export function CardsToPrint({ onFix }: { onFix: (id: number) => void }) {
const queue = useQueue();
const status = printStatus(queue);
const [open, setOpen] = useState(false);
const [made, setMade] = useState<MadePdf | null>(null);
const pdfUrl = useRef<string | null>(null);
useEffect(() => () => { if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); }, []);
// Nothing left to print while the panel is open (for example the last card was removed): close it.
useEffect(() => { if (open && status.ready === 0 && !made) setOpen(false); }, [open, status.ready, made]);
function forget() {
if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current);
pdfUrl.current = null; setMade(null);
}
return (
<section class="cards" aria-labelledby="cards-heading">
<div class="cards-head">
<h2 id="cards-heading">Cards to print <span class="count">{queue.length}</span></h2>
<div class="cards-print">
{status.reason ? <span class="cards-reason" role="status">{status.reason}</span> : null}
<div class="print-anchor">
<button type="button" class={'btn ' + (open ? '' : 'btn-primary')} disabled={status.ready === 0 && !made}
aria-haspopup="dialog" aria-expanded={open} onClick={() => setOpen(o => !o)}>{status.label}</button>
{open ? <PrintPanel ready={status.ready} made={made} setMade={setMade} pdfUrl={pdfUrl} forget={forget} onClose={() => setOpen(false)} /> : null}
</div>
</div>
</div>
{queue.length === 0 ? (
<p class="empty">No cards waiting. Scan a book to start.</p>
) : (
<ul class="rows">
{queue.map(b => <QueueRow key={b.id} book={b} onFix={() => onFix(b.id)} onRemove={() => removeWithUndo(b)} />)}
</ul>
)}
</section>
);
}
/** Where the first card goes, then the PDF, then "did it print?". Anchored under the print button. */
function PrintPanel({ ready, made, setMade, pdfUrl, forget, onClose }: {
ready: number; made: MadePdf | null; setMade: (m: MadePdf | null) => void;
pdfUrl: { current: string | null }; forget: () => void; onClose: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useDialog(ref, onClose, false);
const [start, setStart] = useState(1);
const [busy, setBusy] = useState(false);
const sheets = sheetCount(ready, start);
// Keep keyboard focus inside when the panel changes from the question to the confirmation.
const first = useRef(true);
useEffect(() => {
if (first.current) { first.current = false; return; }
ref.current?.querySelector<HTMLElement>('.btn-primary')?.focus();
}, [made === null]);
async function makePdf() {
setBusy(true);
// Open the tab inside the click so the popup blocker allows it, then point it at the PDF.
const tab = window.open('', '_blank');
try {
const { blob, ids } = await api.fetchPdf(start);
if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); // the previous PDF is no longer needed
const url = URL.createObjectURL(new Blob([blob], { type: 'application/pdf' }));
pdfUrl.current = url;
if (tab) tab.location.href = url;
setMade({ ids, url });
} catch (e) {
tab?.close();
showError(`Could not make the PDF: ${(e as Error).message}`);
}
setBusy(false);
}
async function confirm() {
if (!made) return;
try {
await api.confirmPrint(made.ids);
showToast(`Cleared ${made.ids.length} ${made.ids.length === 1 ? 'card' : 'cards'} from the list`);
forget(); onClose();
} catch (e) { showError(`Could not clear the cards: ${(e as Error).message}`); }
}
return (
<div class="print-panel" role="dialog" aria-label="Print cards" ref={ref} tabIndex={-1}>
{made ? (
<>
<p class="print-question">Did the cards print correctly?</p>
<p class="help"><a href={made.url} target="_blank" rel="noopener">Open the PDF again</a> if the tab did not open.</p>
<div class="actions">
<button type="button" class="btn btn-primary" onClick={() => void confirm()}>Yes, clear them</button>
<button type="button" class="btn" onClick={() => { forget(); onClose(); }}>Not yet</button>
</div>
</>
) : (
<>
<div class="slots-wrap">
<span class="slots-label" id="slots-label">First card goes in</span>
<div class="sheet" role="radiogroup" aria-labelledby="slots-label">
{[1, 2, 3].map(n => (
<button type="button" role="radio" aria-checked={start === n} aria-label={`Slot ${n} of 3`}
class={'slot' + (start === n ? ' on' : '') + (n < start ? ' used' : '')} onClick={() => setStart(n)}>{n}</button>
))}
</div>
</div>
<p class="print-note">Print at actual size (100%), single-sided, from the manual feed slot</p>
<p class="help">{ready} {ready === 1 ? 'card' : 'cards'} on {sheets} {sheets === 1 ? 'sheet' : 'sheets'}</p>
<div class="actions">
<button type="button" class="btn btn-primary" disabled={busy || ready === 0} onClick={() => void makePdf()}>{busy ? 'Making PDF…' : 'Make PDF'}</button>
</div>
</>
)}
</div>
);
}
-43
View File
@@ -1,43 +0,0 @@
import { useState } from 'preact/hooks';
import { useBooks } from '../live.ts';
import { CallNo } from '../components/CallNo.tsx';
import { BookEditor } from '../components/BookEditor.tsx';
export function Catalog() {
const books = useBooks();
const [q, setQ] = useState('');
const [attentionOnly, setAttentionOnly] = useState(false);
const [openId, setOpenId] = useState<number | null>(null);
const needle = q.trim().toLowerCase();
const shown = books.filter(b => {
if (attentionOnly && b.status !== 'needs_attention') return false;
if (!needle) return true;
return [b.title, b.authors.join(' '), b.isbn13 ?? '', b.callNumber ?? ''].some(s => s.toLowerCase().includes(needle));
});
return (
<div class="catalog">
<div class="row wrap">
<input class="grow" type="search" placeholder="Search title, author, ISBN or call number" aria-label="Search" value={q} onInput={e => setQ(e.currentTarget.value)} />
<label class="check"><input type="checkbox" checked={attentionOnly} onChange={e => setAttentionOnly(e.currentTarget.checked)} /> Needs attention only</label>
</div>
<p class="muted">{shown.length} of {books.length} books</p>
{shown.length === 0 ? <p class="muted">Nothing to show.</p> : null}
<ul class="list">
{shown.map(b => (
<li class="item column" key={b.id}>
<button class="item-btn" onClick={() => setOpenId(openId === b.id ? null : b.id)} aria-expanded={openId === b.id}>
{b.status === 'pending' ? <span class="callno muted">Looking up…</span> : <CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />}
<span class="item-main">
<strong class="title">{b.title}</strong>
<span class="muted">{[b.authors.join(', '), b.year].filter(Boolean).join(' · ')}</span>
{b.status === 'needs_attention' ? <span class="chip warn">Needs attention</span> : null}
{b.status === 'pending' ? <span class="chip pending">Looking up…</span> : null}
</span>
</button>
{openId === b.id ? <BookEditor book={b} onClose={() => setOpenId(null)} /> : null}
</li>
))}
</ul>
</div>
);
}
+97
View File
@@ -0,0 +1,97 @@
import { useRef, useState } from 'preact/hooks';
import type { RefObject } from 'preact';
import type { SearchResult } from '../../shared/types.ts';
import { api } from '../api.ts';
import { addByIsbn, addByLccn, addFromResult } from '../actions.ts';
import { classifyEntry } from '../entry.ts';
import { beepAccept, beepLow } from '../sound.ts';
import { showError } from '../toast-store.ts';
import { moveActive, ResultList } from '../components/Results.tsx';
import { Spinner } from '../components/StateMark.tsx';
import type { EditorTarget } from '../components/Editor.tsx';
/** The one entry box: an ISBN, an LCCN, or a title to search for. */
export function Entry({ inputRef, onEdit }: { inputRef: RefObject<HTMLInputElement | null>; onEdit: (t: EditorTarget) => void }) {
const [text, setText] = useState('');
const [message, setMessage] = useState('');
const [searching, setSearching] = useState(false);
const [results, setResults] = useState<SearchResult[] | null>(null);
const [active, setActive] = useState(-1);
const seq = useRef(0);
const query = useRef({ title: '', author: '' });
const open = results !== null;
const count = open ? results.length + 1 : 0; // the last option is always "Not listed?"
const close = () => { seq.current++; setResults(null); setActive(-1); setSearching(false); };
async function search(title: string, author: string) {
const mine = ++seq.current;
query.current = { title, author };
setSearching(true); setResults(null); setActive(-1);
try {
const found = await api.search(title, author);
if (mine !== seq.current) return;
setResults(found);
} catch (e) {
if (mine !== seq.current) return;
showError(`The search failed: ${(e as Error).message}`);
}
setSearching(false);
}
async function submit() {
const action = classifyEntry(text);
setMessage('');
switch (action.kind) {
case 'empty': return;
case 'bad-digits': beepLow(); setMessage('That is not a valid ISBN'); return;
case 'isbn': beepAccept(); setText(''); close(); await addByIsbn(action.isbn); return;
case 'lccn': if (await addByLccn(action.lccn)) { beepAccept(); setText(''); close(); } return;
case 'title': await search(action.title, action.author); return;
}
}
async function pick(r: SearchResult) {
if (await addFromResult(r)) { beepAccept(); setText(''); close(); }
}
function manual() {
const t = query.current;
close(); setText('');
onEdit({ kind: 'new', title: t.title, authors: t.author });
}
const choose = (i: number) => { if (!results) return; if (i < results.length) void pick(results[i]!); else manual(); };
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Enter') {
e.preventDefault();
if (open && active >= 0) choose(active); else void submit();
} else if (open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
e.preventDefault(); setActive(moveActive(e.key, active, count));
} else if (e.key === 'Escape' && (open || searching)) {
e.preventDefault(); close();
}
}
return (
<div class="entry">
<input ref={inputRef} class="entry-input" type="text" inputMode="text" autocomplete="off" spellcheck={false}
placeholder="Type an ISBN, or a title to search" aria-label="ISBN or title"
role="combobox" aria-expanded={open} aria-controls="entry-results" aria-autocomplete="list"
aria-activedescendant={open && active >= 0 ? `entry-results-${active}` : undefined}
aria-describedby="entry-help" aria-invalid={message ? 'true' : undefined}
value={text} onKeyDown={onKeyDown}
onInput={e => { setText(e.currentTarget.value); setMessage(''); if (open || searching) close(); }} />
<p class={'entry-help' + (message ? ' error' : '')} id="entry-help" role={message ? 'alert' : undefined}>
{message || (searching ? <><Spinner /> Searching…</> : 'Also takes an LCCN, such as 88005934.')}
</p>
{open ? (
<div class="entry-pop">
{results.length === 0 ? <p class="entry-none" role="status">No matches for “{query.current.title}”.</p> : null}
<ResultList id="entry-results" label="Search results" results={results} active={active} onPick={r => void pick(r)} onHover={setActive}
footer={{ label: 'Not listed? Enter it by hand', onPick: manual }} />
</div>
) : null}
</div>
);
}
+60
View File
@@ -0,0 +1,60 @@
import { useState } from 'preact/hooks';
import { api } from '../api.ts';
import { rowState } from '../bookstate.ts';
import { upsertBook, useBooks, useLastScan } from '../live.ts';
import { showError, showToast } from '../toast-store.ts';
import { CallNo } from '../components/CallNo.tsx';
import { CheckIcon, LABEL, Spinner, StateText, WarnIcon } from '../components/StateMark.tsx';
/** The book handled last, big enough to read at a glance while looking at the camera. */
export function LastScan({ onFix }: { onFix: (id: number) => void }) {
const last = useLastScan();
const books = useBooks();
const [busy, setBusy] = useState(false);
const book = last ? books.find(b => b.id === last.id) : undefined;
if (!last || !book) {
return <section class="last last-empty" aria-label="Last scan"><p>Hold a barcode up to the camera, or type below.</p></section>;
}
const s = rowState(book);
const already = last.existed && !book.inQueue;
async function printAnother() {
if (!book) return;
setBusy(true);
try {
upsertBook(await api.queueBook(book.id));
showToast(`Queued a card for "${book.title}"`);
} catch (e) { showError(`Could not queue "${book.title}": ${(e as Error).message}`); }
setBusy(false);
}
return (
<section class="last" aria-label="Last scan" aria-live="polite">
<h2 class="last-title">{book.title}</h2>
{book.authors.length ? <p class="last-author">{book.authors.join(', ')}</p> : null}
<div class="last-state">
{s.kind === 'looking' ? <><span class="last-mark"><Spinner /></span><StateText book={book} /></> : null}
{s.kind === 'ready' ? (
<>
<span class="last-mark last-ready" role="img" aria-label={LABEL.ready}><CheckIcon /></span>
<CallNo value={book.callNumber} approximate={book.confidence === 'approximate'} source={book.source} large />
</>
) : null}
{s.kind === 'attention' ? (
<>
<span class="last-mark last-attention" aria-hidden="true"><WarnIcon /></span>
<StateText book={book} />
<button type="button" class="btn" onClick={() => onFix(book.id)}>Fix</button>
</>
) : null}
</div>
{already && s.kind !== 'looking' ? (
<div class="last-already">
<span>Already in your library</span>
<button type="button" class="btn" disabled={busy} onClick={() => void printAnother()}>Print another card</button>
</div>
) : null}
</section>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { useState } from 'preact/hooks';
import { groupLibrary, needsAttention } from '../library.ts';
import { useBooks } from '../live.ts';
import { LibraryRow } from '../components/BookRow.tsx';
import type { EditorTarget } from '../components/Editor.tsx';
export function Library({ onEdit }: { onEdit: (t: EditorTarget) => void }) {
const books = useBooks();
const [query, setQuery] = useState('');
const [attentionFlag, setAttentionFlag] = useState(false);
const attention = books.filter(needsAttention).length;
const attentionOnly = attentionFlag && attention > 0;
const groups = groupLibrary(books, { query, attentionOnly });
if (books.length === 0) return <p class="empty empty-page">Your library is empty. Books appear here once scanned.</p>;
return (
<div class="library">
<div class="library-tools">
<input type="search" class="library-search" placeholder="Search title, author, ISBN or call number" aria-label="Search the library"
value={query} onInput={e => setQuery(e.currentTarget.value)} />
{attention > 0 ? (
<button type="button" class={'chip' + (attentionOnly ? ' on' : '')} aria-pressed={attentionOnly}
onClick={() => setAttentionFlag(!attentionOnly)}>Needs attention ({attention})</button>
) : null}
</div>
{groups.length === 0 ? <p class="empty">Nothing matches. Try fewer words.</p> : null}
{groups.map(g => (
<section class="group" key={g.key} aria-labelledby={`group-${g.key}`}>
<h2 class="group-head" id={`group-${g.key}`}>{g.heading} <span class="count">{g.books.length}</span></h2>
<ul class="rows">
{g.books.map(b => <LibraryRow key={b.id} book={b} onOpen={() => onEdit({ kind: 'edit', id: b.id })} />)}
</ul>
</section>
))}
</div>
);
}
-166
View File
@@ -1,166 +0,0 @@
import { useEffect, useRef, useState } from 'preact/hooks';
import { api } from '../api.ts';
import { dispatch, upsertBook, useBooks } from '../live.ts';
import { sheetCount } from '../sheets.ts';
import { pdfLabel, queueHeader, queueSplit } from '../bookstate.ts';
import { StateLabel } from '../components/BookState.tsx';
import { CallNo } from '../components/CallNo.tsx';
import { BookEditor } from '../components/BookEditor.tsx';
export function Queue() {
const books = useBooks();
const { ready: queued, looking } = queueSplit(books);
const attention = books.filter(b => b.status === 'needs_attention');
const [start, setStart] = useState(1);
const [msg, setMsg] = useState('');
const [busy, setBusy] = useState(false);
const [pending, setPending] = useState<{ ids: number[]; url: string } | null>(null);
const [editId, setEditId] = useState<number | null>(null);
const sheets = sheetCount(queued.length, start);
const pdfUrl = useRef<string | null>(null);
useEffect(() => () => { if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); }, []);
async function makePdf() {
setMsg(''); setBusy(true);
// Open the tab inside the click so the popup blocker allows it, then point it at the PDF.
const tab = window.open('', '_blank');
try {
const { blob, ids } = await api.fetchPdf(start);
if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); // the previous PDF is no longer needed
const url = URL.createObjectURL(new Blob([blob], { type: 'application/pdf' }));
pdfUrl.current = url;
if (tab) tab.location.href = url;
setPending({ ids, url });
} catch (e) {
tab?.close();
setMsg((e as Error).message);
}
setBusy(false);
}
async function confirmPrinted() {
if (!pending) return;
try {
await api.confirmPrint(pending.ids);
URL.revokeObjectURL(pending.url); pdfUrl.current = null;
setPending(null);
setMsg('');
// Live events will update the books; refresh the local copies too.
for (const b of await api.listBooks('all')) upsertBook(b);
} catch (e) { setMsg((e as Error).message); }
}
return (
<div class="queue">
<section>
<h2>Print queue</h2>
<p class="summary" aria-live="polite">{queueHeader(queued.length, looking.length)}</p>
{queued.length ? <p class="muted small">{sheets} {sheets === 1 ? 'sheet' : 'sheets'} of 3 cards</p> : null}
{queued.length === 0 && looking.length === 0 ? <p class="muted">Nothing is waiting to print.</p> : null}
<ul class="list">
{queued.map(b => (
<li class="item" key={b.id}>
<CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />
<span class="item-main"><strong class="title">{b.title}</strong><span class="muted">{b.authors.join(', ')}</span></span>
<StateLabel book={b} />
</li>
))}
{looking.map(b => (
<li class="item dim" key={b.id} data-state="looking">
<span class="callno-slot" aria-hidden="true" />
<span class="item-main">
<strong class="title">{b.title}</strong><span class="muted">{b.authors.join(', ')}</span>
{b.attentionReason ? <span class="muted small note">{b.attentionReason}</span> : null}
</span>
<StateLabel book={b} />
</li>
))}
</ul>
<fieldset class="start">
<legend>First card goes in position</legend>
<div class="sheet" role="radiogroup" aria-label="Start position">
{[1, 2, 3].map(n => (
<button type="button" role="radio" aria-checked={start === n} class={'slot' + (start === n ? ' on' : '') + (n < start ? ' used' : '')}
onClick={() => setStart(n)}>{n}</button>
))}
</div>
</fieldset>
<p class="muted">Print at actual size (100%), single-sided, from the manual feed slot.</p>
<button class="primary" disabled={busy || queued.length === 0} aria-describedby={queued.length === 0 ? 'pdf-why' : undefined} onClick={makePdf}>{busy ? 'Making PDF' : pdfLabel(queued.length)}</button>
{queued.length === 0 ? (
<p class="muted small" id="pdf-why">{looking.length
? 'No card is ready yet. Books still being looked up are added to the PDF once they have a call number.'
: 'There are no cards to print. Scan a book first.'}</p>
) : looking.length ? <p class="muted small">The PDF holds the ready cards only. The {looking.length === 1 ? 'book' : 'books'} still looking up will be in the next one.</p> : null}
{msg ? <p class="error" role="alert">{msg}</p> : null}
{pending ? (
<div class="card confirm" role="alert">
<p><strong>Did the cards print correctly?</strong></p>
<p class="muted"><a href={pending.url} target="_blank" rel="noopener">Open the PDF again</a> if the tab did not open.</p>
<div class="row wrap">
<button class="primary" onClick={confirmPrinted}>Yes, clear these from the queue</button>
<button onClick={() => { URL.revokeObjectURL(pending.url); pdfUrl.current = null; setPending(null); }}>Not yet</button>
</div>
</div>
) : null}
</section>
<section>
<h2>Needs attention</h2>
{attention.length === 0 ? <p class="muted">No book needs attention.</p> : null}
<ul class="list">
{attention.map(b => (
<li class="item column" key={b.id}>
<div class="item-main">
<strong class="title">{b.title}</strong>
<span class="muted">{b.authors.join(', ')}</span>
<span class="warn-text">{b.attentionReason}</span>
</div>
<div class="row wrap">
<button disabled={b.manualOverride} onClick={async () => { try { upsertBook(await api.retryBook(b.id)); } catch (e) { setMsg((e as Error).message); } }}>Retry</button>
<button onClick={() => setEditId(editId === b.id ? null : b.id)}>Edit</button>
<button class="danger" onClick={async () => {
if (!confirm(`Delete "${b.title}"?`)) return;
try { await api.deleteBook(b.id); dispatch({ type: 'delete', id: b.id }); } catch (e) { setMsg((e as Error).message); }
}}>Delete</button>
</div>
{editId === b.id ? <BookEditor book={b} onClose={() => setEditId(null)} /> : null}
</li>
))}
</ul>
</section>
<Alignment />
</div>
);
}
function Alignment() {
const [x, setX] = useState('0'); const [y, setY] = useState('0');
const [msg, setMsg] = useState('');
const loaded = useRef(false);
useEffect(() => {
api.getSettings().then(s => { setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); loaded.current = true; }).catch(() => {});
}, []);
const save = async () => {
setMsg('');
try {
const s = await api.putSettings({ offsetXmm: Number(x) || 0, offsetYmm: Number(y) || 0 });
setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); setMsg('Saved');
} catch (e) { setMsg((e as Error).message); }
};
return (
<section>
<h2>Printer alignment</h2>
<div class="row wrap">
<label>Offset X (mm)<input type="number" step="0.25" min="-10" max="10" value={x} onInput={e => setX(e.currentTarget.value)} /></label>
<label>Offset Y (mm)<input type="number" step="0.25" min="-10" max="10" value={y} onInput={e => setY(e.currentTarget.value)} /></label>
</div>
<div class="row wrap">
<button onClick={save}>Save offsets</button>
<a class="button" href="/api/calibration.pdf" target="_blank" rel="noopener">Print calibration page</a>
</div>
{msg ? <p class="muted" role="status">{msg}</p> : null}
</section>
);
}
+39 -383
View File
@@ -1,407 +1,63 @@
import { useEffect, useRef, useState } from 'preact/hooks';
import type { Book, SearchResult } from '../../shared/types.ts';
import { normalizeIsbn } from '../../shared/isbn.ts';
import { api } from '../api.ts';
import { getBook, upsertBook, useBooks } from '../live.ts';
import { startScanner } from '../scanner.ts';
import type { Scanner } from '../scanner.ts';
import { targetBox, ZOOM } from '../frame.ts';
import { beepAccept, beepLow, unlockAudio } from '../sound.ts';
import { emptySession, touch } from '../session.ts';
import type { SessionState } from '../session.ts';
import { rowState, sessionSummary } from '../bookstate.ts';
import { parseYear } from '../year.ts';
import { CallNo } from '../components/CallNo.tsx';
import { BookEditor } from '../components/BookEditor.tsx';
import { StateLabel } from '../components/BookState.tsx';
import { useEffect, useRef } from 'preact/hooks';
import { addByIsbn } from '../actions.ts';
import { dialogOpen } from '../dialog.ts';
import { unlockAudio } from '../sound.ts';
import type { EditorTarget } from '../components/Editor.tsx';
import { Camera } from './Camera.tsx';
import { CardsToPrint } from './CardsToPrint.tsx';
import { Entry } from './Entry.tsx';
import { LastScan } from './LastScan.tsx';
// Kept at module level so the list survives switching tabs.
let session: SessionState = emptySession;
/** ISBNs with a request in flight: one ISBN is never sent twice at the same time. */
const inflight = new Map<string, Promise<void>>();
const CAMERA_FLAG = 'cameraOn';
const readFlag = (k: string) => { try { return localStorage.getItem(k); } catch { return null; } };
const writeFlag = (k: string, v: string | null) => {
try { if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* ignore */ }
};
function cameraMessage(e: unknown): string {
const name = (e as { name?: string })?.name;
if (name === 'NotAllowedError' || name === 'SecurityError') return 'Camera access was blocked. Allow it in the browser, or type the ISBN below.';
if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'No camera was found. You can still type or scan the ISBN below.';
if (name === 'NotReadableError') return 'The camera is busy in another program.';
return 'The camera could not be started. You can still type the ISBN below.';
/** Space reaches the camera unless focus is in a text field other than an empty entry box (titles contain spaces). */
function spaceIsForCamera(active: HTMLElement | null, entry: HTMLInputElement | null): boolean {
if (!active || active === document.body) return true;
if (active === entry) return entry.value === '';
return !(active.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'SUMMARY', 'A'].includes(active.tagName));
}
type Cam = 'off' | 'starting' | 'on';
type Tone = 'info' | 'ok' | 'warn';
interface Status { text: string; tone: Tone; hold: boolean }
export function Scan({ onEdit }: { onEdit: (t: EditorTarget) => void }) {
const entry = useRef<HTMLInputElement>(null);
const capture = useRef<(() => boolean) | null>(null);
const NOT_FOUND = 'No barcode found. Try again, or type the ISBN below.';
const NOT_FOUND_SAVED = 'No barcode found. Saved the picture to data/captures so the reader can be tuned.';
export function Scan() {
useBooks(); // re-render on live updates
const [, bump] = useState(0);
const refresh = () => bump(n => n + 1);
const video = useRef<HTMLVideoElement>(null);
const isbnBox = useRef<HTMLInputElement>(null);
const scanner = useRef<Scanner | null>(null);
const opening = useRef<AbortController | null>(null);
const statusTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const [cam, setCam] = useState<Cam>('off');
const [camError, setCamError] = useState('');
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
const [deviceId, setDeviceId] = useState(() => readFlag('camera') ?? '');
const [aspect, setAspect] = useState('16 / 9');
const [res, setRes] = useState('');
const [flash, setFlash] = useState(false);
const [status, setStatus] = useState<Status | null>(null);
const [capturing, setCapturing] = useState(false);
const [typed, setTyped] = useState('');
const [typedError, setTypedError] = useState('');
const [sendError, setSendError] = useState('');
const [editId, setEditId] = useState<number | null>(null);
/** Show a message under the video. Unless `hold`, it falls back to "Looking for a barcode…" after a few seconds. */
const say = (text: string, tone: Tone, hold = false) => {
clearTimeout(statusTimer.current);
setStatus({ text, tone, hold });
if (!hold) statusTimer.current = setTimeout(() => setStatus(null), 4000);
};
async function submitIsbn(isbn: string) {
setSendError('');
let p = inflight.get(isbn);
if (!p) {
p = (async () => {
try {
const r = await api.scan(isbn);
upsertBook(r.book);
session = touch(session, r.book.id, r.duplicate);
} catch (e) {
beepLow();
setSendError(`${isbn}: ${(e as Error).message}`);
}
})();
inflight.set(isbn, p);
void p.finally(() => inflight.delete(isbn));
}
await p;
refresh();
}
const addBook = (b: Book) => { session = touch(session, b.id, false); refresh(); };
const gotIsbn = (isbn: string) => {
beepAccept();
setFlash(true); setTimeout(() => setFlash(false), 600);
say(`Read ${isbn}`, 'ok');
void submitIsbn(isbn);
};
const handlers = useRef({ onIsbn: gotIsbn, onOther: (_c: string) => {}, onEnded: () => {} });
handlers.current = {
onIsbn: gotIsbn,
onOther: () => { beepLow(); say('That barcode is not an ISBN', 'warn'); },
onEnded: () => { scanner.current = null; setCam('off'); say('The camera stopped. Press Start camera to turn it on again.', 'warn', true); },
};
/** `user` is true when the person pressed Stop: only then is the camera forgotten for the next visit. */
function stopCamera(user: boolean) {
opening.current?.abort(); opening.current = null;
scanner.current?.stop(); scanner.current = null;
setCam('off'); setStatus(null); setCapturing(false); setAspect('16 / 9'); setRes('');
if (user) writeFlag(CAMERA_FLAG, null);
}
async function startCamera() {
if (opening.current || scanner.current || !video.current) return; // a second click does nothing
unlockAudio(); // needs the user gesture (a no-op for an automatic start)
const ac = new AbortController();
opening.current = ac;
setCam('starting'); setCamError('');
try {
const sc = await startScanner(video.current, deviceId || undefined, {
onIsbn: i => handlers.current.onIsbn(i), onOther: c => handlers.current.onOther(c), onEnded: () => handlers.current.onEnded(),
}, ac.signal);
if (!sc) return; // stopped or left the view while the permission prompt was open
if (ac.signal.aborted) { sc.stop(); return; }
scanner.current = sc;
setCam('on');
writeFlag(CAMERA_FLAG, '1');
const v = video.current;
if (v?.videoWidth) { setAspect(`${v.videoWidth} / ${v.videoHeight}`); setRes(`${v.videoWidth}×${v.videoHeight}`); }
setDevices((await navigator.mediaDevices.enumerateDevices()).filter(d => d.kind === 'videoinput'));
} catch (e) {
if (ac.signal.aborted) return;
setCam('off');
setCamError(cameraMessage(e));
if ((e as { name?: string })?.name === 'NotAllowedError') writeFlag(CAMERA_FLAG, null);
} finally {
if (opening.current === ac) opening.current = null;
}
}
async function capture() {
const sc = scanner.current;
if (!sc || capturing) return;
setCapturing(true);
say('Trying… 0 frames', 'info', true);
try {
const r = await sc.capture(n => say(`Trying… ${n} frames`, 'info', true));
if (scanner.current !== sc) return;
if (r.isbn) gotIsbn(r.isbn);
else if (r.other) { beepLow(); say('That barcode is not an ISBN', 'warn', true); }
else { beepLow(); say(r.saved ? NOT_FOUND_SAVED : NOT_FOUND, 'warn', true); }
} catch {
say(NOT_FOUND, 'warn', true);
}
setCapturing(false);
}
const captureRef = useRef(capture);
captureRef.current = capture;
// Stop the camera when leaving the view, and start it again when it was on last time and the browser
// already allows it (no prompt).
// The entry box keeps keyboard focus, unless another field or an open panel has it; Space takes a picture.
useEffect(() => {
if (readFlag(CAMERA_FLAG) === '1') {
navigator.permissions?.query({ name: 'camera' as PermissionName })
.then(p => { if (p.state === 'granted') void startCamera(); }, () => {});
}
return () => { stopCamera(false); clearTimeout(statusTimer.current); };
}, []);
// Keep the ISBN box focused unless the user is typing in another field; Space takes a picture.
useEffect(() => {
const focusBox = () => {
const focusEntry = () => {
if (dialogOpen()) return;
const a = document.activeElement;
if (!a || a === document.body) isbnBox.current?.focus();
if (!a || a === document.body) entry.current?.focus();
};
focusBox();
const onOut = () => setTimeout(focusBox, 0);
focusEntry();
const onOut = () => setTimeout(focusEntry, 0);
const onKey = (e: KeyboardEvent) => {
unlockAudio();
if (e.ctrlKey || e.metaKey || e.altKey) return;
const a = document.activeElement as HTMLElement | null;
if (e.code === 'Space') {
const inOtherField = a && a !== isbnBox.current && (a.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'SUMMARY'].includes(a.tagName));
if (!inOtherField && scanner.current) { e.preventDefault(); if (!e.repeat) void captureRef.current(); }
return;
}
if ((!a || a === document.body) && /^[0-9xX-]$/.test(e.key)) isbnBox.current?.focus();
if (e.ctrlKey || e.metaKey || e.altKey || e.code !== 'Space' || dialogOpen()) return;
if (!spaceIsForCamera(document.activeElement as HTMLElement | null, entry.current)) return;
if (capture.current?.()) { e.preventDefault(); }
};
// A click on an empty part of the page puts the cursor back in the box.
const onClick = () => setTimeout(focusEntry, 0);
document.addEventListener('focusout', onOut);
document.addEventListener('keydown', onKey);
document.addEventListener('pointerdown', unlockAudio);
document.addEventListener('click', onClick);
return () => {
document.removeEventListener('focusout', onOut); document.removeEventListener('keydown', onKey);
document.removeEventListener('focusout', onOut);
document.removeEventListener('keydown', onKey);
document.removeEventListener('pointerdown', unlockAudio);
document.removeEventListener('click', onClick);
};
}, []);
const onSubmit = (ev: Event) => {
ev.preventDefault();
const raw = typed.trim();
if (!raw) return;
const isbn = normalizeIsbn(raw);
if (!isbn) { beepLow(); setTypedError('Not a valid ISBN'); return; }
setTypedError(''); setTyped('');
beepAccept();
void submitIsbn(isbn);
};
const rows = session.order.map(id => getBook(id)).filter((b): b is Book => !!b);
const shown: Status = status ?? (cam === 'on'
? { text: 'Looking for a barcode…', tone: 'info', hold: true }
: cam === 'starting'
? { text: 'Starting the camera. Allow access if the browser asks.', tone: 'info', hold: true }
: { text: 'The camera is off. Start it to scan, or type the ISBN below.', tone: 'info', hold: true });
const [aw, ah] = aspect.split('/').map(Number);
const t = targetBox((aw || 16) / (ah || 9));
const boxStyle = { left: `${t.left}%`, top: `${t.top}%`, width: `${t.width}%`, height: `${t.height}%` };
const fix = (id: number) => onEdit({ kind: 'edit', id });
return (
<div class="scan">
<section class="left">
<div class={'video-wrap' + (flash ? ' flash' : '')} style={{ aspectRatio: aspect }}>
<video ref={video} playsInline muted style={{ transform: `scale(${-ZOOM}, ${ZOOM})` }} onLoadedMetadata={e => {
const v = e.currentTarget; if (v.videoWidth) { setAspect(`${v.videoWidth} / ${v.videoHeight}`); setRes(`${v.videoWidth}×${v.videoHeight}`); }
}} />
{cam === 'on' ? (
<>
<div class="target" aria-hidden="true" style={boxStyle} />
<div class="hint" aria-hidden="true">Hold the barcode in the box, about a forearm's length from the camera</div>
<div class="scanning" aria-hidden="true"><span class="pulse" />Scanning</div>
</>
) : (
<div class="video-empty">
<button class="primary big" disabled={cam === 'starting'} onClick={startCamera}>{cam === 'starting' ? 'Starting camera…' : 'Start camera'}</button>
</div>
)}
</div>
<p class={'status ' + shown.tone} role="status" aria-live="polite" data-tone={shown.tone}>{shown.text}</p>
{cam === 'on' && res ? <p class="muted small res" aria-label="Camera resolution">{res}</p> : null}
<div class="row wrap">
<button class="primary" disabled={cam !== 'on' || capturing} onClick={() => void capture()}
title="Take one picture now and read it as carefully as possible (Space)">{capturing ? 'Reading…' : 'Capture'}</button>
{cam === 'on' ? <button onClick={() => stopCamera(true)}>Stop camera</button> : null}
{devices.length > 1 ? (
<select aria-label="Camera" value={deviceId} onChange={e => {
const v = e.currentTarget.value; setDeviceId(v); writeFlag('camera', v);
}}>
<option value="">Default camera</option>
{devices.map((d, i) => <option value={d.deviceId}>{d.label || `Camera ${i + 1}`}</option>)}
</select>
) : null}
<span class="muted small">{cam === 'on' ? 'Scans by itself. Capture or Space takes one careful picture.' : ''}</span>
</div>
{camError ? <p class="warn" role="alert">{camError}</p> : null}
<form class="isbn-form" onSubmit={onSubmit}>
<label>ISBN
<input ref={isbnBox} class="mono" inputMode="numeric" autocomplete="off" placeholder="Type or scan an ISBN, then Enter"
value={typed} onInput={e => { setTyped(e.currentTarget.value); setTypedError(''); }} />
</label>
{typedError ? <p class="error" role="alert">{typedError}</p> : null}
{sendError ? <p class="error" role="alert">{sendError}</p> : null}
</form>
</section>
<section class="right">
<h2>This session</h2>
{rows.length === 0 ? <p class="muted">Scanned books appear here, one row per book.</p> : <p class="summary" aria-live="polite">{sessionSummary(rows)}</p>}
<ul class="list">
{rows.map(b => (
<BookRow key={b.id} book={b} earlier={!!session.earlier[b.id]} touched={session.touched[b.id] ?? 0}
editing={editId === b.id} onEdit={() => setEditId(editId === b.id ? null : b.id)} />
))}
</ul>
</section>
<section class="forms">
<SearchForm onAdded={addBook} />
<LccnForm onAdded={addBook} />
<ManualForm onAdded={addBook} />
</section>
<div class="scan-left">
<Camera captureRef={capture} onIsbn={isbn => { void addByIsbn(isbn); }} />
<LastScan onFix={fix} />
<Entry inputRef={entry} onEdit={onEdit} />
</div>
<CardsToPrint onFix={fix} />
</div>
);
}
function BookRow({ book, earlier, touched, editing, onEdit }: { book: Book; earlier: boolean; touched: number; editing: boolean; onEdit: () => void }) {
const [queuing, setQueuing] = useState(false);
const s = rowState(book);
return (
<li class={'book ' + s.kind} data-state={s.kind} data-book-id={book.id}>
{touched > 1 ? <span class="flashbar" key={touched} aria-hidden="true" /> : null}
<div class="book-head">
<div class="item-main">
<strong class="title">{book.title}</strong>
{book.authors.length ? <span class="muted">{book.authors.join(', ')}</span> : null}
</div>
{earlier ? (
<div class="earlier">
<span class="muted small">Already in catalog</span>
{!book.inQueue ? (
<button disabled={queuing} onClick={async () => {
setQueuing(true);
try { upsertBook(await api.queueBook(book.id)); } catch { /* the row stays as it was */ }
setQueuing(false);
}}>Queue reprint</button>
) : null}
</div>
) : null}
</div>
<div class="book-state">
<StateLabel book={book} />
{s.kind === 'ready' ? <CallNo value={book.callNumber} approximate={book.confidence === 'approximate'} /> : null}
{s.kind === 'looking' && s.note ? <span class="muted small note">{s.note}</span> : null}
{s.kind === 'attention' ? (
<>
<span class="reason">{s.reason}</span>
<button class="fix" onClick={onEdit} aria-expanded={editing}>Fix</button>
</>
) : null}
</div>
{editing ? <BookEditor book={book} onClose={onEdit} /> : null}
</li>
);
}
function SearchForm({ onAdded }: { onAdded: (b: Book) => void }) {
const [title, setTitle] = useState(''); const [author, setAuthor] = useState('');
const [results, setResults] = useState<SearchResult[] | null>(null);
const [msg, setMsg] = useState(''); const [busy, setBusy] = useState(false);
const go = async (ev: Event) => {
ev.preventDefault(); setBusy(true); setMsg('');
try { setResults(await api.search(title.trim(), author.trim())); } catch (e) { setMsg((e as Error).message); }
setBusy(false);
};
return (
<details>
<summary>Search by title and author</summary>
<form onSubmit={go} class="stack">
<label>Title<input value={title} onInput={e => setTitle(e.currentTarget.value)} /></label>
<label>Author<input value={author} onInput={e => setAuthor(e.currentTarget.value)} /></label>
<button type="submit" disabled={busy || (!title.trim() && !author.trim())}>{busy ? 'Searching' : 'Search'}</button>
</form>
{msg ? <p class="error" role="alert">{msg}</p> : null}
{results && results.length === 0 ? <p class="muted">No results.</p> : null}
<ul class="list results">
{results?.map(r => (
<li><button class="result" onClick={async () => {
try { const b = await api.fromSearch(r); upsertBook(b); onAdded(b); setResults(null); } catch (e) { setMsg((e as Error).message); }
}}>
<strong>{r.title}</strong>
<span class="muted">{[r.authors.join(', '), r.year, r.publisher].filter(Boolean).join(' · ')}</span>
</button></li>
))}
</ul>
</details>
);
}
function LccnForm({ onAdded }: { onAdded: (b: Book) => void }) {
const [lccn, setLccn] = useState(''); const [msg, setMsg] = useState('');
return (
<details>
<summary>Enter LCCN</summary>
<form class="stack" onSubmit={async ev => {
ev.preventDefault(); setMsg('');
try { const b = await api.addLccn(lccn.trim()); upsertBook(b); onAdded(b); setLccn(''); } catch (e) { setMsg((e as Error).message); }
}}>
<label>LCCN<input class="mono" value={lccn} onInput={e => setLccn(e.currentTarget.value)} /></label>
<button type="submit" disabled={!lccn.trim()}>Add</button>
{msg ? <p class="error" role="alert">{msg}</p> : null}
</form>
</details>
);
}
function ManualForm({ onAdded }: { onAdded: (b: Book) => void }) {
const [title, setTitle] = useState(''); const [authors, setAuthors] = useState('');
const [year, setYear] = useState(''); const [cn, setCn] = useState(''); const [msg, setMsg] = useState('');
return (
<details>
<summary>Enter by hand</summary>
<form class="stack" onSubmit={async ev => {
ev.preventDefault(); setMsg('');
const y = parseYear(year);
if (!y.ok) { setMsg('Enter the year as digits, for example 2018, or leave it empty.'); return; }
try {
const b = await api.addManual({
title: title.trim(), authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean),
...(y.value !== null ? { year: y.value } : {}), ...(cn.trim() ? { callNumber: cn.trim() } : {}),
});
upsertBook(b); onAdded(b); setTitle(''); setAuthors(''); setYear(''); setCn('');
} catch (e) { setMsg((e as Error).message); }
}}>
<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>
<label>Year<input inputMode="numeric" value={year} onInput={e => setYear(e.currentTarget.value)} /></label>
<label>Call number (optional)<input class="mono" value={cn} onInput={e => setCn(e.currentTarget.value)} /></label>
<button type="submit" disabled={!title.trim()}>Add</button>
{msg ? <p class="error" role="alert">{msg}</p> : null}
</form>
</details>
);
}