Rework scan screen, make lookups non-blocking, fix review findings

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-18 10:19:32 -07:00
1 parent 468cafc6db
commit b5defb4e4f
46 files changed
+1957 -406

No files matched your search

+2 -1
View File
@@ -26,11 +26,12 @@ export function Catalog() {
{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}>
<CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />
{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}
+30 -7
View File
@@ -2,12 +2,14 @@ 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 queued = books.filter(b => b.inQueue && b.status === 'resolved' && b.callNumber);
const { ready: queued, looking } = queueSplit(books);
const attention = books.filter(b => b.status === 'needs_attention');
const [start, setStart] = useState(1);
const [msg, setMsg] = useState('');
@@ -15,6 +17,8 @@ export function Queue() {
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);
@@ -22,7 +26,9 @@ export function Queue() {
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) {
@@ -35,7 +41,7 @@ export function Queue() {
if (!pending) return;
try {
await api.confirmPrint(pending.ids);
URL.revokeObjectURL(pending.url);
URL.revokeObjectURL(pending.url); pdfUrl.current = null;
setPending(null);
setMsg('');
// Live events will update the books; refresh the local copies too.
@@ -47,13 +53,25 @@ export function Queue() {
<div class="queue">
<section>
<h2>Print queue</h2>
<p>{queued.length} {queued.length === 1 ? 'card' : 'cards'} ready, {sheets} {sheets === 1 ? 'sheet' : 'sheets'}</p>
{queued.length === 0 ? <p class="muted">Nothing is waiting to print.</p> : null}
<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>
@@ -68,7 +86,12 @@ export function Queue() {
</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} onClick={makePdf}>{busy ? 'Making PDF' : 'Make PDF'}</button>
<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">
@@ -76,7 +99,7 @@ export function Queue() {
<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); setPending(null); }}>Not yet</button>
<button onClick={() => { URL.revokeObjectURL(pending.url); pdfUrl.current = null; setPending(null); }}>Not yet</button>
</div>
</div>
) : null}
@@ -84,7 +107,7 @@ export function Queue() {
<section>
<h2>Needs attention</h2>
{attention.length === 0 ? <p class="muted">Every book has a call number.</p> : null}
{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}>
+212 -68
View File
@@ -4,13 +4,27 @@ 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 { TARGET } 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';
interface Entry { key: number; bookId?: number; duplicate?: boolean; note?: string; error?: boolean }
// Kept at module level so the list survives switching tabs.
let entries: Entry[] = [];
let nextKey = 1;
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;
@@ -20,58 +34,142 @@ function cameraMessage(e: unknown): string {
return 'The camera could not be started. You can still type the ISBN 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 in that picture. Move closer, add light, or type the ISBN below.';
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 stopRef = useRef<(() => void) | null>(null);
const [running, setRunning] = useState(false);
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(() => { try { return localStorage.getItem('camera') ?? ''; } catch { return ''; } });
const [deviceId, setDeviceId] = useState(() => readFlag('camera') ?? '');
const [aspect, setAspect] = useState('16 / 9');
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);
const addEntry = (e: Omit<Entry, 'key'>) => { entries = [{ key: nextKey++, ...e }, ...entries]; refresh(); };
/** 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) {
try {
const r = await api.scan(isbn);
upsertBook(r.book);
if (r.duplicate) beepLow();
addEntry({ bookId: r.book.id, duplicate: r.duplicate });
} catch (e) {
beepLow();
addEntry({ note: `${isbn}: ${(e as Error).message}`, error: true });
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 onIsbn = (isbn: string) => { beepAccept(); setFlash(true); setTimeout(() => setFlash(false), 250); void submitIsbn(isbn); };
const onReject = (code: string) => { beepLow(); addEntry({ note: `${code} is not a book barcode`, error: true }); };
const addBook = (b: Book) => { session = touch(session, b.id, false); refresh(); };
function stopCamera() {
stopRef.current?.(); stopRef.current = null; setRunning(false);
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');
if (user) writeFlag(CAMERA_FLAG, null);
}
async function startCamera() {
unlockAudio(); // needs the user gesture
setCamError('');
stopCamera();
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 {
if (!video.current) return;
stopRef.current = await startScanner(video.current, deviceId || undefined, onIsbn, onReject);
setRunning(true);
const all = await navigator.mediaDevices.enumerateDevices();
setDevices(all.filter(d => d.kind === 'videoinput'));
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}`);
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;
}
isbnBox.current?.focus();
}
useEffect(() => stopCamera, []); // stop on leaving the view
// Keep the ISBN box focused unless the user is typing in another field.
async function capture() {
const sc = scanner.current;
if (!sc || capturing) return;
setCapturing(true);
say('Taking a picture and reading it…', 'info', true);
try {
const r = await sc.capture();
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(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).
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 a = document.activeElement;
@@ -80,13 +178,23 @@ export function Scan() {
focusBox();
const onOut = () => setTimeout(focusBox, 0);
const onKey = (e: KeyboardEvent) => {
unlockAudio();
if (e.ctrlKey || e.metaKey || e.altKey) return;
const a = document.activeElement;
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();
};
document.addEventListener('focusout', onOut);
document.addEventListener('keydown', onKey);
return () => { document.removeEventListener('focusout', onOut); document.removeEventListener('keydown', onKey); };
document.addEventListener('pointerdown', unlockAudio);
return () => {
document.removeEventListener('focusout', onOut); document.removeEventListener('keydown', onKey);
document.removeEventListener('pointerdown', unlockAudio);
};
}, []);
const onSubmit = (ev: Event) => {
@@ -100,24 +208,46 @@ export function Scan() {
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 });
return (
<div class="scan">
<section class="left">
<div class={'video-wrap' + (flash ? ' flash' : '')}>
<video ref={video} playsInline muted class="mirror" />
{!running ? <div class="video-empty">Camera is off</div> : null}
<div class={'video-wrap' + (flash ? ' flash' : '')} style={{ aspectRatio: aspect }}>
<video ref={video} playsInline muted onLoadedMetadata={e => {
const v = e.currentTarget; if (v.videoWidth) setAspect(`${v.videoWidth} / ${v.videoHeight}`);
}} />
{cam === 'on' ? (
<>
<div class="target" aria-hidden="true" style={{ left: `${TARGET.x * 100}%`, top: `${TARGET.y * 100}%`, width: `${TARGET.w * 100}%`, height: `${TARGET.h * 100}%` }} />
<div class="hint" aria-hidden="true">Hold the barcode inside the box</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>
<div class="row wrap">
<button class="primary" onClick={running ? stopCamera : startCamera}>{running ? 'Stop camera' : 'Start camera'}</button>
<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);
try { localStorage.setItem('camera', v); } catch { /* ignore */ }
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}>
@@ -126,54 +256,66 @@ export function Scan() {
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>
{entries.length === 0 ? <p class="muted">Scanned books appear here.</p> : null}
{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">
{entries.map(e => <EntryRow key={e.key} entry={e} />)}
{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={b => addEntry({ bookId: b.id })} />
<LccnForm onAdded={b => addEntry({ bookId: b.id })} />
<ManualForm onAdded={b => addEntry({ bookId: b.id })} />
<SearchForm onAdded={addBook} />
<LccnForm onAdded={addBook} />
<ManualForm onAdded={addBook} />
</section>
</div>
);
}
function EntryRow({ entry }: { entry: Entry }) {
function BookRow({ book, earlier, touched, editing, onEdit }: { book: Book; earlier: boolean; touched: number; editing: boolean; onEdit: () => void }) {
const [queuing, setQueuing] = useState(false);
if (entry.bookId === undefined) return <li class="item error-item"><span class="error">{entry.note}</span></li>;
const book = getBook(entry.bookId);
if (!book) return <li class="item"><span class="muted">Removed</span></li>;
let chip;
if (entry.duplicate) chip = <span class="chip dup">Already in catalog</span>;
else if (book.status === 'pending') chip = <span class="chip pending">Looking up</span>;
else if (book.status === 'resolved') chip = <span class="chip ok">Ready</span>;
else chip = <span class="chip warn">Needs attention</span>;
const s = rowState(book);
return (
<li class="item">
<div class="item-main">
<strong class="title">{book.title}</strong>
{book.authors.length ? <span class="muted"> {book.authors.join(', ')}</span> : null}
<CallNo value={book.callNumber} approximate={book.confidence === 'approximate'} />
<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="item-side">
{chip}
{!entry.duplicate && book.status === 'needs_attention' && book.attentionReason ? <small class="muted">{book.attentionReason}</small> : null}
{entry.duplicate ? (book.inQueue
? <small class="muted">In the print queue</small>
: <button disabled={queuing} onClick={async () => {
setQueuing(true);
try { upsertBook(await api.queueBook(book.id)); } catch { /* shown via chip staying */ }
setQueuing(false);
}}>Queue reprint</button>) : null}
<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>
);
}
@@ -236,10 +378,12 @@ function ManualForm({ onAdded }: { onAdded: (b: Book) => void }) {
<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),
...(year.trim() ? { year: Number(year) } : {}), ...(cn.trim() ? { callNumber: cn.trim() } : {}),
...(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); }