Add resolver, server, PDF rendering and web app
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
6a7fcdc4b8
commit
bdfdf581f3
59 files changed
+4088
No files matched your search
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user