Add resolver, server, PDF rendering and web app

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-18 09:46:46 -07:00
1 parent 6a7fcdc4b8
commit bdfdf581f3
59 files changed
+4088

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
import type { Book, SearchResult, Settings } from '../shared/types.ts';
export class ApiError extends Error {}
async function request<T>(method: string, url: string, body?: unknown): Promise<T> {
let res: Response;
try {
res = await fetch(url, {
method,
headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch {
throw new ApiError('Cannot reach the Booksorter server');
}
if (!res.ok) {
let msg = `Request failed (${res.status})`;
try { const j = await res.json(); if (j && typeof j.error === 'string') msg = j.error; } catch { /* keep default */ }
throw new ApiError(msg);
}
if (res.status === 204) return undefined as T;
const text = await res.text();
return (text ? JSON.parse(text) : undefined) as T;
}
/** Some creation routes may answer with the Book itself or with {book}; accept both. */
function toBook(r: unknown): Book {
const o = r as { book?: Book };
return (o && typeof o === 'object' && 'book' in o && o.book ? o.book : r) as Book;
}
export interface ManualInput { title: string; authors: string[]; year?: number; publisher?: string; callNumber?: string }
export interface BookPatch { title?: string; authors?: string[]; publisher?: string | null; year?: number | null; callNumber?: string }
export const api = {
scan: (isbn: string) => request<{ book: Book; duplicate: boolean }>('POST', '/api/scan', { isbn }),
addLccn: async (lccn: string) => toBook(await request('POST', '/api/books/lccn', { lccn })),
search: (title: string, author: string) =>
request<SearchResult[]>('GET', `/api/search?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`),
fromSearch: async (result: SearchResult) => toBook(await request('POST', '/api/books/from-search', { result })),
addManual: async (input: ManualInput) => toBook(await request('POST', '/api/books/manual', input)),
listBooks: (filter: 'all' | 'queue' | 'attention' = 'all', q = '') =>
request<Book[]>('GET', `/api/books?filter=${filter}&q=${encodeURIComponent(q)}`),
patchBook: async (id: number, patch: BookPatch) => toBook(await request('PATCH', `/api/books/${id}`, patch)),
deleteBook: (id: number) => request<void>('DELETE', `/api/books/${id}`),
queueBook: async (id: number) => toBook(await request('POST', `/api/books/${id}/queue`)),
retryBook: async (id: number) => toBook(await request('POST', `/api/books/${id}/retry`)),
confirmPrint: (ids: number[]) => request<unknown>('POST', '/api/print/confirm', { ids }),
getSettings: () => request<Settings>('GET', '/api/settings'),
putSettings: (s: Settings) => request<Settings>('PUT', '/api/settings', s),
/** Fetch the PDF as a blob so the X-Book-Ids header can be read. */
async fetchPdf(start: number): Promise<{ blob: Blob; ids: number[] }> {
let res: Response;
try { res = await fetch(`/api/print.pdf?start=${start}`); }
catch { throw new ApiError('Cannot reach the Booksorter server'); }
if (!res.ok) {
let msg = `Request failed (${res.status})`;
try { const j = await res.json(); if (j && typeof j.error === 'string') msg = j.error; } catch { /* default */ }
throw new ApiError(msg);
}
const ids = (res.headers.get('X-Book-Ids') ?? '').split(',').map(s => Number(s.trim())).filter(n => Number.isInteger(n) && n > 0);
return { blob: await res.blob(), ids };
},
};
+61
View File
@@ -0,0 +1,61 @@
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>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { cardLines, parseCallNumber } from '../../shared/callnumber.ts';
export function CallNo({ value, approximate }: { value: string | null; approximate?: boolean }) {
if (!value) return <span class="callno muted">No call number</span>;
const cn = parseCallNumber(value);
const lines = cn ? cardLines(cn) : [value, ''];
return (
<span class="callno">
<span class="callno-line">{lines[0]}{approximate ? <span class="approx" title="Approximate number"> ~</span> : null}</span>
<span class="callno-line">{lines[1] || ' '}</span>
</span>
);
}
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Booksorter</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div id="app"></div>
<script type="module" src="/app.js"></script>
</body>
</html>
+42
View File
@@ -0,0 +1,42 @@
import { useEffect, useState } from 'preact/hooks';
import type { Book } from '../shared/types.ts';
import { api } from './api.ts';
import { emptyState, reduce, shelfOrder } from './store.ts';
import type { BookAction, BookState } from './store.ts';
let state: BookState = emptyState;
const listeners = new Set<() => void>();
export function dispatch(action: BookAction): void {
state = reduce(state, action);
listeners.forEach(l => l());
}
export const upsertBook = (book: Book) => dispatch({ type: 'upsert', book });
export function useBooks(): Book[] {
const [, force] = useState(0);
useEffect(() => {
const l = () => force(n => n + 1);
listeners.add(l);
return () => { listeners.delete(l); };
}, []);
return shelfOrder(state);
}
export function getBook(id: number): Book | undefined { return state.byId[id]; }
async function refetch(): Promise<void> {
try { dispatch({ type: 'replace', books: await api.listBooks('all') }); } catch { /* retried on next open */ }
}
/** One EventSource for the whole app. Every (re)connect refetches the full list. */
export function startLive(): void {
const es = new EventSource('/api/events');
es.onopen = () => { void refetch(); };
es.addEventListener('book', e => {
try { upsertBook(JSON.parse((e as MessageEvent).data) as Book); } catch { /* ignore */ }
});
es.addEventListener('deleted', e => {
try { dispatch({ type: 'delete', id: (JSON.parse((e as MessageEvent).data) as { id: number }).id }); } catch { /* ignore */ }
});
}
+33
View File
@@ -0,0 +1,33 @@
import { render } from 'preact';
import { useState } from 'preact/hooks';
import { startLive, useBooks } from './live.ts';
import { Scan } from './views/Scan.tsx';
import { Queue } from './views/Queue.tsx';
import { Catalog } from './views/Catalog.tsx';
type Tab = 'scan' | 'queue' | 'catalog';
function App() {
const [tab, setTab] = useState<Tab>('scan');
const books = useBooks();
const ready = books.filter(b => b.inQueue && b.status === 'resolved' && b.callNumber).length;
const tabs: [Tab, string][] = [['scan', 'Scan'], ['queue', ready ? `Print queue (${ready})` : 'Print queue'], ['catalog', 'Catalog']];
return (
<>
<header>
<h1>Booksorter</h1>
<nav role="tablist">
{tabs.map(([id, label]) => (
<button role="tab" aria-selected={tab === id} class={tab === id ? 'on' : ''} onClick={() => setTab(id)}>{label}</button>
))}
</nav>
</header>
<main>
{tab === 'scan' ? <Scan /> : tab === 'queue' ? <Queue /> : <Catalog />}
</main>
</>
);
}
startLive();
render(<App />, document.getElementById('app')!);
+52
View File
@@ -0,0 +1,52 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { acceptRead, endRound, newReadState } from './readstate.ts';
const ISBN = '9780306406157';
test('single read emits nothing, second consecutive read emits', () => {
let r = acceptRead(newReadState(), ISBN, 0);
assert.equal(r.emit, null);
r = acceptRead(endRound(r.state, [ISBN]), ISBN, 150);
assert.equal(r.emit, ISBN);
assert.equal(r.reject, false);
});
test('a gap between reads resets the streak', () => {
let r = acceptRead(newReadState(), ISBN, 0);
const s = endRound(r.state, []);
r = acceptRead(s, ISBN, 150);
assert.equal(r.emit, null);
});
test('third read does not emit again; emits again after 5 s', () => {
let s = newReadState();
let t = 0;
const read = () => { const r = acceptRead(s, ISBN, t); s = endRound(r.state, [ISBN]); t += 150; return r; };
read();
assert.equal(read().emit, ISBN);
assert.equal(read().emit, null);
t = 5200;
assert.equal(read().emit, ISBN);
});
test('a UPC rejects once per 5 s', () => {
const upc = '036000291452';
let s = newReadState();
let t = 0;
const read = () => { const r = acceptRead(s, upc, t); s = endRound(r.state, [upc]); t += 150; return r; };
assert.equal(read().reject, false);
const second = read();
assert.equal(second.reject, true);
assert.equal(second.emit, null);
assert.equal(read().reject, false);
t = 6000;
assert.equal(read().reject, true);
});
test('bad check digit rejects', () => {
let s = newReadState();
let r = acceptRead(s, '9780306406158', 0); s = endRound(r.state, ['9780306406158']);
r = acceptRead(s, '9780306406158', 150);
assert.equal(r.reject, true);
});
+39
View File
@@ -0,0 +1,39 @@
import { normalizeIsbn } from '../shared/isbn.ts';
export const REPEAT_MS = 5000;
export interface ReadState {
streak: Record<string, number>;
emittedAt: Record<string, number>;
rejectedAt: Record<string, number>;
}
export function newReadState(): ReadState {
return { streak: {}, emittedAt: {}, rejectedAt: {} };
}
/** Call once per detected code in a detection round. */
export function acceptRead(
state: ReadState, code: string, now: number,
): { state: ReadState; emit: string | null; reject: boolean } {
const streak = { ...state.streak, [code]: (state.streak[code] ?? 0) + 1 };
const next: ReadState = { ...state, streak };
if (streak[code] < 2) return { state: next, emit: null, reject: false };
const isbn = normalizeIsbn(code);
if (isbn === null) {
const last = state.rejectedAt[code];
if (last !== undefined && now - last < REPEAT_MS) return { state: next, emit: null, reject: false };
return { state: { ...next, rejectedAt: { ...state.rejectedAt, [code]: now } }, emit: null, reject: true };
}
const last = state.emittedAt[isbn];
if (last !== undefined && now - last < REPEAT_MS) return { state: next, emit: null, reject: false };
return { state: { ...next, emittedAt: { ...state.emittedAt, [isbn]: now } }, emit: isbn, reject: false };
}
/** Call at the end of every detection round with the codes seen in it; codes not seen lose their streak. */
export function endRound(state: ReadState, seen: string[]): ReadState {
const streak: Record<string, number> = {};
for (const c of seen) if (state.streak[c] !== undefined) streak[c] = state.streak[c];
return { ...state, streak };
}
+85
View File
@@ -0,0 +1,85 @@
import { BarcodeDetector, prepareZXingModule } from 'barcode-detector/ponyfill';
import { acceptRead, endRound, newReadState } from './readstate.ts';
export { acceptRead } from './readstate.ts';
export type { ReadState } from './readstate.ts';
/** The reader wasm is served by our own server (copied there by scripts/build-web.ts), never a CDN. */
export const WASM_PATH = '/zxing_reader.wasm';
let prepared = false;
function prepare(): void {
if (prepared) return;
prepared = true;
prepareZXingModule({
overrides: {
locateFile: (path: string, prefix: string) =>
path.endsWith('.wasm') ? WASM_PATH : prefix + path,
},
fireImmediately: true,
});
}
const INTERVAL_MS = 150;
export async function startScanner(
video: HTMLVideoElement,
deviceId: string | undefined,
onIsbn: (isbn13: string) => void,
onReject: (code: string) => void,
): Promise<() => void> {
prepare();
const stream = await navigator.mediaDevices.getUserMedia({
video: {
...(deviceId ? { deviceId: { exact: deviceId } } : { facingMode: 'environment' }),
width: { ideal: 1920 }, height: { ideal: 1080 },
},
audio: false,
});
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const stop = () => {
stopped = true;
if (timer !== undefined) clearTimeout(timer);
stream.getTracks().forEach(t => t.stop());
if (video.srcObject === stream) video.srcObject = null;
};
try {
video.srcObject = stream;
video.muted = true;
await video.play();
} catch (e) {
stop();
throw e;
}
const detector = new BarcodeDetector({ formats: ['ean_13'] });
let state = newReadState();
// Sequential loop: the next round is scheduled only after the previous detection finished,
// so two detections never overlap.
const tick = async () => {
if (stopped) return;
const began = performance.now();
if (video.readyState >= 2 && video.videoWidth > 0) {
try {
const found = await detector.detect(video);
if (stopped) return;
const codes = found.filter(f => f.format === 'ean_13').map(f => f.rawValue);
const now = Date.now();
for (const code of codes) {
const r = acceptRead(state, code, now);
state = r.state;
if (r.emit) onIsbn(r.emit);
else if (r.reject) onReject(code);
}
state = endRound(state, codes);
} catch { /* a failed frame is skipped */ }
}
if (stopped) return;
timer = setTimeout(tick, Math.max(0, INTERVAL_MS - (performance.now() - began)));
};
timer = setTimeout(tick, INTERVAL_MS);
return stop;
}
+15
View File
@@ -0,0 +1,15 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { sheetCount } from './sheets.ts';
test('sheet counts', () => {
assert.equal(sheetCount(0, 1), 0);
assert.equal(sheetCount(1, 1), 1);
assert.equal(sheetCount(3, 1), 1);
assert.equal(sheetCount(4, 1), 2);
assert.equal(sheetCount(3, 3), 2);
assert.equal(sheetCount(1, 3), 1);
assert.equal(sheetCount(2, 3), 2);
assert.equal(sheetCount(2, 2), 1);
assert.equal(sheetCount(3, 2), 2);
});
+5
View File
@@ -0,0 +1,5 @@
/** Number of sheets needed for `count` cards when the first card goes in slot `start` (1 to 3). */
export function sheetCount(count: number, start: number): number {
if (count <= 0) return 0;
return Math.ceil((count + (start - 1)) / 3);
}
+26
View File
@@ -0,0 +1,26 @@
let ctx: AudioContext | null = null;
/** Create or resume the audio context. Call from a user gesture (the Start camera click). */
export function unlockAudio(): void {
try {
ctx ??= new AudioContext();
if (ctx.state === 'suspended') void ctx.resume();
} catch { /* audio unavailable; stay silent */ }
}
function tone(freq: number, ms: number): void {
if (!ctx) return;
try {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.frequency.value = freq;
gain.gain.setValueAtTime(0.2, ctx.currentTime);
gain.gain.setValueAtTime(0.0001, ctx.currentTime + ms / 1000);
osc.connect(gain).connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + ms / 1000);
} catch { /* ignore */ }
}
export const beepAccept = () => tone(880, 120);
export const beepLow = () => tone(220, 200);
+40
View File
@@ -0,0 +1,40 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { emptyState, reduce, shelfOrder } from './store.ts';
import type { Book } from '../shared/types.ts';
function book(id: number, title: string, sortKey: string | null): Book {
return {
id, isbn13: null, lccn: null, title, subtitle: null, authors: [], publisher: null, year: null,
subjects: [], callNumber: null, sortKey, confidence: null, source: null, dewey: null,
status: 'resolved', attentionReason: null, manualOverride: false, inQueue: true,
printedAt: null, createdAt: '', updatedAt: '',
};
}
test('upsert adds then replaces', () => {
let s = reduce(emptyState, { type: 'upsert', book: book(1, 'A', 'x') });
s = reduce(s, { type: 'upsert', book: book(1, 'A2', 'x') });
assert.equal(shelfOrder(s).length, 1);
assert.equal(shelfOrder(s)[0].title, 'A2');
});
test('delete removes', () => {
let s = reduce(emptyState, { type: 'upsert', book: book(1, 'A', 'x') });
s = reduce(s, { type: 'delete', id: 1 });
assert.equal(shelfOrder(s).length, 0);
assert.equal(shelfOrder(reduce(s, { type: 'delete', id: 99 })).length, 0);
});
test('replace swaps the whole set', () => {
let s = reduce(emptyState, { type: 'upsert', book: book(1, 'A', 'x') });
s = reduce(s, { type: 'replace', books: [book(2, 'B', 'y')] });
assert.deepEqual(shelfOrder(s).map(b => b.id), [2]);
});
test('shelf order: sort key, unparseable last, then title', () => {
let s = emptyState;
for (const b of [book(1, 'Zed', null), book(2, 'Beta', 'QA0002'), book(3, 'Alpha', null), book(4, 'Gamma', 'QA0001'), book(5, 'Delta', 'QA0002')])
s = reduce(s, { type: 'upsert', book: b });
assert.deepEqual(shelfOrder(s).map(b => b.id), [4, 2, 5, 3, 1]);
});
+40
View File
@@ -0,0 +1,40 @@
import type { Book } from '../shared/types.ts';
export interface BookState { byId: Record<number, Book> }
export type BookAction =
| { type: 'upsert'; book: Book }
| { type: 'delete'; id: number }
| { type: 'replace'; books: Book[] };
export const emptyState: BookState = { byId: {} };
export function reduce(state: BookState, action: BookAction): BookState {
switch (action.type) {
case 'upsert':
return { byId: { ...state.byId, [action.book.id]: action.book } };
case 'delete': {
const byId = { ...state.byId };
delete byId[action.id];
return { byId };
}
case 'replace': {
const byId: Record<number, Book> = {};
for (const b of action.books) byId[b.id] = b;
return { byId };
}
}
}
/** Shelf order: by sortKey, books without one last, then title. */
export function compareShelf(a: Book, b: Book): number {
if (a.sortKey !== b.sortKey) {
if (a.sortKey === null) return 1;
if (b.sortKey === null) return -1;
return a.sortKey < b.sortKey ? -1 : 1;
}
return a.title.localeCompare(b.title);
}
export function shelfOrder(state: BookState): Book[] {
return Object.values(state.byId).sort(compareShelf);
}
+77
View File
@@ -0,0 +1,77 @@
:root {
color-scheme: light dark;
--bg: #f7f6f3; --panel: #fff; --text: #1d1d1b; --muted: #6a6a64; --line: #dcdad3;
--accent: #1f5fbf; --accent-text: #fff; --ok: #1d7a46; --warn: #a15c00; --bad: #b3261e; --flash: #2fa35d;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #16171a; --panel: #1f2125; --text: #ecebe6; --muted: #9a9a94; --line: #33363b;
--accent: #6ea3f2; --accent-text: #0b1b33; --ok: #52c586; --warn: #e0a24a; --bad: #f08a82; --flash: #52c586; }
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
header { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 24px; padding: 14px 20px; border-bottom: 1px solid var(--line); background: var(--panel); }
h1 { font-size: 1.15rem; margin: 0; }
h2 { font-size: 1.05rem; margin: 0 0 8px; }
nav { display: flex; gap: 6px; flex-wrap: wrap; }
nav button { border: 0; background: none; padding: 6px 12px; border-radius: 8px; color: var(--muted); }
nav button.on { background: var(--bg); color: var(--text); font-weight: 600; }
main { max-width: 1100px; margin: 0 auto; padding: 20px; }
button, .button, select, input { font: inherit; color: inherit; }
button, .button { display: inline-block; padding: 8px 14px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); cursor: pointer; text-decoration: none; }
button:hover:not(:disabled), .button:hover { border-color: var(--muted); }
button:disabled { opacity: .5; cursor: default; }
button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
button.danger { color: var(--bad); }
button.quiet { border-color: transparent; background: none; color: var(--muted); }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
input, select { padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); width: 100%; }
input[type=checkbox] { width: auto; }
label { display: block; font-size: .9rem; color: var(--muted); }
label > input, label > select { margin-top: 4px; color: var(--text); }
label small { display: block; margin-top: 4px; }
.row { display: flex; gap: 10px; align-items: flex-end; margin: 10px 0; }
.row.wrap { flex-wrap: wrap; align-items: center; }
.grow { flex: 1 1 200px; } .year { width: 110px; }
.stack { display: grid; gap: 10px; margin: 10px 0; }
.muted { color: var(--muted); } .mono { font-family: ui-monospace, "SF Mono", Menlo, monospace; }
.error { color: var(--bad); } .warn, .warn-text { color: var(--warn); }
.check { display: flex; gap: 6px; align-items: center; }
.scan { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 24px; }
.scan .forms { grid-column: 1 / -1; }
@media (max-width: 760px) { .scan { grid-template-columns: 1fr; } main { padding: 14px 12px; } }
.video-wrap { position: relative; aspect-ratio: 16 / 9; background: #000; border-radius: 12px; overflow: hidden; border: 3px solid transparent; }
.video-wrap.flash { border-color: var(--flash); }
video { width: 100%; height: 100%; object-fit: cover; display: block; }
video.mirror { transform: scaleX(-1); }
.video-empty { position: absolute; inset: 0; display: grid; place-items: center; color: #aaa; }
.isbn-form input { font-size: 1.1rem; }
.list { list-style: none; margin: 0; padding: 0; }
.item { display: flex; gap: 14px; justify-content: space-between; align-items: flex-start; padding: 12px 0; border-bottom: 1px solid var(--line); }
.item.column { flex-direction: column; align-items: stretch; gap: 8px; }
.item-btn { display: flex; gap: 14px; align-items: flex-start; width: 100%; text-align: left; border: 0; padding: 0; background: none; }
.item-main { display: flex; flex-direction: column; min-width: 0; flex: 1; }
.item-side { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; }
.title { overflow-wrap: anywhere; }
.callno { display: inline-flex; flex-direction: column; font-family: ui-monospace, "SF Mono", Menlo, monospace; font-variant-numeric: tabular-nums; white-space: pre; min-width: 9.5em; font-size: .92rem; line-height: 1.35; }
.item-main .callno { margin-top: 4px; }
.approx { color: var(--warn); }
.chip { display: inline-block; padding: 2px 10px; border-radius: 999px; font-size: .8rem; border: 1px solid var(--line); white-space: nowrap; }
.chip.ok { color: var(--ok); border-color: var(--ok); } .chip.warn { color: var(--warn); border-color: var(--warn); }
.chip.dup { color: var(--accent); border-color: var(--accent); } .chip.pending { color: var(--muted); }
.error-item { color: var(--bad); }
details { border: 1px solid var(--line); border-radius: 10px; background: var(--panel); padding: 10px 14px; margin: 8px 0; }
summary { cursor: pointer; font-weight: 600; }
.results .result { width: 100%; text-align: left; display: flex; flex-direction: column; border: 0; border-bottom: 1px solid var(--line); border-radius: 0; background: none; }
.card { border: 1px solid var(--line); border-radius: 10px; background: var(--panel); padding: 14px; margin: 10px 0; }
.editor { display: grid; gap: 10px; }
.editor .row { margin: 0; }
.queue section { margin-bottom: 28px; }
fieldset.start { border: 0; padding: 0; margin: 16px 0 8px; }
legend { color: var(--muted); font-size: .9rem; padding: 0; margin-bottom: 6px; }
.sheet { display: inline-flex; flex-direction: column; gap: 4px; padding: 8px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); }
.slot { width: 150px; height: 40px; padding: 0; border-radius: 4px; }
.slot.on { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
.slot.used { opacity: .45; }
.confirm { border-color: var(--accent); }
+42
View File
@@ -0,0 +1,42 @@
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}>
<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}
</span>
</button>
{openId === b.id ? <BookEditor book={b} onClose={() => setOpenId(null)} /> : null}
</li>
))}
</ul>
</div>
);
}
+143
View File
@@ -0,0 +1,143 @@
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 { 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 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);
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);
const url = URL.createObjectURL(new Blob([blob], { type: 'application/pdf' }));
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);
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>{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}
<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>
</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} onClick={makePdf}>{busy ? 'Making PDF' : 'Make PDF'}</button>
{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); setPending(null); }}>Not yet</button>
</div>
</div>
) : null}
</section>
<section>
<h2>Needs attention</h2>
{attention.length === 0 ? <p class="muted">Every book has a call number.</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>
);
}
+256
View File
@@ -0,0 +1,256 @@
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 { beepAccept, beepLow, unlockAudio } from '../sound.ts';
import { CallNo } from '../components/CallNo.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;
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.';
}
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 [camError, setCamError] = useState('');
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
const [deviceId, setDeviceId] = useState(() => { try { return localStorage.getItem('camera') ?? ''; } catch { return ''; } });
const [flash, setFlash] = useState(false);
const [typed, setTyped] = useState('');
const [typedError, setTypedError] = useState('');
const addEntry = (e: Omit<Entry, 'key'>) => { entries = [{ key: nextKey++, ...e }, ...entries]; refresh(); };
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 });
}
}
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 }); };
function stopCamera() {
stopRef.current?.(); stopRef.current = null; setRunning(false);
}
async function startCamera() {
unlockAudio(); // needs the user gesture
setCamError('');
stopCamera();
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'));
} catch (e) {
setCamError(cameraMessage(e));
}
isbnBox.current?.focus();
}
useEffect(() => stopCamera, []); // stop on leaving the view
// Keep the ISBN box focused unless the user is typing in another field.
useEffect(() => {
const focusBox = () => {
const a = document.activeElement;
if (!a || a === document.body) isbnBox.current?.focus();
};
focusBox();
const onOut = () => setTimeout(focusBox, 0);
const onKey = (e: KeyboardEvent) => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
const a = document.activeElement;
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); };
}, []);
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);
};
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>
<div class="row wrap">
<button class="primary" onClick={running ? stopCamera : startCamera}>{running ? 'Stop camera' : 'Start camera'}</button>
{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 */ }
}}>
<option value="">Default camera</option>
{devices.map((d, i) => <option value={d.deviceId}>{d.label || `Camera ${i + 1}`}</option>)}
</select>
) : null}
</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}
</form>
</section>
<section class="right">
<h2>This session</h2>
{entries.length === 0 ? <p class="muted">Scanned books appear here.</p> : null}
<ul class="list">
{entries.map(e => <EntryRow key={e.key} entry={e} />)}
</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 })} />
</section>
</div>
);
}
function EntryRow({ entry }: { entry: Entry }) {
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>;
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'} />
</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>
</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('');
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() } : {}),
});
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>
);
}