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
+51
-5
@@ -10,20 +10,20 @@ const found: Resolution = {
|
||||
callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: null, reason: null,
|
||||
};
|
||||
|
||||
function setup(resolve = async () => found) {
|
||||
function setup(resolve = async () => found, port?: number) {
|
||||
const db = openDb(':memory:');
|
||||
const events = createEventBus();
|
||||
const resolver = { resolve, search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
|
||||
const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0] });
|
||||
const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0], log: () => {} });
|
||||
const pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = [];
|
||||
const app = createApp({
|
||||
db, jobs, resolver, events,
|
||||
db, jobs, resolver, events, port,
|
||||
renderCardsPdf: async (cards, opts) => { pdfCalls.push({ cards, opts }); return new TextEncoder().encode('%PDF-stub'); },
|
||||
renderCalibrationPdf: async () => new TextEncoder().encode('%PDF-cal'),
|
||||
classNames: (l) => ({ className: 'Class ' + l[0], subclassName: 'Sub ' + l }),
|
||||
});
|
||||
const req = (method: string, path: string, json?: unknown) =>
|
||||
app.request(path, { method, ...(json === undefined ? {} : { body: JSON.stringify(json), headers: { 'content-type': 'application/json' } }) });
|
||||
const req = (method: string, path: string, json?: unknown, extra: Record<string, string> = {}) =>
|
||||
app.request(path, { method, headers: { ...(json === undefined ? {} : { 'content-type': 'application/json' }), ...extra }, ...(json === undefined ? {} : { body: JSON.stringify(json) }) });
|
||||
return { db, jobs, app, req, pdfCalls, events };
|
||||
}
|
||||
|
||||
@@ -176,3 +176,49 @@ test('events stream delivers changes and cleans up on disconnect', async () => {
|
||||
await res2.body!.cancel();
|
||||
assert.equal(events.listenerCount(), 0);
|
||||
});
|
||||
|
||||
test('state-changing requests from another origin are refused', async () => {
|
||||
const { req, db } = setup(undefined, 4321);
|
||||
const ok = ['http://localhost:4321', 'http://127.0.0.1:4321'];
|
||||
const bad = ['http://evil.example', 'http://localhost:9999', 'http://localhost:4321.evil.com', 'null', 'https://localhost:4321'];
|
||||
for (const origin of ok) assert.equal((await req('POST', '/api/books/manual', { title: 'T' }, { origin })).status, 200, origin);
|
||||
for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {
|
||||
for (const origin of bad) {
|
||||
const r = await req(method, '/api/books/1', method === 'DELETE' ? undefined : { title: 'x' }, { origin });
|
||||
assert.equal(r.status, 403, `${method} ${origin}`);
|
||||
}
|
||||
}
|
||||
assert.equal(db.listBooks().length, 2);
|
||||
assert.equal((await req('GET', '/api/books', undefined, { origin: 'http://evil.example' })).status, 200);
|
||||
assert.equal((await req('POST', '/api/books/manual', { title: 'No origin header' })).status, 200);
|
||||
});
|
||||
|
||||
test('PATCH year must be an integer or null', async () => {
|
||||
const { req, db, jobs } = setup();
|
||||
const m = await (await req('POST', '/api/books/manual', { title: 'Foo', year: 2000 })).json() as any;
|
||||
await jobs.idle();
|
||||
for (const year of ['abc', 1999.5, true, {}, -4]) {
|
||||
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year })).status, 400, JSON.stringify(year));
|
||||
}
|
||||
assert.equal(db.getBook(m.book.id)!.year, 2000);
|
||||
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year: 2011 })).status, 200);
|
||||
assert.equal(db.getBook(m.book.id)!.year, 2011);
|
||||
assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year: null })).status, 200);
|
||||
assert.equal(db.getBook(m.book.id)!.year, null);
|
||||
});
|
||||
|
||||
test('retry forgets the book\'s cached source responses', async () => {
|
||||
const { req, db, jobs } = setup();
|
||||
const s = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any;
|
||||
await jobs.idle();
|
||||
db.updateBook(s.book.id, { lccn: '2018012345', title: 'Rust Book' });
|
||||
for (const k of ['ol-data:9781593278281', 'ol-search:9781593278281', 'loc-isbn:9781593278281', 'loc-lccn:2018012345',
|
||||
'loc-title:Rust Book|Steve Klabnik', 'ol-data:9780201835953', 'loc-title:Other|X']) db.cache.set(k, 'body');
|
||||
assert.equal((await req('POST', `/api/books/${s.book.id}/retry`)).status, 200);
|
||||
await jobs.idle();
|
||||
for (const k of ['ol-data:9781593278281', 'ol-search:9781593278281', 'loc-isbn:9781593278281', 'loc-lccn:2018012345', 'loc-title:Rust Book|Steve Klabnik']) {
|
||||
assert.equal(db.cache.get(k), null, k);
|
||||
}
|
||||
assert.equal(db.cache.get('ol-data:9780201835953'), 'body');
|
||||
assert.equal(db.cache.get('loc-title:Other|X'), 'body');
|
||||
});
|
||||
@@ -31,6 +31,8 @@ export function createEventBus(): EventBus {
|
||||
}
|
||||
|
||||
export interface AppDeps {
|
||||
/** The port the page is served from; the only Origin (on localhost / 127.0.0.1) allowed to change state. */
|
||||
port?: number;
|
||||
db: Db; jobs: Jobs; resolver: ResolverLike;
|
||||
renderCardsPdf: RenderCardsPdf; renderCalibrationPdf: RenderCalibrationPdf;
|
||||
classNames: ClassNames;
|
||||
@@ -58,6 +60,13 @@ function callNumberFields(raw: string): Partial<Book> {
|
||||
manualOverride: true, confidence: 'manual', source: 'manual' };
|
||||
}
|
||||
|
||||
function cacheKeys(book: Book): string[] {
|
||||
const keys: string[] = [];
|
||||
if (book.isbn13) keys.push(`ol-data:${book.isbn13}`, `ol-search:${book.isbn13}`, `loc-isbn:${book.isbn13}`);
|
||||
if (book.lccn) keys.push(`loc-lccn:${book.lccn}`);
|
||||
return keys;
|
||||
}
|
||||
|
||||
export function createApp(deps: AppDeps): Hono {
|
||||
const { db, jobs, resolver, classNames } = deps;
|
||||
const events = deps.events ?? createEventBus();
|
||||
@@ -69,6 +78,20 @@ export function createApp(deps: AppDeps): Hono {
|
||||
return c.json({ error: 'Internal error' }, 500);
|
||||
});
|
||||
|
||||
// A web page on another origin must not be able to drive this local app. Requests without an
|
||||
// Origin header (curl, tests, same-origin GET-like navigations) are not browser cross-site requests.
|
||||
app.use('*', async (c, next) => {
|
||||
const method = c.req.method;
|
||||
const origin = c.req.header('origin');
|
||||
if (origin !== undefined && (method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE')) {
|
||||
const port = deps.port ?? (new URL(c.req.url).port || '80');
|
||||
if (origin !== `http://localhost:${port}` && origin !== `http://127.0.0.1:${port}`) {
|
||||
return c.json({ error: 'Cross-origin request refused' }, 403);
|
||||
}
|
||||
}
|
||||
await next();
|
||||
});
|
||||
|
||||
async function body(c: Context): Promise<Record<string, unknown>> {
|
||||
try {
|
||||
const v = await c.req.json();
|
||||
@@ -189,6 +212,9 @@ export function createApp(deps: AppDeps): Hono {
|
||||
app.post('/api/books/:id/retry', (c) => {
|
||||
const book = bookParam(c);
|
||||
if (book.manualOverride) throw new HttpError(400, 'This call number was entered by hand, so there is nothing to look up');
|
||||
// "Look up again" must really ask again, so forget what the sources told us for this book.
|
||||
for (const key of cacheKeys(book)) db.cache.delete(key);
|
||||
if (book.title) db.cache.deletePrefix(`loc-title:${book.title}|`);
|
||||
const updated = db.updateBook(book.id, { status: 'pending', attentionReason: null })!;
|
||||
events.emitBook(updated);
|
||||
jobs.enqueue(book.id);
|
||||
|
||||
+8
-2
@@ -3,7 +3,7 @@ import { mkdirSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import type { Book, Confidence, Settings, Source, Status } from '../shared/types.ts';
|
||||
|
||||
import type { SourceCache } from './sources/http.ts';
|
||||
import type { ForgettableCache, SourceCache } from './sources/http.ts';
|
||||
export type { SourceCache };
|
||||
|
||||
export interface NewBook {
|
||||
@@ -26,7 +26,7 @@ export interface Db {
|
||||
listPendingIds(): number[];
|
||||
getSettings(): Settings;
|
||||
putSettings(s: Settings): void;
|
||||
cache: SourceCache;
|
||||
cache: ForgettableCache;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
@@ -169,6 +169,12 @@ export function openDb(path: string): Db {
|
||||
db.prepare('INSERT INTO source_cache (key, body) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET body = excluded.body')
|
||||
.run(key, body);
|
||||
},
|
||||
delete(key) {
|
||||
db.prepare('DELETE FROM source_cache WHERE key = ?').run(key);
|
||||
},
|
||||
deletePrefix(prefix) {
|
||||
db.prepare('DELETE FROM source_cache WHERE substr(key, 1, length(?)) = ?').run(prefix, prefix);
|
||||
},
|
||||
},
|
||||
close() { db.close(); },
|
||||
};
|
||||
|
||||
+123
-5
@@ -1,7 +1,7 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { openDb } from './db.ts';
|
||||
import { createJobs } from './jobs.ts';
|
||||
import { createJobs, DEFAULT_RETRY_DELAYS_MS } from './jobs.ts';
|
||||
import type { ResolverLike } from './jobs.ts';
|
||||
import type { Book, Resolution } from '../shared/types.ts';
|
||||
|
||||
@@ -13,12 +13,13 @@ const found: Resolution = {
|
||||
reason: null,
|
||||
};
|
||||
|
||||
function setup(resolve: ResolverLike['resolve']) {
|
||||
function setup(resolve: ResolverLike['resolve'], delays = [0, 0, 0]) {
|
||||
const db = openDb(':memory:');
|
||||
const changes: Book[] = [];
|
||||
const logs: string[] = [];
|
||||
const resolver: ResolverLike = { resolve, search: async () => [] };
|
||||
const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0, 0, 0] });
|
||||
return { db, jobs, changes };
|
||||
const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: delays, log: (l) => logs.push(l) });
|
||||
return { db, jobs, changes, logs };
|
||||
}
|
||||
|
||||
test('success resolves the book and emits changes', async () => {
|
||||
@@ -37,7 +38,7 @@ test('success resolves the book and emits changes', async () => {
|
||||
|
||||
test('no call number -> needs_attention with reason, metadata kept', async () => {
|
||||
const { db, jobs } = setup(async () => ({ ...found, callNumber: null, sortKey: null, confidence: null, source: null, reason: 'No Library of Congress number found' }));
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' });
|
||||
jobs.enqueue(book.id);
|
||||
await jobs.idle();
|
||||
const b = db.getBook(book.id)!;
|
||||
@@ -140,3 +141,120 @@ test('deleting a book mid-queue is harmless', async () => {
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(book.id), null);
|
||||
});
|
||||
|
||||
test('default retry delays are 5 s, 30 s, 120 s', () => {
|
||||
assert.deepEqual(DEFAULT_RETRY_DELAYS_MS, [5000, 30000, 120000]);
|
||||
});
|
||||
|
||||
test('a waiting retry does not block the books behind it', async () => {
|
||||
const order: string[] = [];
|
||||
let aCalls = 0;
|
||||
const { db, jobs } = setup(async (i) => {
|
||||
if (i.isbn13 === '9781593278281' && ++aCalls === 1) throw new TemporaryError('LoC did not answer');
|
||||
order.push(i.isbn13!);
|
||||
return found;
|
||||
}, [60, 60, 60]);
|
||||
const a = db.insertPending({ isbn13: '9781593278281', title: 'a' }).book;
|
||||
const b = db.insertPending({ isbn13: '9780201835953', title: 'b' }).book;
|
||||
jobs.enqueue(a.id); jobs.enqueue(b.id);
|
||||
await jobs.idle();
|
||||
assert.deepEqual(order, ['9780201835953', '9781593278281']);
|
||||
assert.equal(db.getBook(a.id)!.status, 'resolved');
|
||||
});
|
||||
|
||||
test('a book waiting for a retry stays pending with a progress note, cleared when it resolves', async () => {
|
||||
let calls = 0;
|
||||
const { db, jobs, changes } = setup(async () => {
|
||||
if (++calls === 1) throw new TemporaryError('Network error for https://lx2.loc.gov/sru/lcdb: fetch failed');
|
||||
return found;
|
||||
}, [40, 40, 40]);
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' });
|
||||
jobs.enqueue(book.id);
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
const mid = db.getBook(book.id)!;
|
||||
assert.equal(mid.status, 'pending');
|
||||
assert.equal(mid.attentionReason, 'Library of Congress did not answer. Trying again shortly.');
|
||||
assert.ok(changes.some((c) => c.attentionReason === mid.attentionReason), 'a change was emitted');
|
||||
await jobs.idle();
|
||||
const done = db.getBook(book.id)!;
|
||||
assert.equal(done.status, 'resolved');
|
||||
assert.equal(done.attentionReason, null);
|
||||
});
|
||||
|
||||
test('retry timers are unref\'d', async () => {
|
||||
const real = globalThis.setTimeout;
|
||||
const made: ReturnType<typeof setTimeout>[] = [];
|
||||
globalThis.setTimeout = ((fn: () => void, ms?: number) => { const t = real(fn, ms); made.push(t); return t; }) as typeof setTimeout;
|
||||
try {
|
||||
const { db, jobs } = setup(async () => { throw new TemporaryError('x'); }, [60_000]);
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
|
||||
jobs.enqueue(book.id);
|
||||
await new Promise((r) => real(r, 20));
|
||||
assert.equal(made.length, 1);
|
||||
assert.equal(made[0]!.hasRef(), false);
|
||||
jobs.enqueue(book.id); // cancels the wait; ends the test cleanly
|
||||
} finally { globalThis.setTimeout = real; }
|
||||
});
|
||||
|
||||
test('only the final attempt asks the resolver to tolerate LoC failure', async () => {
|
||||
const flags: (boolean | undefined)[] = [];
|
||||
const { db, jobs } = setup(async (_i, o) => {
|
||||
flags.push(o?.tolerateLocFailure);
|
||||
if (flags.length < 4) throw new TemporaryError('blocked');
|
||||
return found;
|
||||
});
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
|
||||
jobs.enqueue(book.id);
|
||||
await jobs.idle();
|
||||
assert.deepEqual(flags, [false, false, false, true]);
|
||||
assert.equal(db.getBook(book.id)!.status, 'resolved');
|
||||
});
|
||||
|
||||
test('"Look up again" while waiting restarts the retries at once', async () => {
|
||||
let calls = 0;
|
||||
const { db, jobs } = setup(async () => { if (++calls === 1) throw new TemporaryError('x'); return found; }, [60_000]);
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
|
||||
jobs.enqueue(book.id);
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
assert.equal(db.getBook(book.id)!.status, 'pending');
|
||||
jobs.enqueue(book.id);
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(book.id)!.status, 'resolved');
|
||||
});
|
||||
|
||||
test('one log line per attempt: ISBN, outcome and elapsed ms', async () => {
|
||||
let calls = 0;
|
||||
const { db, jobs, logs } = setup(async () => { if (++calls === 1) throw new TemporaryError('timed out'); return found; });
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' });
|
||||
jobs.enqueue(book.id);
|
||||
await jobs.idle();
|
||||
assert.equal(logs.length, 2);
|
||||
assert.match(logs[0]!, /9781593278281.*timed out.*\d+ ms/);
|
||||
assert.match(logs[1]!, /9781593278281.*QA76\.73\.R87 K53 2018 \(loc-isbn\).* in \d+ ms/);
|
||||
const t = setup(async () => ({ ...found, callNumber: null, sortKey: null, confidence: null, source: null, reason: 'No Library of Congress number found' }));
|
||||
const nb = t.db.insertPending({ title: 'Some Title', authors: ['A'] }).book;
|
||||
t.jobs.enqueue(nb.id);
|
||||
await t.jobs.idle();
|
||||
assert.match(t.logs[0]!, /Some Title.*No Library of Congress number found.*\d+ ms/);
|
||||
});
|
||||
|
||||
test('lookup metadata fills empty fields but never overwrites what the user typed', async () => {
|
||||
const { db, jobs } = setup(async (_i, o) => { o?.onMeta?.(found.meta!); return found; });
|
||||
const typed = db.insertPending({ isbn13: '9781593278281', title: 'My Title', authors: ['Me Myself'], publisher: 'Mine', year: 1999 }).book;
|
||||
const bare = db.insertPending({ isbn13: '9780201835953', title: '9780201835953' }).book;
|
||||
jobs.enqueue(typed.id); jobs.enqueue(bare.id);
|
||||
await jobs.idle();
|
||||
const t = db.getBook(typed.id)!;
|
||||
assert.deepEqual([t.title, t.authors, t.publisher, t.year], ['My Title', ['Me Myself'], 'Mine', 1999]);
|
||||
assert.deepEqual(t.subjects, ['Rust']); // was empty, so filled
|
||||
const b = db.getBook(bare.id)!;
|
||||
assert.deepEqual([b.title, b.authors, b.publisher, b.year], ['The Rust Book', ['Klabnik, Steve'], 'No Starch', 2018]);
|
||||
});
|
||||
|
||||
test('an LCCN placeholder title counts as empty', async () => {
|
||||
const { db, jobs } = setup(async (_i, o) => { o?.onMeta?.(found.meta!); return found; });
|
||||
const { book } = db.insertPending({ lccn: '88005934', title: '88005934' });
|
||||
jobs.enqueue(book.id);
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(book.id)!.title, 'The Rust Book');
|
||||
});
|
||||
+104
-58
@@ -2,6 +2,8 @@ import type { Book, BookMeta, ResolveInput } from '../shared/types.ts';
|
||||
import type { Db } from './db.ts';
|
||||
import type { Resolver } from './resolve/resolver.ts';
|
||||
|
||||
export const DEFAULT_RETRY_DELAYS_MS = [5_000, 30_000, 120_000];
|
||||
|
||||
export type ResolverLike = Resolver;
|
||||
|
||||
export interface Jobs { enqueue(id: number): void; resume(): void; idle(): Promise<void> }
|
||||
@@ -14,86 +16,118 @@ function defaultIsTemporary(e: unknown): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
if (ms <= 0) return Promise.resolve();
|
||||
return new Promise((resolve) => { setTimeout(resolve, ms).unref(); });
|
||||
/** What the page shows while a book waits for another try. */
|
||||
export function retryNote(message: string): string {
|
||||
const who = /loc\.gov|Library of Congress/i.test(message) ? 'Library of Congress'
|
||||
: /openlibrary|Open Library/i.test(message) ? 'Open Library' : 'A lookup service';
|
||||
return `${who} did not answer. Trying again shortly.`;
|
||||
}
|
||||
|
||||
export function createJobs(deps: {
|
||||
db: Db; resolver: ResolverLike; onChange: (book: Book) => void;
|
||||
retryDelaysMs?: number[]; isTemporary?: (e: unknown) => boolean;
|
||||
log?: (line: string) => void;
|
||||
}): Jobs {
|
||||
const { db, resolver, onChange } = deps;
|
||||
const delays = deps.retryDelaysMs ?? [30000, 120000, 600000];
|
||||
const delays = deps.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
||||
const isTemporary = deps.isTemporary ?? defaultIsTemporary;
|
||||
const log = deps.log ?? ((line: string) => console.log(line));
|
||||
const queue: number[] = [];
|
||||
const queued = new Set<number>();
|
||||
const attempts = new Map<number, number>();
|
||||
// Books waiting for a retry: they hold no worker; a timer puts them back in the queue.
|
||||
const waiting = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
let running: Promise<void> | null = null;
|
||||
let idlers = 0;
|
||||
let wake: (() => void)[] = [];
|
||||
const notify = () => { const w = wake; wake = []; for (const f of w) f(); };
|
||||
|
||||
function emit(id: number, patch: Parameters<Db['updateBook']>[1]): void {
|
||||
const b = db.updateBook(id, patch);
|
||||
if (b) onChange(b);
|
||||
}
|
||||
|
||||
/** Lookup metadata only fills what is empty; the placeholder title (the ISBN or LCCN) counts as empty. */
|
||||
function applyMeta(id: number, meta: BookMeta): void {
|
||||
const cur = db.getBook(id);
|
||||
if (!cur) return;
|
||||
const patch: Parameters<Db['updateBook']>[1] = {
|
||||
subtitle: meta.subtitle ?? cur.subtitle ?? undefined,
|
||||
publisher: meta.publisher ?? cur.publisher ?? undefined,
|
||||
year: meta.year ?? cur.year ?? undefined,
|
||||
subjects: meta.subjects.length ? meta.subjects : cur.subjects,
|
||||
lccn: meta.lccn ?? cur.lccn ?? undefined,
|
||||
};
|
||||
// A hand-edited book keeps the title and authors the user typed.
|
||||
if (!cur.manualOverride) {
|
||||
if (meta.title) patch.title = meta.title;
|
||||
if (meta.authors.length) patch.authors = meta.authors;
|
||||
}
|
||||
emit(id, patch);
|
||||
const patch: Parameters<Db['updateBook']>[1] = {};
|
||||
if (meta.title && (cur.title === cur.isbn13 || cur.title === cur.lccn || !cur.title.trim())) patch.title = meta.title;
|
||||
if (meta.authors.length && cur.authors.length === 0) patch.authors = meta.authors;
|
||||
if (meta.subtitle && !cur.subtitle) patch.subtitle = meta.subtitle;
|
||||
if (meta.publisher && !cur.publisher) patch.publisher = meta.publisher;
|
||||
if (meta.year && !cur.year) patch.year = meta.year;
|
||||
if (meta.subjects.length && cur.subjects.length === 0) patch.subjects = meta.subjects;
|
||||
if (meta.lccn && !cur.lccn) patch.lccn = meta.lccn;
|
||||
if (Object.keys(patch).length) emit(id, patch);
|
||||
}
|
||||
|
||||
async function lookup(id: number): Promise<void> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const book = db.getBook(id);
|
||||
if (!book || book.status !== 'pending') return;
|
||||
const input: ResolveInput = {};
|
||||
if (book.isbn13) input.isbn13 = book.isbn13;
|
||||
if (book.lccn) input.lccn = book.lccn;
|
||||
if (!book.isbn13) {
|
||||
input.title = book.title;
|
||||
if (book.authors[0]) input.author = book.authors[0];
|
||||
function schedule(id: number, delayMs: number): void {
|
||||
if (delayMs <= 0) { queued.add(id); queue.push(id); start(); return; }
|
||||
const t = setTimeout(() => {
|
||||
waiting.delete(id);
|
||||
queued.add(id); queue.push(id);
|
||||
start();
|
||||
notify();
|
||||
}, delayMs);
|
||||
// Do not hold the process open for a retry, unless a test is awaiting idle().
|
||||
if (idlers === 0) t.unref();
|
||||
waiting.set(id, t);
|
||||
}
|
||||
|
||||
async function attempt(id: number): Promise<void> {
|
||||
const book = db.getBook(id);
|
||||
if (!book || book.status !== 'pending') { attempts.delete(id); return; }
|
||||
const n = attempts.get(id) ?? 0;
|
||||
const final = n >= delays.length;
|
||||
const input: ResolveInput = {};
|
||||
if (book.isbn13) input.isbn13 = book.isbn13;
|
||||
if (book.lccn) input.lccn = book.lccn;
|
||||
if (!book.isbn13) {
|
||||
input.title = book.title;
|
||||
if (book.authors[0]) input.author = book.authors[0];
|
||||
}
|
||||
if (book.year) input.year = book.year;
|
||||
const label = book.isbn13 ?? book.title;
|
||||
const started = Date.now();
|
||||
const took = () => `${Date.now() - started} ms`;
|
||||
try {
|
||||
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final });
|
||||
attempts.delete(id);
|
||||
const cur = db.getBook(id);
|
||||
if (!cur) return;
|
||||
if (res.meta) applyMeta(id, res.meta);
|
||||
const dewey = res.dewey ?? cur.dewey ?? undefined;
|
||||
if (cur.manualOverride) {
|
||||
emit(id, { dewey });
|
||||
log(`[lookup] ${label}: kept the hand-entered call number (${took()})`);
|
||||
} else if (res.callNumber) {
|
||||
emit(id, {
|
||||
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
|
||||
source: res.source, dewey, status: 'resolved', attentionReason: null,
|
||||
});
|
||||
log(`[lookup] ${label}: ${res.callNumber} (${res.source}) in ${took()}`);
|
||||
} else {
|
||||
const reason = res.reason ?? 'No Library of Congress number found';
|
||||
emit(id, { dewey, status: 'needs_attention', attentionReason: reason });
|
||||
log(`[lookup] ${label}: no call number, ${reason} in ${took()}`);
|
||||
}
|
||||
if (book.year) input.year = book.year;
|
||||
try {
|
||||
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m) });
|
||||
const cur = db.getBook(id);
|
||||
if (!cur) return;
|
||||
if (res.meta) applyMeta(id, res.meta);
|
||||
const dewey = res.dewey ?? cur.dewey ?? undefined;
|
||||
if (cur.manualOverride) {
|
||||
emit(id, { dewey });
|
||||
} else if (res.callNumber) {
|
||||
emit(id, {
|
||||
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
|
||||
source: res.source, dewey, status: 'resolved', attentionReason: null,
|
||||
});
|
||||
} else {
|
||||
emit(id, { dewey, status: 'needs_attention', attentionReason: res.reason ?? 'No Library of Congress number found' });
|
||||
}
|
||||
return;
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
if (isTemporary(e) && attempt < delays.length) {
|
||||
await sleep(delays[attempt]!);
|
||||
continue;
|
||||
}
|
||||
const cur = db.getBook(id);
|
||||
if (cur && !cur.manualOverride) {
|
||||
emit(id, { status: 'needs_attention', attentionReason: 'Lookup failed: ' + message });
|
||||
}
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
if (isTemporary(e) && !final) {
|
||||
attempts.set(id, n + 1);
|
||||
const delay = delays[n]!;
|
||||
log(`[lookup] ${label}: attempt ${n + 1} failed, ${message}; trying again in ${Math.round(delay / 1000)} s (${took()})`);
|
||||
if (db.getBook(id)?.status === 'pending') emit(id, { attentionReason: retryNote(message) });
|
||||
schedule(id, delay);
|
||||
return;
|
||||
}
|
||||
attempts.delete(id);
|
||||
log(`[lookup] ${label}: failed, ${message} in ${took()}`);
|
||||
const cur = db.getBook(id);
|
||||
if (cur && !cur.manualOverride) {
|
||||
emit(id, { status: 'needs_attention', attentionReason: 'Lookup failed: ' + message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,17 +135,20 @@ export function createJobs(deps: {
|
||||
while (queue.length) {
|
||||
const id = queue.shift()!;
|
||||
queued.delete(id);
|
||||
try { await lookup(id); } catch { /* a failure on one book must not stop the queue */ }
|
||||
try { await attempt(id); } catch { /* a failure on one book must not stop the queue */ }
|
||||
}
|
||||
}
|
||||
|
||||
function start(): void {
|
||||
if (running) return;
|
||||
running = drain().finally(() => { running = null; if (queue.length) start(); });
|
||||
running = drain().finally(() => { running = null; if (queue.length) start(); notify(); });
|
||||
}
|
||||
|
||||
return {
|
||||
enqueue(id) {
|
||||
// A fresh request (scan, "Look up again") overrides any wait and starts the retries over.
|
||||
const t = waiting.get(id);
|
||||
if (t) { clearTimeout(t); waiting.delete(id); attempts.delete(id); }
|
||||
if (queued.has(id)) return;
|
||||
queued.add(id);
|
||||
queue.push(id);
|
||||
@@ -119,7 +156,16 @@ export function createJobs(deps: {
|
||||
},
|
||||
resume() { for (const id of db.listPendingIds()) this.enqueue(id); },
|
||||
async idle() {
|
||||
while (running || queue.length) await running;
|
||||
idlers++;
|
||||
for (const t of waiting.values()) t.ref();
|
||||
try {
|
||||
while (running || queue.length || waiting.size) {
|
||||
if (running) await running;
|
||||
else await new Promise<void>((r) => { wake.push(r); });
|
||||
}
|
||||
} finally {
|
||||
if (--idlers === 0) for (const t of waiting.values()) t.unref();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
+5
-5
@@ -1,5 +1,6 @@
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { extname, join, normalize, resolve as resolvePath } from 'node:path';
|
||||
import { extname, join, resolve as resolvePath } from 'node:path';
|
||||
import { staticPath } from './static.ts';
|
||||
import { serve } from '@hono/node-server';
|
||||
import { openDb } from './db.ts';
|
||||
import { createJobs } from './jobs.ts';
|
||||
@@ -24,15 +25,14 @@ const resolver = createResolver({ fetch: globalThis.fetch, cache: db.cache });
|
||||
const jobs = createJobs({
|
||||
db, resolver, onChange: (b) => events.emitBook(b), isTemporary: (e) => e instanceof TemporaryError,
|
||||
});
|
||||
const app = createApp({ db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events });
|
||||
const app = createApp({ port, db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events });
|
||||
|
||||
app.get('*', (c) => {
|
||||
if (!existsSync(join(webRoot, 'index.html'))) {
|
||||
return c.text('The web app has not been built. Run `npm run build` and reload.', 503);
|
||||
}
|
||||
const rel = normalize(decodeURIComponent(c.req.path)).replace(/^([/\\])+/, '');
|
||||
const file = resolvePath(webRoot, rel === '' ? 'index.html' : rel);
|
||||
if (!file.startsWith(webRoot) || !existsSync(file) || !statSync(file).isFile()) return c.text('Not found', 404);
|
||||
const file = staticPath(webRoot, c.req.path);
|
||||
if (!file || !existsSync(file) || !statSync(file).isFile()) return c.text('Not found', 404);
|
||||
return c.body(readFileSync(file), 200, { 'Content-Type': MIME[extname(file)] ?? 'application/octet-stream' });
|
||||
});
|
||||
|
||||
|
||||
@@ -68,3 +68,15 @@ test('earlier tier wins over later tiers', () => {
|
||||
test('unparseable only -> null', () => {
|
||||
assert.equal(chooseCallNumber({ ...none, olEdition: raws('[E]', 'Fic') }, m), null);
|
||||
});
|
||||
|
||||
test('literature class-only number with the author cutter gets a title cutter', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('PS3552.R89') }, { authors: ['Frank Herbert'], title: 'Dune', year: 2010 });
|
||||
assert.equal(r?.callNumber, 'PS3552.R89 D86 2010');
|
||||
const the = chooseCallNumber({ ...none, olEdition: raws('PS3552.R89') }, { authors: ['Frank Herbert'], title: 'The Dune' });
|
||||
assert.equal(the?.callNumber, 'PS3552.R89 D86');
|
||||
});
|
||||
|
||||
test('non-literature class-only numbers still get the author cutter', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.R87') }, { authors: ['Klabnik, Steve'], title: 'The Rust Programming Language', year: 2018 });
|
||||
assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018');
|
||||
});
|
||||
@@ -59,7 +59,9 @@ export function chooseCallNumber(
|
||||
const approximate = tier === 'locTitle' || tier === 'olWork';
|
||||
let { cn, complete } = pickMostFrequent(ps);
|
||||
if (!complete && cn.cutters.length < 3) {
|
||||
const c = cutterFor(mainEntry(meta.authors, meta.title));
|
||||
// Literature (P plus one letter) already carries the author as its first cutter; the next one is the title.
|
||||
const literature = /^P[A-Z]$/.test(cn.letters) && cn.cutters.length >= 1;
|
||||
const c = cutterFor(literature ? meta.title.trim().replace(/^(a|an|the)\s+/i, '') : mainEntry(meta.authors, meta.title));
|
||||
cn = { ...cn, cutters: [...cn.cutters, { letter: c[0]!, digits: c.slice(1) }] };
|
||||
if (meta.year) cn = withYear(cn, meta.year);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeTitle, recordMatches, titlesMatch } from './match.ts';
|
||||
import type { MarcFields } from '../sources/marc.ts';
|
||||
|
||||
const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names });
|
||||
|
||||
test('normalizeTitle', () => {
|
||||
assert.equal(normalizeTitle('The Mythical Man-Month: Essays on Software'), 'mythical man month');
|
||||
assert.equal(normalizeTitle('An Introduction!'), 'introduction');
|
||||
});
|
||||
|
||||
test('titlesMatch: equal or prefix, nothing looser', () => {
|
||||
assert.ok(titlesMatch('The mythical man-month :', 'Mythical Man-Month'));
|
||||
assert.ok(titlesMatch('Dune', 'Dune Messiah'));
|
||||
assert.ok(!titlesMatch('Dunes', 'Dune'));
|
||||
assert.ok(!titlesMatch('', 'Dune'));
|
||||
assert.ok(titlesMatch('Rust', 'The Rust Programming Language'));
|
||||
});
|
||||
|
||||
test('recordMatches needs title and an author surname', () => {
|
||||
const r = rec('The mythical man-month', ['Brooks, Frederick P.']);
|
||||
assert.ok(recordMatches(r, 'The Mythical Man-Month: Essays', 'Frederick P. Brooks'));
|
||||
assert.ok(recordMatches(r, 'Mythical Man-Month', 'Brooks, Frederick P.'));
|
||||
assert.ok(!recordMatches(r, 'Mythical Man-Month', 'Tolkien'));
|
||||
assert.ok(!recordMatches(r, 'Something Else', 'Brooks'));
|
||||
assert.ok(recordMatches(rec('Dune', ['Smith, Bob', 'Herbert, Frank']), 'Dune', 'Frank Herbert'));
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { mainEntry } from '../../shared/cutter.ts';
|
||||
import type { MarcFields } from '../sources/marc.ts';
|
||||
|
||||
const plain = (s: string): string =>
|
||||
s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
||||
|
||||
/** Lower-case, main title only (before any ":"), no punctuation, no leading article. */
|
||||
export function normalizeTitle(title: string): string {
|
||||
return plain(title.split(':')[0]!).replace(/^(a|an|the) /, '');
|
||||
}
|
||||
|
||||
/** Equal, or one is a prefix of the other (a record may carry a longer or shorter main title). */
|
||||
export function titlesMatch(a: string, b: string): boolean {
|
||||
const x = normalizeTitle(a);
|
||||
const y = normalizeTitle(b);
|
||||
if (!x || !y) return false;
|
||||
return x === y || x.startsWith(y + ' ') || y.startsWith(x + ' ');
|
||||
}
|
||||
|
||||
/** Does a LoC record plausibly describe this book? Title must match and a 100/700 name must contain the surname. */
|
||||
export function recordMatches(rec: MarcFields, title: string, author: string): boolean {
|
||||
if (!rec.meta.title || !titlesMatch(rec.meta.title, title)) return false;
|
||||
const surname = plain(mainEntry([author], title));
|
||||
if (!surname) return false;
|
||||
return rec.names.some((n) => (' ' + plain(n) + ' ').includes(' ' + surname + ' '));
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createResolver, TemporaryError } from './resolver.ts';
|
||||
import type { SourceCache } from './resolver.ts';
|
||||
import { createLoc } from '../sources/loc.ts';
|
||||
import { createOpenLibrary } from '../sources/openlibrary.ts';
|
||||
import { fixtureFetch } from '../sources/fixture-fetch.ts';
|
||||
|
||||
function memCache(): SourceCache & { map: Map<string, string> } {
|
||||
@@ -102,22 +104,72 @@ test('cache hits are not delayed by the throttle', async () => {
|
||||
assert.equal(sleeps.length, before);
|
||||
});
|
||||
|
||||
test('two uncached ISBNs are spaced by locIntervalMs', async () => {
|
||||
const f = fixtureFetch();
|
||||
const emptyLoc = '<?xml version="1.0"?><zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:numberOfRecords>0</zs:numberOfRecords></zs:searchRetrieveResponse>';
|
||||
const locSetup = (sleeps: number[]) => {
|
||||
const urls: string[] = [];
|
||||
const fetchStub = (async (u: string) => { urls.push(String(u)); return new Response(emptyLoc, { status: 200 }); }) as typeof fetch;
|
||||
const loc = createLoc({ fetch: fetchStub, cache: memCache(), intervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } });
|
||||
return { loc, urls };
|
||||
};
|
||||
|
||||
test('token bucket: three LoC calls go out at once, the fourth waits one interval', async () => {
|
||||
const sleeps: number[] = [];
|
||||
const r = createResolver({ fetch: f.fetch, cache: memCache(), locIntervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } });
|
||||
await r.resolve({ isbn13: '9781593278281' });
|
||||
await r.resolve({ isbn13: '9780201835953' });
|
||||
const { loc } = locSetup(sleeps);
|
||||
for (const i of ['1', '2', '3']) await loc.byIsbn(i);
|
||||
assert.deepEqual(sleeps, []);
|
||||
await loc.byIsbn('4');
|
||||
assert.equal(sleeps.length, 1);
|
||||
assert.ok(sleeps[0]! > 5000 && sleeps[0]! <= 6000, String(sleeps[0]));
|
||||
});
|
||||
|
||||
test('concurrent resolves are also spaced', async () => {
|
||||
const f = fixtureFetch();
|
||||
test('token bucket: concurrent callers beyond the burst are spaced one interval apart', async () => {
|
||||
const sleeps: number[] = [];
|
||||
const r = createResolver({ fetch: f.fetch, cache: memCache(), locIntervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } });
|
||||
await Promise.all([r.resolve({ isbn13: '9781593278281' }), r.resolve({ isbn13: '9780201835953' })]);
|
||||
assert.equal(sleeps.length, 1);
|
||||
const { loc } = locSetup(sleeps);
|
||||
await Promise.all(['1', '2', '3', '4', '5'].map((i) => loc.byIsbn(i)));
|
||||
assert.equal(sleeps.length, 2);
|
||||
assert.ok(sleeps[0]! > 5000 && sleeps[0]! <= 6000);
|
||||
assert.ok(sleeps[1]! > 11000 && sleeps[1]! <= 12000);
|
||||
});
|
||||
|
||||
test('LoC tries https first and the port-210 endpoint only as the fallback', async () => {
|
||||
const { loc, urls } = locSetup([]);
|
||||
await loc.byIsbn('1');
|
||||
assert.ok(urls[0]!.startsWith('https://lx2.loc.gov/sru/lcdb?'), urls[0]);
|
||||
const urls2: string[] = [];
|
||||
const failFirst = (async (u: string) => {
|
||||
urls2.push(String(u));
|
||||
if (urls2.length === 1) throw new TypeError('down');
|
||||
return new Response(emptyLoc, { status: 200 });
|
||||
}) as typeof fetch;
|
||||
await createLoc({ fetch: failFirst, cache: memCache(), intervalMs: 0, sleep: noSleep }).byIsbn('1');
|
||||
assert.equal(urls2.length, 2);
|
||||
assert.ok(urls2[1]!.startsWith('http://lx2.loc.gov:210/lcdb?'), urls2[1]);
|
||||
});
|
||||
|
||||
test('a LoC response with no record is not cached; one with a record is', async () => {
|
||||
const cache = memCache();
|
||||
const loc = createLoc({ fetch: (async () => new Response(emptyLoc)) as typeof fetch, cache, intervalMs: 0, sleep: noSleep });
|
||||
assert.deepEqual(await loc.byIsbn('9780999999998'), []);
|
||||
assert.equal(cache.map.size, 0);
|
||||
const f = fixtureFetch();
|
||||
const loc2 = createLoc({ fetch: f.fetch, cache, intervalMs: 0, sleep: noSleep });
|
||||
assert.equal((await loc2.byIsbn('9781593278281')).length, 1);
|
||||
assert.equal(cache.map.size, 1);
|
||||
});
|
||||
|
||||
test('an Open Library miss is not cached, so the next lookup asks again', async () => {
|
||||
const cache = memCache();
|
||||
let n = 0;
|
||||
const miss = (async () => { n++; return new Response('{}'); }) as typeof fetch;
|
||||
const ol = createOpenLibrary({ fetch: miss, cache });
|
||||
assert.equal(await ol.edition('9780999999998'), null);
|
||||
assert.equal(await ol.work('9780999999998'), null);
|
||||
assert.equal(cache.map.size, 0);
|
||||
await ol.edition('9780999999998');
|
||||
assert.equal(n, 3);
|
||||
const f = fixtureFetch();
|
||||
await createOpenLibrary({ fetch: f.fetch, cache }).edition('9781593278281');
|
||||
assert.deepEqual([...cache.map.keys()], ['ol-data:9781593278281']);
|
||||
});
|
||||
|
||||
test('LCCN only', async () => {
|
||||
@@ -138,10 +190,10 @@ test('title and author only uses the LoC title tier', async () => {
|
||||
assert.ok(res.meta);
|
||||
});
|
||||
|
||||
test('falls back to the HTTPS SRU endpoint when the first refuses', async () => {
|
||||
test('falls back to the port-210 SRU endpoint when https fails', async () => {
|
||||
const f = fixtureFetch();
|
||||
const wrapped = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
if (String(input).includes(':210')) throw new TypeError('connect ECONNREFUSED');
|
||||
if (String(input).startsWith('https://lx2.loc.gov')) throw new TypeError('connect ECONNREFUSED');
|
||||
return f.fetch(input as string, init);
|
||||
}) as typeof fetch;
|
||||
const res = await createResolver({ fetch: wrapped, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281' });
|
||||
@@ -156,8 +208,50 @@ test('search by title and author', async () => {
|
||||
});
|
||||
|
||||
test('lccn.loc.gov "Record not found" (HTTP 200) is an empty result, not a block page', async () => {
|
||||
const { createLoc } = await import('../sources/loc.ts');
|
||||
const fetchStub = (async () => new Response('<?xml version="1.0" encoding="UTF-8"?><error>Record not found for LCCN: 2003054578.</error>', { status: 200 })) as typeof fetch;
|
||||
const loc = createLoc({ fetch: fetchStub, cache: memCache(), intervalMs: 0, sleep: noSleep });
|
||||
assert.deepEqual(await loc.byLccn('2003054578'), []);
|
||||
});
|
||||
|
||||
test('title tier is skipped when the book has no author', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ title: 'The Mythical Man-Month' });
|
||||
assert.equal(res.callNumber, null);
|
||||
assert.equal(f.locCalls().length, 0);
|
||||
});
|
||||
|
||||
test('title tier ignores records for a different author', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep })
|
||||
.resolve({ title: 'The Mythical Man-Month', author: 'Tolkien, J. R. R.' });
|
||||
assert.ok(f.locCalls().length > 0);
|
||||
assert.equal(res.callNumber, null);
|
||||
});
|
||||
|
||||
test('title tier ignores records for a different title', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep })
|
||||
.resolve({ title: 'The Mythical Dragon', author: 'Frederick Brooks' });
|
||||
assert.equal(res.callNumber, null);
|
||||
});
|
||||
|
||||
function locDown(f: ReturnType<typeof fixtureFetch>): typeof fetch {
|
||||
return (async (input: string | URL | Request, init?: RequestInit) =>
|
||||
/loc\.gov/.test(String(input)) ? new Response('down', { status: 503 }) : f.fetch(input as string, init)) as typeof fetch;
|
||||
}
|
||||
|
||||
test('tolerateLocFailure: Open Library numbers are used when the LoC is down', async () => {
|
||||
const f = fixtureFetch();
|
||||
const r = createResolver({ fetch: locDown(f), cache: memCache(), sleep: noSleep });
|
||||
await assert.rejects(r.resolve({ isbn13: '9780441172719' }), TemporaryError);
|
||||
const res = await r.resolve({ isbn13: '9780441172719' }, { tolerateLocFailure: true });
|
||||
assert.ok(res.callNumber, res.reason ?? '');
|
||||
assert.match(res.callNumber!, /^PS3558/);
|
||||
assert.ok(res.source === 'ol-edition' || res.source === 'ol-work');
|
||||
});
|
||||
|
||||
test('tolerateLocFailure: nothing from Open Library either still fails', async () => {
|
||||
const f = fixtureFetch();
|
||||
const r = createResolver({ fetch: locDown(f), cache: memCache(), sleep: noSleep });
|
||||
await assert.rejects(r.resolve({ isbn13: '9780999999998' }, { tolerateLocFailure: true }), TemporaryError);
|
||||
});
|
||||
@@ -6,13 +6,20 @@ import { createOpenLibrary } from '../sources/openlibrary.ts';
|
||||
import type { OlInfo } from '../sources/openlibrary.ts';
|
||||
import type { MarcFields } from '../sources/marc.ts';
|
||||
import { TemporaryError } from '../sources/http.ts';
|
||||
import { recordMatches } from './match.ts';
|
||||
import type { SourceCache } from '../sources/http.ts';
|
||||
|
||||
export { TemporaryError };
|
||||
export type { SourceCache };
|
||||
|
||||
export interface ResolveOpts {
|
||||
onMeta?: (meta: BookMeta) => void;
|
||||
/** Last-attempt mode: a Library of Congress failure is not fatal; use Open Library's numbers if it has any. */
|
||||
tolerateLocFailure?: boolean;
|
||||
}
|
||||
|
||||
export interface Resolver {
|
||||
resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise<Resolution>;
|
||||
resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution>;
|
||||
search(title: string, author: string): Promise<SearchResult[]>;
|
||||
}
|
||||
|
||||
@@ -50,7 +57,16 @@ export function createResolver(deps: {
|
||||
sleep: deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))),
|
||||
});
|
||||
|
||||
async function resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise<Resolution> {
|
||||
async function resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution> {
|
||||
// In tolerant mode the first LoC failure switches the LoC tiers off for the rest of this lookup.
|
||||
let locError: unknown = null;
|
||||
const locCall = async (fn: () => Promise<MarcFields[]>): Promise<MarcFields[]> => {
|
||||
if (locError) return [];
|
||||
try { return await fn(); } catch (e) {
|
||||
if (opts?.tolerateLocFailure && e instanceof TemporaryError) { locError = e; return []; }
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined;
|
||||
let notified = false;
|
||||
const notify = (m: BookMeta | null) => {
|
||||
@@ -82,11 +98,11 @@ export function createResolver(deps: {
|
||||
let locRecs: MarcFields[] = [];
|
||||
let exactSource: 'loc-isbn' | 'loc-lccn' = 'loc-isbn';
|
||||
if (lccn) {
|
||||
locRecs = await loc.byLccn(lccn);
|
||||
locRecs = await locCall(() => loc.byLccn(lccn));
|
||||
if (locRecs.length > 0) exactSource = 'loc-lccn';
|
||||
}
|
||||
if (isbn && lccOf(locRecs).length === 0) {
|
||||
const recs = await loc.byIsbn(isbn);
|
||||
const recs = await locCall(() => loc.byIsbn(isbn));
|
||||
if (recs.length > 0) { locRecs = recs; exactSource = 'loc-isbn'; }
|
||||
}
|
||||
|
||||
@@ -112,8 +128,11 @@ export function createResolver(deps: {
|
||||
work ??= await getWork(false);
|
||||
const m = metaOf([work?.meta]);
|
||||
const title = m?.title ?? input.title;
|
||||
if (title) {
|
||||
locTitleRecs = await loc.byTitle(title, m?.authors[0] ?? input.author ?? '');
|
||||
const author = m?.authors[0] ?? input.author ?? '';
|
||||
// Without an author a title search cannot be verified, so the tier is skipped.
|
||||
if (title && author) {
|
||||
const found = await locCall(() => loc.byTitle(title, author));
|
||||
locTitleRecs = found.filter((r) => recordMatches(r, title, author));
|
||||
chosen = chooseCallNumber(
|
||||
{ locExact: [], olEdition: [], locTitle: lccOf(locTitleRecs), olWork: [] },
|
||||
forChoose(m), exactSource,
|
||||
@@ -141,6 +160,8 @@ export function createResolver(deps: {
|
||||
confidence: chosen.confidence, source: chosen.source, dewey, reason: null,
|
||||
};
|
||||
}
|
||||
// Open Library had nothing and the LoC could not be asked: report that, not "no number found".
|
||||
if (locError) throw locError;
|
||||
return {
|
||||
meta, callNumber: null, sortKey: null, confidence: null, source: null, dewey,
|
||||
reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library or the Library of Congress',
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { getText, REQUEST_TIMEOUT_MS, TemporaryError } from './http.ts';
|
||||
|
||||
test('every request carries a 15 s abort signal', async () => {
|
||||
assert.equal(REQUEST_TIMEOUT_MS, 15_000);
|
||||
let signal: AbortSignal | undefined;
|
||||
await getText((async (_u: string, init?: RequestInit) => { signal = init?.signal ?? undefined; return new Response('ok'); }) as typeof fetch, 'http://x/');
|
||||
assert.ok(signal instanceof AbortSignal);
|
||||
assert.equal(signal.aborted, false);
|
||||
});
|
||||
|
||||
test('a request that never answers becomes a TemporaryError', async () => {
|
||||
const hang = ((_u: string, init?: RequestInit) => new Promise((_res, rej) => {
|
||||
init!.signal!.addEventListener('abort', () => rej(init!.signal!.reason));
|
||||
})) as typeof fetch;
|
||||
await assert.rejects(getText(hang, 'http://x/', 20), (e: Error) => e instanceof TemporaryError && /Timed out/.test(e.message));
|
||||
});
|
||||
|
||||
test('a body that stalls past the timeout is a TemporaryError too', async () => {
|
||||
const slowBody = (async (_u: string, init?: RequestInit) => {
|
||||
const res = new Response('x');
|
||||
res.text = () => new Promise((_a, rej) => { init!.signal!.addEventListener('abort', () => rej(init!.signal!.reason)); });
|
||||
return res;
|
||||
}) as typeof fetch;
|
||||
await assert.rejects(getText(slowBody, 'http://x/', 20), TemporaryError);
|
||||
});
|
||||
@@ -2,16 +2,27 @@ export class TemporaryError extends Error {}
|
||||
|
||||
export interface SourceCache { get(key: string): string | null; set(key: string, body: string): void }
|
||||
|
||||
/** The database cache can also forget entries, so "Look up again" really asks again. */
|
||||
export interface ForgettableCache extends SourceCache {
|
||||
delete(key: string): void;
|
||||
deletePrefix(prefix: string): void;
|
||||
}
|
||||
|
||||
export const REQUEST_TIMEOUT_MS = 15_000;
|
||||
|
||||
export const USER_AGENT = 'booksorter/0.1 (personal library tool)';
|
||||
|
||||
export interface HttpResult { status: number; body: string }
|
||||
|
||||
/** One GET. Network errors and 5xx/429 become TemporaryError; other statuses are returned. */
|
||||
export async function getText(f: typeof fetch, url: string): Promise<HttpResult> {
|
||||
export async function getText(f: typeof fetch, url: string, timeoutMs = REQUEST_TIMEOUT_MS): Promise<HttpResult> {
|
||||
const signal = AbortSignal.timeout(timeoutMs);
|
||||
const timedOut = (e: unknown) => signal.aborted || (e as Error)?.name === 'TimeoutError';
|
||||
let res: Response;
|
||||
try {
|
||||
res = await f(url, { headers: { 'User-Agent': USER_AGENT } });
|
||||
res = await f(url, { headers: { 'User-Agent': USER_AGENT }, signal });
|
||||
} catch (e) {
|
||||
if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`);
|
||||
throw new TemporaryError(`Network error for ${url}: ${(e as Error).message}`);
|
||||
}
|
||||
if (res.status >= 500 || res.status === 429) throw new TemporaryError(`HTTP ${res.status} from ${url}`);
|
||||
@@ -19,6 +30,7 @@ export async function getText(f: typeof fetch, url: string): Promise<HttpResult>
|
||||
try {
|
||||
body = await res.text();
|
||||
} catch (e) {
|
||||
if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`);
|
||||
throw new TemporaryError(`Network error reading ${url}: ${(e as Error).message}`);
|
||||
}
|
||||
return { status: res.status, body };
|
||||
|
||||
+22
-11
@@ -4,7 +4,9 @@ import type { SourceCache } from './http.ts';
|
||||
import { parseMarcXml } from './marc.ts';
|
||||
import type { MarcFields } from './marc.ts';
|
||||
|
||||
const SRU_URLS = ['http://lx2.loc.gov:210/lcdb', 'https://lx2.loc.gov/sru/lcdb'];
|
||||
// https first; port 210 is blocked on some networks, so plain http on 210 is only the fallback.
|
||||
export const SRU_URLS = ['https://lx2.loc.gov/sru/lcdb', 'http://lx2.loc.gov:210/lcdb'];
|
||||
export const BURST = 3;
|
||||
const MAX_INTERVAL_MS = 60_000;
|
||||
|
||||
export function isLocXml(body: string): boolean {
|
||||
@@ -22,19 +24,26 @@ export function createLoc(deps: {
|
||||
}): Loc {
|
||||
const baseInterval = deps.intervalMs;
|
||||
let interval = baseInterval;
|
||||
let lastSlot: number | null = null;
|
||||
// Token bucket: BURST tokens, one returns every `interval`. A book's two or three calls go out together;
|
||||
// the long-run rate is one per interval. Tokens may go negative: that is a queue of reserved future slots.
|
||||
let tokens = BURST;
|
||||
let lastRefill = Date.now();
|
||||
|
||||
/** Reserve the next request slot synchronously so concurrent callers are spaced too. */
|
||||
/** Take a token synchronously (so concurrent callers queue up too), then wait if it was not yet available. */
|
||||
async function throttle(): Promise<void> {
|
||||
if (interval <= 0) return;
|
||||
const now = Date.now();
|
||||
const slot = lastSlot === null ? now : Math.max(now, lastSlot + interval);
|
||||
lastSlot = slot;
|
||||
if (slot > now) await deps.sleep(slot - now);
|
||||
tokens = Math.min(BURST, tokens + (now - lastRefill) / interval);
|
||||
lastRefill = now;
|
||||
const wait = tokens >= 1 ? 0 : Math.ceil((1 - tokens) * interval);
|
||||
tokens -= 1;
|
||||
if (wait > 0) await deps.sleep(wait);
|
||||
}
|
||||
|
||||
function blocked(): never {
|
||||
interval = Math.min(interval * 2, MAX_INTERVAL_MS);
|
||||
lastSlot = Date.now();
|
||||
tokens = 0; // the next call waits one (doubled) interval from the block
|
||||
lastRefill = Date.now();
|
||||
throw new TemporaryError('Library of Congress returned a block page');
|
||||
}
|
||||
|
||||
@@ -63,8 +72,9 @@ export function createLoc(deps: {
|
||||
if (body === null) throw lastErr;
|
||||
if (!isLocXml(body)) blocked();
|
||||
ok();
|
||||
deps.cache.set(cacheKey, body);
|
||||
return parseMarcXml(body);
|
||||
const recs = parseMarcXml(body);
|
||||
if (recs.length > 0) deps.cache.set(cacheKey, body); // a miss is not cached: asking again may find it
|
||||
return recs;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -79,8 +89,9 @@ export function createLoc(deps: {
|
||||
if (res.status === 404 || /<error>\s*Record not found/i.test(res.body)) { ok(); return []; }
|
||||
if (res.status >= 400 || !isLocXml(res.body)) blocked();
|
||||
ok();
|
||||
deps.cache.set(key, res.body);
|
||||
return parseMarcXml(res.body);
|
||||
const recs = parseMarcXml(res.body);
|
||||
if (recs.length > 0) deps.cache.set(key, res.body);
|
||||
return recs;
|
||||
},
|
||||
byTitle(title, author) {
|
||||
const t = title.replace(/"/g, ' ').trim();
|
||||
|
||||
@@ -10,7 +10,7 @@ test('SRU wrapped record', () => {
|
||||
const [r] = parseMarcXml(fx('loc-isbn-9781593278281.xml'));
|
||||
assert.deepEqual(r!.lcc, [{ raw: 'QA76.73.R87 K53 2018', complete: true }]);
|
||||
assert.match(r!.meta.title!, /Rust/);
|
||||
assert.ok(r!.meta.authors!.some((a) => a.startsWith('Klabnik')));
|
||||
assert.ok(r!.meta.authors!.some((a) => a.endsWith('Klabnik')));
|
||||
assert.equal(r!.meta.year, 2018);
|
||||
assert.ok(r!.lccn);
|
||||
});
|
||||
@@ -53,3 +53,27 @@ test('non-text records (a DVD of the book) contribute no call number', () => {
|
||||
assert.equal(parseMarcXml(rec('g'))[0]!.meta.title, 'Harry Potter');
|
||||
assert.equal(parseMarcXml(rec('a'))[0]!.lcc.length, 1);
|
||||
});
|
||||
|
||||
test('authors: 100 only, dates and commas stripped, shown as Forename Surname', () => {
|
||||
const xml = `<record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<datafield tag="100" ind1="1" ind2=" "><subfield code="a">Herbert, Frank,</subfield><subfield code="d">1920-1986.</subfield></datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0"><subfield code="a">Dune /</subfield></datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" "><subfield code="a">Whelan, Michael,</subfield><subfield code="d">1950-</subfield></datafield></record>`;
|
||||
const [r] = parseMarcXml(xml);
|
||||
assert.deepEqual(r!.meta.authors, ['Frank Herbert']);
|
||||
assert.deepEqual(r!.names, ['Herbert, Frank', 'Whelan, Michael']);
|
||||
});
|
||||
|
||||
test('authors: 700 only stands in when there is no 100; dates inside $a are removed', () => {
|
||||
const xml = `<record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<datafield tag="245" ind1="1" ind2="0"><subfield code="a">Anthology</subfield></datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" "><subfield code="a">Brooks, Frederick P., 1931-</subfield></datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" "><subfield code="a">King, Martin Luther, Jr.,</subfield></datafield></record>`;
|
||||
const [r] = parseMarcXml(xml);
|
||||
assert.deepEqual(r!.meta.authors, ['Frederick P. Brooks', 'Martin Luther King Jr.']);
|
||||
});
|
||||
|
||||
test('the Rust fixture shows a plain author name', () => {
|
||||
const [r] = parseMarcXml(fx('loc-isbn-9781593278281.xml'));
|
||||
assert.ok(r!.meta.authors!.every((a) => !a.includes(',') && !/\d/.test(a)), String(r!.meta.authors));
|
||||
});
|
||||
@@ -7,6 +7,8 @@ export interface MarcFields {
|
||||
lcc: Candidate[];
|
||||
dewey: string | null;
|
||||
meta: Partial<BookMeta>;
|
||||
/** Every 100/700 $a, cleaned but still in "Surname, Forename" form; used to verify title/author matches. */
|
||||
names: string[];
|
||||
}
|
||||
|
||||
type Node = Record<string, unknown>;
|
||||
@@ -60,6 +62,25 @@ function sub(f: Field, code: string): string {
|
||||
|
||||
function uniq(a: string[]): string[] { return [...new Set(a)]; }
|
||||
|
||||
/** Strip trailing punctuation and life dates from a MARC name: "Brooks, Frederick P., 1931-" -> "Brooks, Frederick P." */
|
||||
export function cleanName(raw: string): string {
|
||||
let s = raw.trim();
|
||||
s = s.replace(/[,\s]*\(?\b(?:b\.\s*|d\.\s*|ca\.\s*)?\d{3,4}\??\s*-\s*(?:\d{3,4})?\)?[.,\s]*$/i, '');
|
||||
s = s.replace(/[\s,;:\/]+$/, '');
|
||||
// Keep the period of an initial or Jr./Sr.; drop the ISBD full stop after other words.
|
||||
const last = /([^\s,]+)\.$/.exec(s)?.[1];
|
||||
if (last && last.length > 1 && !/^(jr|sr)$/i.test(last)) s = s.slice(0, -1);
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
/** "Herbert, Frank" -> "Frank Herbert"; "King, Martin Luther, Jr." -> "Martin Luther King Jr."; names without a comma are left alone. */
|
||||
export function displayName(name: string): string {
|
||||
const parts = name.split(',').map((p) => p.trim()).filter(Boolean);
|
||||
if (parts.length < 2) return name.trim();
|
||||
const [surname, forenames, ...suffix] = parts as [string, string, ...string[]];
|
||||
return [forenames, surname, ...suffix].join(' ');
|
||||
}
|
||||
|
||||
export function parseMarcRecord(rec: Node): MarcFields {
|
||||
const fields = fieldsOf(rec);
|
||||
const all = (tag: string) => fields.filter((f) => f.tag === tag);
|
||||
@@ -83,9 +104,10 @@ export function parseMarcRecord(rec: Node): MarcFields {
|
||||
const title = f245 ? trimPunct(sub(f245, 'a')) : '';
|
||||
const subtitle = f245 ? trimPunct(sub(f245, 'b')) : '';
|
||||
|
||||
const authors = uniq(
|
||||
[...all('100'), ...all('700')].map((f) => trimPunct(sub(f, 'a'))).filter(Boolean),
|
||||
);
|
||||
const f100 = all('100');
|
||||
const names = uniq([...f100, ...all('700')].map((f) => cleanName(sub(f, 'a'))).filter(Boolean));
|
||||
// The 100 is the author; 700s (editors, illustrators, co-authors) only stand in when there is none.
|
||||
const authors = uniq((f100.length ? f100 : all('700')).map((f) => cleanName(sub(f, 'a'))).filter(Boolean).map(displayName));
|
||||
|
||||
const pub = all('260')[0] ?? all('264').find((f) => f.ind2 === '1') ?? all('264')[0];
|
||||
const publisher = pub ? trimPunct(sub(pub, 'b')) : '';
|
||||
@@ -101,7 +123,7 @@ export function parseMarcRecord(rec: Node): MarcFields {
|
||||
if (publisher) meta.publisher = publisher;
|
||||
if (ym) meta.year = Number(ym[1]);
|
||||
if (lccn) meta.lccn = lccn;
|
||||
return { lccn, lcc, dewey, meta };
|
||||
return { lccn, lcc, dewey, meta, names };
|
||||
}
|
||||
|
||||
/** Parse every MARC record in an SRU response or a bare LCCN permalink record. */
|
||||
|
||||
@@ -102,7 +102,8 @@ export interface OpenLibrary {
|
||||
}
|
||||
|
||||
export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCache }): OpenLibrary {
|
||||
async function body(key: string | null, url: string): Promise<string> {
|
||||
/** Only a response that actually held a record (per `hasRecord`) is cached, so misses are asked again. */
|
||||
async function body(key: string | null, url: string, hasRecord: (text: string) => boolean = () => true): Promise<string> {
|
||||
if (key) {
|
||||
const hit = deps.cache.get(key);
|
||||
if (hit !== null) return hit;
|
||||
@@ -111,17 +112,17 @@ export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCach
|
||||
// Other 4xx: treat as an empty answer rather than an error.
|
||||
const text = res.status >= 400 ? '{}' : res.body;
|
||||
parseJson(text); // reject HTML overload pages before they reach the cache
|
||||
if (key && res.status < 400) deps.cache.set(key, text);
|
||||
if (key && res.status < 400 && hasRecord(text)) deps.cache.set(key, text);
|
||||
return text;
|
||||
}
|
||||
return {
|
||||
async edition(isbn) {
|
||||
const url = `https://openlibrary.org/api/books?bibkeys=ISBN:${isbn}&jscmd=data&format=json`;
|
||||
return parseEdition(await body(`ol-data:${isbn}`, url), isbn);
|
||||
return parseEdition(await body(`ol-data:${isbn}`, url, (t) => parseEdition(t, isbn) !== null), isbn);
|
||||
},
|
||||
async work(isbn) {
|
||||
const url = `https://openlibrary.org/search.json?isbn=${isbn}&fields=${FIELDS}`;
|
||||
return parseWork(await body(`ol-search:${isbn}`, url));
|
||||
return parseWork(await body(`ol-search:${isbn}`, url, (t) => parseWork(t) !== null));
|
||||
},
|
||||
async search(title, author) {
|
||||
const q = new URLSearchParams();
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { staticPath } from './static.ts';
|
||||
|
||||
test('static paths stay inside the web root', () => {
|
||||
const root = '/srv/dist/web';
|
||||
assert.equal(staticPath(root, '/'), '/srv/dist/web/index.html');
|
||||
assert.equal(staticPath(root, '/assets/app.js'), '/srv/dist/web/assets/app.js');
|
||||
assert.equal(staticPath(root, '/../webx/secret'), '/srv/dist/web/webx/secret');
|
||||
assert.equal(staticPath(root, '..%2Fwebx/secret'), null);
|
||||
assert.equal(staticPath(root, '/%2e%2e/%2e%2e/etc/passwd'), '/srv/dist/web/etc/passwd');
|
||||
assert.equal(staticPath(root, '/bad%zz'), null);
|
||||
assert.equal(staticPath(root, '/a%00b'), null);
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { sep, normalize, resolve as resolvePath } from 'node:path';
|
||||
|
||||
/** Map a request path to a file under `root`, or null when it would leave the root. Does not check existence. */
|
||||
export function staticPath(root: string, urlPath: string): string | null {
|
||||
let decoded: string;
|
||||
try { decoded = decodeURIComponent(urlPath); } catch { return null; }
|
||||
if (decoded.includes('\0')) return null;
|
||||
const rel = normalize(decoded).replace(/^([/\\])+/, '');
|
||||
const file = resolvePath(root, rel === '' ? 'index.html' : rel);
|
||||
// Compare with a trailing separator so a sibling like "<root>x" cannot pass as inside "<root>".
|
||||
return file.startsWith(root.endsWith(sep) ? root : root + sep) ? file : null;
|
||||
}
|
||||
@@ -16,6 +16,7 @@ test('format', () => {
|
||||
['PS-3558.00000000.E63 D8 2005', 'PS3558.E63 D8 2005'],
|
||||
['PZ7.R79835 Har 1998', 'PZ7.R79835 Har 1998'],
|
||||
['qa76.73.r87 k53 2018', 'QA76.73.R87 K53 2018'],
|
||||
['QA76.73.R87x K53 2018', 'QA76.73.R87x K53 2018'],
|
||||
];
|
||||
for (const [i, o] of cases) assert.equal(fmt(i), o, i);
|
||||
});
|
||||
@@ -54,3 +55,19 @@ test('sort order', () => {
|
||||
shuffled.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
|
||||
assert.deepEqual(shuffled, want);
|
||||
});
|
||||
|
||||
test('cutter with one trailing lower-case letter', () => {
|
||||
const cn = parseCallNumber('QA76.73.R87x K53 2018')!;
|
||||
assert.deepEqual(cn.cutters, [{ letter: 'R', digits: '87x' }, { letter: 'K', digits: '53' }]);
|
||||
assert.equal(cn.suffix, '2018');
|
||||
assert.deepEqual(parseCallNumber('QA76.73.C15K47 1988')!.cutters, [{ letter: 'C', digits: '15' }, { letter: 'K', digits: '47' }]);
|
||||
assert.deepEqual(parseCallNumber('qa76.73.r87 k53 2018')!.cutters.map((c) => c.letter + c.digits), ['R87', 'K53']);
|
||||
});
|
||||
|
||||
test('years with a trailing copy letter', () => {
|
||||
const w = (raw: string, y: number) => formatCallNumber(withYear(parseCallNumber(raw)!, y));
|
||||
assert.equal(w('PS3562.E353 B3 1997c', 2005), 'PS3562.E353 B3 2005');
|
||||
assert.equal(w('PS3562.E353 B3 2005b', 2007), 'PS3562.E353 B3 2007');
|
||||
assert.equal(w('PZ7.R79835 Har 1998', 2001), 'PZ7.R79835 Har 2001');
|
||||
assert.equal(hasYear(parseCallNumber('PS3562.E353 B3 1997c')!), true);
|
||||
});
|
||||
@@ -16,7 +16,8 @@ export function parseCallNumber(raw: string): CallNumber | null {
|
||||
let rest = m[4]!;
|
||||
const cutters: { letter: string; digits: string }[] = [];
|
||||
while (cutters.length < 3) {
|
||||
const c = /^\s*\.?\s*([A-Za-z])(\d+)/.exec(rest);
|
||||
// A cutter may carry one trailing lower-case letter ("R87x") when nothing alphanumeric follows it.
|
||||
const c = /^\s*\.?\s*([A-Za-z])(\d+(?:[a-z](?![A-Za-z0-9]))?)/.exec(rest);
|
||||
if (!c) break;
|
||||
cutters.push({ letter: c[1]!.toUpperCase(), digits: c[2]! });
|
||||
rest = rest.slice(c[0].length);
|
||||
@@ -58,7 +59,8 @@ export function cardLines(cn: CallNumber): [string, string] {
|
||||
return [line1, line2];
|
||||
}
|
||||
|
||||
const YEAR = /\b(1[4-9]\d\d|20\d\d)\b/;
|
||||
// A year may carry a copy-letter: 1997c.
|
||||
const YEAR = /\b(1[4-9]\d\d|20\d\d)[a-z]?\b/;
|
||||
export function hasYear(cn: CallNumber): boolean { return YEAR.test(cn.suffix); }
|
||||
|
||||
export function withYear(cn: CallNumber, year: number): CallNumber {
|
||||
|
||||
@@ -16,3 +16,11 @@ test('mainEntry', () => {
|
||||
assert.equal(mainEntry(['Steve Klabnik'], 'x'), 'Klabnik');
|
||||
assert.equal(mainEntry([], 'The Mythical Man-Month'), 'Mythical Man-Month');
|
||||
});
|
||||
|
||||
test('mainEntry: both name forms and suffixes give the surname', () => {
|
||||
assert.equal(mainEntry(['Herbert, Frank'], 'x'), 'Herbert');
|
||||
assert.equal(mainEntry(['Frank Herbert'], 'x'), 'Herbert');
|
||||
assert.equal(mainEntry(['Martin Luther King Jr.'], 'x'), 'King');
|
||||
assert.equal(mainEntry(['King, Martin Luther, Jr.'], 'x'), 'King');
|
||||
assert.equal(mainEntry(['Martin Luther King, Jr.'], 'x'), 'King');
|
||||
});
|
||||
+12
-3
@@ -51,12 +51,21 @@ export function cutterFor(name: string): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
const SUFFIX = /^(jr|sr|ii|iii|iv|esq|md|phd)\.?$/i;
|
||||
|
||||
export function mainEntry(authors: string[], title: string): string {
|
||||
const a = authors[0]?.trim();
|
||||
const a = authors[0]?.trim().replace(/[\s,;]+$/, '');
|
||||
if (a) {
|
||||
if (a.includes(',')) return a.split(',')[0]!.trim();
|
||||
if (a.includes(',')) {
|
||||
const head = a.split(',')[0]!.trim();
|
||||
// "Frank Herbert, Jr." has its suffix after the comma; "Herbert, Frank" has the forenames.
|
||||
const words = head.split(/\s+/);
|
||||
if (words.length > 1 && a.split(',').slice(1).every((p) => SUFFIX.test(p.trim()))) return words[words.length - 1]!;
|
||||
return head;
|
||||
}
|
||||
const words = a.split(/\s+/);
|
||||
return words[words.length - 1]!;
|
||||
while (words.length > 1 && SUFFIX.test(words[words.length - 1]!)) words.pop();
|
||||
return words[words.length - 1]!.replace(/\.$/, '');
|
||||
}
|
||||
return title.trim().replace(/^(a|an|the)\s+/i, '');
|
||||
}
|
||||
@@ -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