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:
1 parent
468cafc6db
commit
b5defb4e4f
46 files changed
+1957
-406
No files matched your search
@@ -0,0 +1,60 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { elapsedText, pdfLabel, queueHeader, queueSplit, queueTabLabel, rowState, sessionSummary } from './bookstate.ts';
|
||||
|
||||
function book(id: number, over: Partial<Book>): Book {
|
||||
return {
|
||||
id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey: null, confidence: null, source: null, dewey: null,
|
||||
status: 'pending', attentionReason: null, manualOverride: false, inQueue: true,
|
||||
printedAt: null, createdAt: '', updatedAt: '', ...over,
|
||||
};
|
||||
}
|
||||
const ready = (id: number) => book(id, { status: 'resolved', callNumber: 'QA76.73 .R87 K53 2018', sortKey: 'k' + id });
|
||||
const looking = (id: number) => book(id, {});
|
||||
const attention = (id: number) => book(id, { status: 'needs_attention', attentionReason: 'No match' });
|
||||
|
||||
test('a pending book is "looking", never "no call number"', () => {
|
||||
assert.deepEqual(rowState(looking(1)), { kind: 'looking', note: null });
|
||||
assert.deepEqual(rowState(book(1, { attentionReason: 'LC did not answer. Trying again shortly.' })),
|
||||
{ kind: 'looking', note: 'LC did not answer. Trying again shortly.' });
|
||||
});
|
||||
|
||||
test('ready and attention states', () => {
|
||||
assert.deepEqual(rowState(ready(1)), { kind: 'ready' });
|
||||
assert.deepEqual(rowState(attention(1)), { kind: 'attention', reason: 'No match' });
|
||||
assert.equal(rowState(book(1, { status: 'resolved' })).kind, 'attention');
|
||||
});
|
||||
|
||||
test('session summary', () => {
|
||||
assert.equal(sessionSummary([ready(1), ready(2), ready(3), looking(4)]), '4 scanned · 3 ready · 1 looking up');
|
||||
assert.equal(sessionSummary([ready(1)]), '1 scanned · 1 ready');
|
||||
assert.equal(sessionSummary([attention(1), attention(2), looking(3)]), '3 scanned · 1 looking up · 2 need attention');
|
||||
assert.equal(sessionSummary([]), '0 scanned');
|
||||
});
|
||||
|
||||
test('queue split ignores books that are not queued or need attention', () => {
|
||||
const printed = { ...ready(9), inQueue: false };
|
||||
const q = queueSplit([ready(1), looking(2), attention(3), printed, ready(4)]);
|
||||
assert.deepEqual(q.ready.map(b => b.id), [1, 4]);
|
||||
assert.deepEqual(q.looking.map(b => b.id), [2]);
|
||||
});
|
||||
|
||||
test('queue labels', () => {
|
||||
assert.equal(queueHeader(3, 1), '3 cards ready · 1 still looking up');
|
||||
assert.equal(queueHeader(1, 0), '1 card ready');
|
||||
assert.equal(queueHeader(0, 1), '0 cards ready · 1 still looking up');
|
||||
assert.equal(pdfLabel(3), 'Make PDF (3 cards)');
|
||||
assert.equal(pdfLabel(1), 'Make PDF (1 card)');
|
||||
assert.equal(pdfLabel(0), 'Make PDF');
|
||||
assert.equal(queueTabLabel(3, 1), 'Print queue (4)');
|
||||
assert.equal(queueTabLabel(0, 0), 'Print queue');
|
||||
});
|
||||
|
||||
test('elapsed text', () => {
|
||||
assert.equal(elapsedText(0), '0 s');
|
||||
assert.equal(elapsedText(59_900), '59 s');
|
||||
assert.equal(elapsedText(65_000), '1 min 05 s');
|
||||
assert.equal(elapsedText(-5), '0 s');
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { Book } from '../shared/types.ts';
|
||||
|
||||
/** The single state a book is shown in. */
|
||||
export type RowState =
|
||||
| { kind: 'looking'; note: string | null }
|
||||
| { kind: 'ready' }
|
||||
| { kind: 'attention'; reason: string };
|
||||
|
||||
export function rowState(book: Book): RowState {
|
||||
if (book.status === 'pending') return { kind: 'looking', note: book.attentionReason };
|
||||
if (book.status === 'resolved' && book.callNumber) return { kind: 'ready' };
|
||||
if (book.status === 'resolved') return { kind: 'attention', reason: 'No call number was found.' };
|
||||
return { kind: 'attention', reason: book.attentionReason ?? 'This book needs a look.' };
|
||||
}
|
||||
|
||||
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
|
||||
|
||||
export function sessionSummary(books: Book[]): string {
|
||||
let ready = 0, looking = 0, attention = 0;
|
||||
for (const b of books) {
|
||||
const s = rowState(b).kind;
|
||||
if (s === 'ready') ready++; else if (s === 'looking') looking++; else attention++;
|
||||
}
|
||||
const parts = [`${books.length} scanned`];
|
||||
if (ready) parts.push(`${ready} ready`);
|
||||
if (looking) parts.push(`${looking} looking up`);
|
||||
if (attention) parts.push(`${attention} ${attention === 1 ? 'needs' : 'need'} attention`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
export interface QueueSplit { ready: Book[]; looking: Book[] }
|
||||
|
||||
/** Queued books, split into the ones that can be printed now and the ones still being looked up. */
|
||||
export function queueSplit(books: Book[]): QueueSplit {
|
||||
const ready: Book[] = [], looking: Book[] = [];
|
||||
for (const b of books) {
|
||||
if (!b.inQueue) continue;
|
||||
const s = rowState(b).kind;
|
||||
if (s === 'ready') ready.push(b); else if (s === 'looking') looking.push(b);
|
||||
}
|
||||
return { ready, looking };
|
||||
}
|
||||
|
||||
export function queueHeader(ready: number, looking: number): string {
|
||||
const head = plural(ready, 'card', 'cards') + ' ready';
|
||||
return looking ? `${head} · ${looking} still looking up` : head;
|
||||
}
|
||||
|
||||
export function pdfLabel(ready: number): string {
|
||||
return ready ? `Make PDF (${plural(ready, 'card', 'cards')})` : 'Make PDF';
|
||||
}
|
||||
|
||||
export function queueTabLabel(ready: number, looking: number): string {
|
||||
const n = ready + looking;
|
||||
return n ? `Print queue (${n})` : 'Print queue';
|
||||
}
|
||||
|
||||
/** "12 s", "1 min 05 s" */
|
||||
export function elapsedText(ms: number): string {
|
||||
const s = Math.max(0, Math.floor(ms / 1000));
|
||||
return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${String(s % 60).padStart(2, '0')} s`;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { useState } from 'preact/hooks';
|
||||
import type { Book } from '../../shared/types.ts';
|
||||
import { api } from '../api.ts';
|
||||
import { upsertBook, dispatch } from '../live.ts';
|
||||
import { parseYear } from '../year.ts';
|
||||
|
||||
export function BookEditor({ book, onClose }: { book: Book; onClose: () => void }) {
|
||||
const [title, setTitle] = useState(book.title);
|
||||
@@ -10,6 +11,7 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void
|
||||
const [year, setYear] = useState(book.year?.toString() ?? '');
|
||||
const [callNumber, setCallNumber] = useState(book.callNumber ?? '');
|
||||
const [msg, setMsg] = useState('');
|
||||
const [yearError, setYearError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function run(fn: () => Promise<void>) {
|
||||
@@ -18,17 +20,23 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
const save = (ev: Event) => { ev.preventDefault(); void run(async () => {
|
||||
const save = (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
const y = parseYear(year);
|
||||
if (!y.ok) { setYearError('Enter the year as digits, for example 2018, or leave it empty.'); return; }
|
||||
setYearError('');
|
||||
void run(async () => {
|
||||
const 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,
|
||||
year: y.value,
|
||||
};
|
||||
if (callNumber.trim() !== (book.callNumber ?? '')) patch.callNumber = callNumber.trim();
|
||||
upsertBook(await api.patchBook(book.id, patch));
|
||||
onClose();
|
||||
}); };
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form class="card editor" onSubmit={save}>
|
||||
@@ -36,8 +44,9 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void
|
||||
<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>
|
||||
<label class="year">Year<input inputMode="numeric" value={year} aria-invalid={yearError ? 'true' : undefined} onInput={e => { setYear(e.currentTarget.value); setYearError(''); }} /></label>
|
||||
</div>
|
||||
{yearError ? <p class="error" role="alert">{yearError}</p> : null}
|
||||
<label>Call number
|
||||
<input class="mono" value={callNumber} onInput={e => setCallNumber(e.currentTarget.value)} />
|
||||
<small>Changing this locks the number</small>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { Book } from '../../shared/types.ts';
|
||||
import { elapsedText, rowState } from '../bookstate.ts';
|
||||
import { lookupStartedAt, useNow } from '../live.ts';
|
||||
|
||||
const CheckIcon = () => (
|
||||
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3.2 3.2L13 4.8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /></svg>
|
||||
);
|
||||
const AlertIcon = () => (
|
||||
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 2.2L14.6 13.5H1.4L8 2.2z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" /><path d="M8 6.6v3.2M8 11.6v.1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
|
||||
);
|
||||
|
||||
function Looking({ book }: { book: Book }) {
|
||||
const now = useNow(true);
|
||||
return <span class="state-label"><span class="spinner" aria-hidden="true" />Looking up… <span class="elapsed">{elapsedText(now - lookupStartedAt(book))}</span></span>;
|
||||
}
|
||||
|
||||
/** The one label a book shows: Looking up… (spinner, seconds), Ready, or Needs attention. */
|
||||
export function StateLabel({ book }: { book: Book }) {
|
||||
const s = rowState(book);
|
||||
if (s.kind === 'looking') return <Looking book={book} />;
|
||||
if (s.kind === 'ready') return <span class="state-label"><CheckIcon />Ready</span>;
|
||||
return <span class="state-label"><AlertIcon />Needs attention</span>;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ export function CallNo({ value, approximate }: { value: string | null; approxima
|
||||
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 class="callno-line">{lines[1] || ' '}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { cropRect, upscaleFor } from './frame.ts';
|
||||
|
||||
test('the crop is the target box inside the frame', () => {
|
||||
const r = cropRect(1920, 1080);
|
||||
assert.deepEqual(r, { x: 192, y: 292, w: 1536, h: 497 });
|
||||
assert.ok(r.x + r.w <= 1920 && r.y + r.h <= 1080);
|
||||
});
|
||||
|
||||
test('small crops are enlarged 2x, large ones are not', () => {
|
||||
assert.equal(upscaleFor(512), 2);
|
||||
assert.equal(upscaleFor(999), 2);
|
||||
assert.equal(upscaleFor(1000), 1);
|
||||
assert.equal(upscaleFor(1536), 1);
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Where the barcode is expected, as fractions of the video frame. The overlay box is drawn from the same numbers. */
|
||||
export const TARGET = { x: 0.1, y: 0.27, w: 0.8, h: 0.46 };
|
||||
|
||||
export interface Rect { x: number; y: number; w: number; h: number }
|
||||
|
||||
/** The target box in pixels of a frame of the given size. */
|
||||
export function cropRect(width: number, height: number): Rect {
|
||||
const x = Math.round(width * TARGET.x), y = Math.round(height * TARGET.y);
|
||||
return { x, y, w: Math.min(width - x, Math.round(width * TARGET.w)), h: Math.min(height - y, Math.round(height * TARGET.h)) };
|
||||
}
|
||||
|
||||
/** A small crop is enlarged so that thin bars cover enough pixels for the decoder: 2x below 1000 px wide. */
|
||||
export function upscaleFor(cropWidth: number): number {
|
||||
return cropWidth < 1000 ? 2 : 1;
|
||||
}
|
||||
@@ -7,7 +7,35 @@ import type { BookAction, BookState } from './store.ts';
|
||||
let state: BookState = emptyState;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
/** When each book was first seen waiting for its lookup, for the elapsed-seconds display. */
|
||||
const pendingSince = new Map<number, number>();
|
||||
function trackPending(action: BookAction): void {
|
||||
const note = (b: Book, fromServerTime: boolean) => {
|
||||
if (b.status !== 'pending') { pendingSince.delete(b.id); return; }
|
||||
if (pendingSince.has(b.id)) return;
|
||||
const created = Date.parse(b.createdAt);
|
||||
pendingSince.set(b.id, fromServerTime && Number.isFinite(created) ? Math.min(created, Date.now()) : Date.now());
|
||||
};
|
||||
if (action.type === 'upsert') note(action.book, false);
|
||||
else if (action.type === 'replace') { pendingSince.clear(); action.books.forEach(b => note(b, true)); }
|
||||
else pendingSince.delete(action.id);
|
||||
}
|
||||
export function lookupStartedAt(book: Book): number { return pendingSince.get(book.id) ?? Date.now(); }
|
||||
|
||||
/** Re-renders once a second while `active`, and returns the current time. */
|
||||
export function useNow(active: boolean): number {
|
||||
const [now, setNow] = useState(Date.now());
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
setNow(Date.now());
|
||||
const t = setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => clearInterval(t);
|
||||
}, [active]);
|
||||
return now;
|
||||
}
|
||||
|
||||
export function dispatch(action: BookAction): void {
|
||||
trackPending(action);
|
||||
state = reduce(state, action);
|
||||
listeners.forEach(l => l());
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
import { render } from 'preact';
|
||||
import { useState } from 'preact/hooks';
|
||||
import { startLive, useBooks } from './live.ts';
|
||||
import { queueSplit, queueTabLabel } from './bookstate.ts';
|
||||
import { Scan } from './views/Scan.tsx';
|
||||
import { Queue } from './views/Queue.tsx';
|
||||
import { Catalog } from './views/Catalog.tsx';
|
||||
@@ -10,8 +11,8 @@ 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']];
|
||||
const { ready, looking } = queueSplit(books);
|
||||
const tabs: [Tab, string][] = [['scan', 'Scan'], ['queue', queueTabLabel(ready.length, looking.length)], ['catalog', 'Catalog']];
|
||||
return (
|
||||
<>
|
||||
<header>
|
||||
|
||||
+30
-34
@@ -1,52 +1,48 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { acceptRead, endRound, newReadState } from './readstate.ts';
|
||||
import { acceptRead, markEmitted, 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);
|
||||
test('a valid ISBN-13 is accepted on the first read', () => {
|
||||
const r = acceptRead(newReadState(), ISBN, 0);
|
||||
assert.equal(r.emit, ISBN);
|
||||
assert.equal(r.reject, false);
|
||||
});
|
||||
|
||||
test('a gap between reads resets the streak', () => {
|
||||
test('the same ISBN is not repeated within 5 s, then is again', () => {
|
||||
let r = acceptRead(newReadState(), ISBN, 0);
|
||||
const s = endRound(r.state, []);
|
||||
r = acceptRead(s, ISBN, 150);
|
||||
r = acceptRead(r.state, ISBN, 150);
|
||||
assert.equal(r.emit, null);
|
||||
assert.equal(r.reject, false);
|
||||
r = acceptRead(r.state, ISBN, 4900);
|
||||
assert.equal(r.emit, null);
|
||||
r = acceptRead(r.state, ISBN, 5100);
|
||||
assert.equal(r.emit, ISBN);
|
||||
});
|
||||
|
||||
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 979 ISBN is accepted', () => {
|
||||
assert.equal(acceptRead(newReadState(), '9791034305261', 0).emit, '9791034305261');
|
||||
});
|
||||
|
||||
test('a UPC rejects once per 5 s', () => {
|
||||
test('a UPC-A 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);
|
||||
let r = acceptRead(newReadState(), upc, 0);
|
||||
assert.equal(r.reject, true);
|
||||
assert.equal(r.emit, null);
|
||||
r = acceptRead(r.state, upc, 150);
|
||||
assert.equal(r.reject, false);
|
||||
r = acceptRead(r.state, upc, 6000);
|
||||
assert.equal(r.reject, true);
|
||||
});
|
||||
|
||||
test('a 13-digit code without a 978/979 prefix, or with a bad check digit, rejects', () => {
|
||||
assert.equal(acceptRead(newReadState(), '5012345678900', 0).reject, true);
|
||||
assert.equal(acceptRead(newReadState(), '9780306406158', 0).reject, true);
|
||||
});
|
||||
|
||||
test('markEmitted silences the loop for 5 s', () => {
|
||||
const s = markEmitted(newReadState(), ISBN, 1000);
|
||||
assert.equal(acceptRead(s, ISBN, 2000).emit, null);
|
||||
assert.equal(acceptRead(s, ISBN, 6100).emit, ISBN);
|
||||
});
|
||||
+15
-17
@@ -2,38 +2,36 @@ import { normalizeIsbn } from '../shared/isbn.ts';
|
||||
|
||||
export const REPEAT_MS = 5000;
|
||||
|
||||
/** Remembers when each code was last reported, so a barcode held in view is announced once per 5 seconds. */
|
||||
export interface ReadState {
|
||||
streak: Record<string, number>;
|
||||
emittedAt: Record<string, number>;
|
||||
rejectedAt: Record<string, number>;
|
||||
}
|
||||
|
||||
export function newReadState(): ReadState {
|
||||
return { streak: {}, emittedAt: {}, rejectedAt: {} };
|
||||
return { emittedAt: {}, rejectedAt: {} };
|
||||
}
|
||||
|
||||
/** Call once per detected code in a detection round. */
|
||||
/**
|
||||
* Judge one decoded barcode. A valid ISBN-13 (check digit, 978 or 979 prefix) is accepted at once, with no
|
||||
* second confirming read: the EAN checksum already makes a false read very unlikely. Anything else
|
||||
* (a UPC, a price code, a bad check digit) is rejected. Neither is repeated within REPEAT_MS.
|
||||
*/
|
||||
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);
|
||||
const isbn = /^\d{13}$/.test(code) ? normalizeIsbn(code) : null;
|
||||
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 };
|
||||
if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null, reject: false };
|
||||
return { state: { ...state, 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 };
|
||||
if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null, reject: false };
|
||||
return { state: { ...state, 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 };
|
||||
/** Record that an ISBN was just reported by some other path (the Capture button), so the loop stays quiet. */
|
||||
export function markEmitted(state: ReadState, isbn: string, now: number): ReadState {
|
||||
return { ...state, emittedAt: { ...state.emittedAt, [isbn]: now } };
|
||||
}
|
||||
+156
-29
@@ -1,5 +1,8 @@
|
||||
import { BarcodeDetector, prepareZXingModule } from 'barcode-detector/ponyfill';
|
||||
import { acceptRead, endRound, newReadState } from './readstate.ts';
|
||||
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
|
||||
import type { ReaderOptions } from 'zxing-wasm/reader';
|
||||
import { normalizeIsbn } from '../shared/isbn.ts';
|
||||
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
|
||||
import { cropRect, upscaleFor } from './frame.ts';
|
||||
|
||||
export { acceptRead } from './readstate.ts';
|
||||
export type { ReadState } from './readstate.ts';
|
||||
@@ -8,10 +11,10 @@ export type { ReadState } from './readstate.ts';
|
||||
export const WASM_PATH = '/zxing_reader.wasm';
|
||||
|
||||
let prepared = false;
|
||||
function prepare(): void {
|
||||
export function prepare(): void {
|
||||
if (prepared) return;
|
||||
prepared = true;
|
||||
prepareZXingModule({
|
||||
void prepareZXingModule({
|
||||
overrides: {
|
||||
locateFile: (path: string, prefix: string) =>
|
||||
path.endsWith('.wasm') ? WASM_PATH : prefix + path,
|
||||
@@ -20,34 +23,139 @@ function prepare(): void {
|
||||
});
|
||||
}
|
||||
|
||||
/** The one detector configuration the scanner uses; also used by scripts/browser-check.ts. */
|
||||
export function makeDetector(): BarcodeDetector {
|
||||
prepare();
|
||||
return new BarcodeDetector({ formats: ['ean_13'] });
|
||||
/**
|
||||
* Book barcodes are EAN-13 (978/979); UPC-A is read too so that a US price/UPC code can be reported as
|
||||
* "not an ISBN" instead of silently ignored. Everything else (QR, Code 128, ...) is not searched for.
|
||||
* Settings are for a fixed-focus laptop webcam: try hard, try rotated (a book held sideways), and try
|
||||
* downscaled copies (a soft image of thin bars decodes better smaller).
|
||||
*/
|
||||
const BASE: ReaderOptions = {
|
||||
formats: ['EAN13', 'UPCA'],
|
||||
tryHarder: true, tryRotate: true, tryDownscale: true, tryInvert: false,
|
||||
maxNumberOfSymbols: 2,
|
||||
};
|
||||
/** Extra passes for the Capture button: other thresholding, and light-on-dark codes. */
|
||||
const THOROUGH: ReaderOptions[] = [
|
||||
{ ...BASE, binarizer: 'LocalAverage', tryInvert: true },
|
||||
{ ...BASE, binarizer: 'GlobalHistogram', tryInvert: true },
|
||||
{ ...BASE, binarizer: 'FixedThreshold', tryInvert: true, tryDownscale: false },
|
||||
{ ...BASE, binarizer: 'LocalAverage', downscaleThreshold: 200, downscaleFactor: 2 },
|
||||
];
|
||||
|
||||
export interface DecodeOutcome { isbn: string | null; other: string | null }
|
||||
|
||||
/** Decoding runs one at a time: a new request waits for the one in progress. */
|
||||
let queue: Promise<unknown> = Promise.resolve();
|
||||
function exclusive<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const run = queue.then(fn, fn);
|
||||
queue = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
const INTERVAL_MS = 150;
|
||||
type Source = HTMLVideoElement | ImageBitmap;
|
||||
const sizeOf = (s: Source) => s instanceof HTMLVideoElement ? { w: s.videoWidth, h: s.videoHeight } : { w: s.width, h: s.height };
|
||||
|
||||
let scratch: HTMLCanvasElement | null = null;
|
||||
/** Draw a region of the source into a canvas of the given size and return its pixels. */
|
||||
function pixels(src: Source, sx: number, sy: number, sw: number, sh: number, dw: number, dh: number): ImageData {
|
||||
scratch ??= document.createElement('canvas');
|
||||
scratch.width = dw; scratch.height = dh;
|
||||
const g = scratch.getContext('2d', { willReadFrequently: true })!;
|
||||
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high';
|
||||
g.drawImage(src, sx, sy, sw, sh, 0, 0, dw, dh);
|
||||
return g.getImageData(0, 0, dw, dh);
|
||||
}
|
||||
|
||||
function judge(codes: { text: string }[], into: DecodeOutcome): void {
|
||||
for (const c of codes) {
|
||||
const isbn = /^\d{13}$/.test(c.text) ? normalizeIsbn(c.text) : null;
|
||||
if (isbn) into.isbn ??= isbn; else into.other ??= c.text;
|
||||
}
|
||||
}
|
||||
|
||||
/** The images to try, most promising first: the target box (enlarged when small), then the whole frame. */
|
||||
function views(src: Source, maxSide: number): ImageData[] {
|
||||
const { w, h } = sizeOf(src);
|
||||
const c = cropRect(w, h);
|
||||
const k = upscaleFor(c.w);
|
||||
const full = Math.min(1, maxSide / Math.max(w, h));
|
||||
return [
|
||||
pixels(src, c.x, c.y, c.w, c.h, Math.round(c.w * k), Math.round(c.h * k)),
|
||||
pixels(src, 0, 0, w, h, Math.round(w * full), Math.round(h * full)),
|
||||
];
|
||||
}
|
||||
|
||||
/** One quick pass for the live loop: the target box, then the full frame if the box held no ISBN. */
|
||||
export function decodeLive(src: Source): Promise<DecodeOutcome> {
|
||||
return exclusive(async () => {
|
||||
const out: DecodeOutcome = { isbn: null, other: null };
|
||||
for (const img of views(src, 2560)) {
|
||||
judge(await readBarcodes(img, BASE), out);
|
||||
if (out.isbn) break;
|
||||
}
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
/** The most thorough decode: every view with every setting, stopping at the first valid ISBN. */
|
||||
export function decodeThorough(src: Source): Promise<DecodeOutcome> {
|
||||
return exclusive(async () => {
|
||||
const out: DecodeOutcome = { isbn: null, other: null };
|
||||
const imgs = views(src, 3000);
|
||||
for (const opts of [BASE, ...THOROUGH]) {
|
||||
for (const img of imgs) {
|
||||
judge(await readBarcodes(img, opts), out);
|
||||
if (out.isbn) return out;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
export interface ScannerHandlers {
|
||||
/** A valid ISBN-13 was read (at most once per 5 seconds per book). */
|
||||
onIsbn(isbn13: string): void;
|
||||
/** A barcode was read that is not a book ISBN. */
|
||||
onOther(code: string): void;
|
||||
/** The camera stopped by itself (unplugged, taken by another program). */
|
||||
onEnded(): void;
|
||||
}
|
||||
|
||||
export interface Scanner {
|
||||
stop(): void;
|
||||
/** Take one still at the highest resolution available and decode it as thoroughly as possible. */
|
||||
capture(): Promise<DecodeOutcome>;
|
||||
}
|
||||
|
||||
const INTERVAL_MS = 120;
|
||||
|
||||
/**
|
||||
* Open the camera and start the sequential decode loop. If `signal` aborts while the permission prompt is
|
||||
* open, the stream is stopped the moment it arrives and null is returned.
|
||||
*/
|
||||
export async function startScanner(
|
||||
video: HTMLVideoElement,
|
||||
deviceId: string | undefined,
|
||||
onIsbn: (isbn13: string) => void,
|
||||
onReject: (code: string) => void,
|
||||
): Promise<() => void> {
|
||||
video: HTMLVideoElement, deviceId: string | undefined, handlers: ScannerHandlers, signal?: AbortSignal,
|
||||
): Promise<Scanner | null> {
|
||||
prepare();
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
video: {
|
||||
...(deviceId ? { deviceId: { exact: deviceId } } : { facingMode: 'environment' }),
|
||||
width: { ideal: 1920 }, height: { ideal: 1080 },
|
||||
...(deviceId ? { deviceId: { exact: deviceId } } : {}),
|
||||
width: { ideal: 1920 }, height: { ideal: 1080 }, frameRate: { ideal: 30 },
|
||||
// Not in every TypeScript lib; ignored by cameras without focus control.
|
||||
...({ advanced: [{ focusMode: 'continuous' }] } as object),
|
||||
},
|
||||
audio: false,
|
||||
});
|
||||
const release = () => stream.getTracks().forEach(t => t.stop());
|
||||
if (signal?.aborted) { release(); return null; }
|
||||
|
||||
let stopped = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const stop = () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
stream.getTracks().forEach(t => t.stop());
|
||||
release();
|
||||
if (video.srcObject === stream) video.srcObject = null;
|
||||
};
|
||||
|
||||
@@ -59,33 +167,52 @@ export async function startScanner(
|
||||
stop();
|
||||
throw e;
|
||||
}
|
||||
if (signal?.aborted) { stop(); return null; }
|
||||
stream.getVideoTracks()[0]?.addEventListener('ended', () => { if (!stopped) { stop(); handlers.onEnded(); } });
|
||||
|
||||
const detector = makeDetector();
|
||||
let state = newReadState();
|
||||
|
||||
// Sequential loop: the next round is scheduled only after the previous detection finished,
|
||||
// so two detections never overlap.
|
||||
// Sequential: the next round is scheduled only after the previous detection finished.
|
||||
const tick = async () => {
|
||||
if (stopped) return;
|
||||
const began = performance.now();
|
||||
if (video.readyState >= 2 && video.videoWidth > 0) {
|
||||
try {
|
||||
const found = await detector.detect(video);
|
||||
const found = await decodeLive(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);
|
||||
for (const code of [found.isbn, found.other]) {
|
||||
if (!code) continue;
|
||||
const r = acceptRead(state, code, Date.now());
|
||||
state = r.state;
|
||||
if (r.emit) onIsbn(r.emit);
|
||||
else if (r.reject) onReject(code);
|
||||
if (r.emit) handlers.onIsbn(r.emit);
|
||||
else if (r.reject) handlers.onOther(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;
|
||||
|
||||
async function capture(): Promise<DecodeOutcome> {
|
||||
let result: DecodeOutcome = { isbn: null, other: null };
|
||||
// Highest resolution first: the camera's still-photo mode where it exists.
|
||||
const IC = (window as unknown as { ImageCapture?: new (t: MediaStreamTrack) => { takePhoto(): Promise<Blob> } }).ImageCapture;
|
||||
const track = stream.getVideoTracks()[0];
|
||||
if (IC && track) {
|
||||
let photo: ImageBitmap | null = null;
|
||||
try { photo = await createImageBitmap(await new IC(track).takePhoto()); } catch { /* use the current frame */ }
|
||||
if (photo) {
|
||||
try { result = await decodeThorough(photo); } finally { photo.close(); }
|
||||
}
|
||||
}
|
||||
if (!result.isbn && video.videoWidth > 0) {
|
||||
const frame = await decodeThorough(video);
|
||||
result = { isbn: frame.isbn, other: result.other ?? frame.other };
|
||||
}
|
||||
if (result.isbn) state = markEmitted(state, result.isbn, Date.now());
|
||||
return result;
|
||||
}
|
||||
|
||||
return { stop, capture };
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { emptySession, forget, touch } from './session.ts';
|
||||
|
||||
test('a book listed twice stays one row and moves to the top', () => {
|
||||
let s = touch(emptySession, 1, false);
|
||||
s = touch(s, 2, false);
|
||||
s = touch(s, 1, true);
|
||||
assert.deepEqual(s.order, [1, 2]);
|
||||
assert.equal(s.touched[1], 2);
|
||||
assert.equal(s.touched[2], 1);
|
||||
});
|
||||
|
||||
test('"earlier" is decided when the book is first listed, not by later scans', () => {
|
||||
let s = touch(emptySession, 1, false);
|
||||
s = touch(s, 1, true);
|
||||
assert.equal(s.earlier[1], undefined);
|
||||
s = touch(s, 2, true);
|
||||
s = touch(s, 2, false);
|
||||
assert.equal(s.earlier[2], true);
|
||||
});
|
||||
|
||||
test('forget removes a book everywhere', () => {
|
||||
let s = touch(touch(emptySession, 1, true), 2, false);
|
||||
s = forget(s, 1);
|
||||
assert.deepEqual(s.order, [2]);
|
||||
assert.equal(s.earlier[1], undefined);
|
||||
assert.equal(s.touched[1], undefined);
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
/** The books touched in this browsing session, one row per book id, newest activity first. */
|
||||
export interface SessionState {
|
||||
order: number[];
|
||||
/** Books that were already in the catalog when first added to this session. */
|
||||
earlier: Record<number, true>;
|
||||
/** How many times each book was added or scanned; above 1 means "seen again", so its row flashes. */
|
||||
touched: Record<number, number>;
|
||||
}
|
||||
|
||||
export const emptySession: SessionState = { order: [], earlier: {}, touched: {} };
|
||||
|
||||
/** Add a book, or move it to the top if it is listed already. Never creates a second row. */
|
||||
export function touch(s: SessionState, bookId: number, alreadyInCatalog: boolean): SessionState {
|
||||
const known = s.order.includes(bookId);
|
||||
return {
|
||||
order: [bookId, ...s.order.filter(i => i !== bookId)],
|
||||
earlier: !known && alreadyInCatalog ? { ...s.earlier, [bookId]: true } : s.earlier,
|
||||
touched: { ...s.touched, [bookId]: (s.touched[bookId] ?? 0) + 1 },
|
||||
};
|
||||
}
|
||||
|
||||
export function forget(s: SessionState, bookId: number): SessionState {
|
||||
const { [bookId]: _a, ...earlier } = s.earlier;
|
||||
const { [bookId]: _b, ...touched } = s.touched;
|
||||
return { ...s, order: s.order.filter(i => i !== bookId), earlier, touched };
|
||||
}
|
||||
+44
-4
@@ -40,11 +40,25 @@ label small { display: block; margin-top: 4px; }
|
||||
.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-wrap { position: relative; width: 100%; background: #0b0c0e; border-radius: 12px; overflow: hidden; border: 3px solid var(--line); transition: border-color .15s; }
|
||||
.video-wrap.flash { border-color: var(--flash); transition: none; }
|
||||
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; }
|
||||
.video-empty { position: absolute; inset: 0; display: grid; place-items: center; }
|
||||
button.big { font-size: 1.1rem; padding: 12px 26px; }
|
||||
.target { position: absolute; border: 2px solid rgba(255,255,255,.92); border-radius: 10px; box-shadow: 0 0 0 100vmax rgba(0,0,0,.38); pointer-events: none; transition: border-color .15s; }
|
||||
.video-wrap.flash .target { border-color: var(--flash); box-shadow: 0 0 0 100vmax rgba(0,0,0,.38), 0 0 0 3px var(--flash); }
|
||||
.hint { position: absolute; left: 50%; bottom: 5%; transform: translateX(-50%); max-width: 92%; padding: 4px 12px; border-radius: 999px; background: rgba(0,0,0,.72); color: #fff; font-size: .9rem; white-space: nowrap; pointer-events: none; }
|
||||
.scanning { position: absolute; top: 10px; right: 10px; display: flex; align-items: center; gap: 7px; padding: 3px 11px 3px 9px; border-radius: 999px; background: rgba(0,0,0,.72); color: #fff; font-size: .82rem; pointer-events: none; }
|
||||
.pulse { width: 9px; height: 9px; border-radius: 50%; background: #52c586; animation: pulse 1.2s ease-in-out infinite; }
|
||||
@keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .35; transform: scale(.7); } }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@keyframes rowflash { from { opacity: .35; } to { opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) { .pulse { animation: none; } .spinner { animation-duration: 3s; } .flashbar { animation-duration: .01s; } }
|
||||
.status { margin: 10px 0; padding: 8px 12px; border-radius: 8px; border-left: 4px solid var(--line); background: var(--panel); font-weight: 500; min-height: 2.6em; }
|
||||
.status.ok { border-left-color: var(--ok); color: var(--ok); }
|
||||
.status.warn { border-left-color: var(--warn); color: var(--warn); }
|
||||
.small { font-size: .85rem; }
|
||||
.summary { font-weight: 600; margin: 0 0 6px; }
|
||||
.isbn-form input { font-size: 1.1rem; }
|
||||
|
||||
.list { list-style: none; margin: 0; padding: 0; }
|
||||
@@ -76,3 +90,29 @@ legend { color: var(--muted); font-size: .9rem; padding: 0; margin-bottom: 6px;
|
||||
.slot.on { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
|
||||
.slot.used { opacity: .45; }
|
||||
.confirm { border-color: var(--accent); }
|
||||
|
||||
/* Books: one row each, one state each. */
|
||||
.book { position: relative; display: grid; gap: 8px; padding: 12px 12px 12px 14px; border-bottom: 1px solid var(--line); border-left: 4px solid var(--line); overflow: hidden; }
|
||||
.book.looking { border-left-color: var(--accent); }
|
||||
.book.ready { border-left-color: var(--ok); }
|
||||
.book.attention { border-left-color: var(--warn); background: color-mix(in srgb, var(--warn) 8%, transparent); }
|
||||
.book-head { display: flex; gap: 12px; justify-content: space-between; align-items: flex-start; }
|
||||
.book-head .item-main { flex: 1; }
|
||||
.earlier { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; }
|
||||
.book-state { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; }
|
||||
.state-label { display: inline-flex; align-items: center; gap: 7px; font-weight: 600; white-space: nowrap; }
|
||||
.book.looking .state-label, .item[data-state=looking] .state-label { color: var(--accent); }
|
||||
.book.ready .state-label, .item .state-label { color: var(--ok); }
|
||||
.book.attention .state-label { color: var(--warn); }
|
||||
.item[data-state=looking] .state-label { color: var(--accent); }
|
||||
.elapsed { font-weight: 400; font-variant-numeric: tabular-nums; color: var(--muted); }
|
||||
.icon { width: 16px; height: 16px; flex: none; }
|
||||
.spinner { width: 14px; height: 14px; border-radius: 50%; border: 2px solid color-mix(in srgb, var(--accent) 30%, transparent); border-top-color: var(--accent); animation: spin .8s linear infinite; flex: none; }
|
||||
.reason { color: var(--text); overflow-wrap: anywhere; }
|
||||
.note { overflow-wrap: anywhere; }
|
||||
.flashbar { position: absolute; inset: 0; background: var(--flash); opacity: 0; animation: rowflash 1.4s ease-out; pointer-events: none; }
|
||||
.item { align-items: center; }
|
||||
.item > .state-label { margin-left: auto; }
|
||||
.item.dim .title { color: var(--muted); }
|
||||
.callno-slot { min-width: 9.5em; }
|
||||
.queue-head { font-weight: 600; }
|
||||
@@ -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
@@ -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
@@ -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); }
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseYear } from './year.ts';
|
||||
|
||||
test('empty year is null', () => {
|
||||
assert.deepEqual(parseYear(''), { ok: true, value: null });
|
||||
assert.deepEqual(parseYear(' '), { ok: true, value: null });
|
||||
});
|
||||
test('numeric year is a number', () => assert.deepEqual(parseYear(' 2018 '), { ok: true, value: 2018 }));
|
||||
test('non-numeric year is an error, not NaN', () => {
|
||||
for (const t of ['abc', '20x8', '2018.5', '-5', '12345']) assert.deepEqual(parseYear(t), { ok: false }, t);
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Empty means "no year" (null); anything that is not a whole number is an error, never NaN. */
|
||||
export function parseYear(text: string): { ok: true; value: number | null } | { ok: false } {
|
||||
const t = text.trim();
|
||||
if (t === '') return { ok: true, value: null };
|
||||
if (!/^\d{1,4}$/.test(t)) return { ok: false };
|
||||
return { ok: true, value: Number(t) };
|
||||
}
|
||||
Reference in new issue
Block a user