Add QR codes to cards, stop inventing call number parts

Cards now carry a QR code holding the book's own record (call number,
title, authors, ISBN, year), and the scanner reads it back to find or
add that book.

Call number selection no longer pads catalogue numbers with generated
cutters. A number is "exact" only when it comes verbatim from a record
for this edition; a bare class is a hint that steers the other-edition
and similar-books lookups; a record fetched by LCCN must list the
book's ISBN to count as this edition. "Look up again" bypasses every
cached result, and shelf order breaks ties by author then title.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 12:53:12 -07:00
1 parent 6cec404e21
commit ad2956e868
56 files changed
+4020 -156

No files matched your search

+31 -1
View File
@@ -2,7 +2,7 @@ import type { Book, SearchResult } from '../shared/types.ts';
import { api } from './api.ts';
import { setLastScan, upsertBook } from './live.ts';
import { beepLow } from './sound.ts';
import { showError } from './toast-store.ts';
import { showError, showToast } from './toast-store.ts';
/** ISBNs with a request in flight: one ISBN is never sent twice at the same time. */
const inflight = new Map<string, Promise<void>>();
@@ -41,3 +41,33 @@ export async function addFromResult(r: SearchResult): Promise<boolean> {
try { added(await api.fromSearch(r)); return true; }
catch (e) { beepLow(); showError(`Could not add "${r.title}": ${(e as Error).message}`); return false; }
}
/** Card texts with a request in flight: one card is never sent twice at the same time. */
const cardsInflight = new Map<string, Promise<void>>();
/**
* A card's QR code was read: find or add the book it describes. Nothing changes on the Scan screen except a
* toast; for a book already in the library the toast can open it in the editor.
*/
export function addFromCard(text: string, open: (id: number) => void): Promise<void> {
let p = cardsInflight.get(text);
if (!p) {
p = (async () => {
try {
const r = await api.fromCard(text);
upsertBook(r.book);
if (r.existed) {
showToast(`Already in your library: ${r.book.title}`, { action: { label: 'Open', run: () => open(r.book.id) } });
} else {
showToast(`Added from its card: ${r.book.title}`);
}
} catch (e) {
beepLow();
showError(`Could not use that card: ${(e as Error).message}`);
}
})();
cardsInflight.set(text, p);
void p.finally(() => cardsInflight.delete(text));
}
return p;
}
+1
View File
@@ -34,6 +34,7 @@ export interface BookPatch { title?: string; authors?: string[]; publisher?: str
export const api = {
scan: (isbn: string) => request<{ book: Book; duplicate: boolean }>('POST', '/api/scan', { isbn }),
fromCard: (text: string) => request<{ book: Book; existed: boolean }>('POST', '/api/books/from-card', { text }),
addLccn: async (lccn: string) => toBook(await request('POST', '/api/books/lccn', { lccn })),
search: (title: string, author: string) =>
request<SearchResult[]>('GET', `/api/search?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`),
+2 -1
View File
@@ -2,11 +2,12 @@ import { cardLines, parseCallNumber } from '../../shared/callnumber.ts';
export const APPROX_TIP = 'Number borrowed from another edition';
export const SIMILAR_TIP = 'Number borrowed from similar books';
export const CARD_TIP = 'Number read from its card, marked approximate there';
/** A call number in two monospaced lines, the way it is printed on the card. `~` marks an approximate one. */
export function CallNo({ value, approximate, source, large }: { value: string | null; approximate?: boolean; source?: string | null; large?: boolean }) {
const similar = source === 'similar';
const tip = similar ? SIMILAR_TIP : APPROX_TIP;
const tip = similar ? SIMILAR_TIP : source === 'card' ? CARD_TIP : APPROX_TIP;
const cls = 'callno' + (large ? ' callno-large' : '');
if (!value) return <span class={cls + ' callno-none'} aria-label="No call number yet">–</span>;
const cn = parseCallNumber(value);
+31
View File
@@ -118,3 +118,34 @@ test('decodeLive and decodeThorough return the ISBN of a readable frame', async
assert.equal(live.out.isbn, CODE);
assert.equal((await decodeThorough(p, null)).isbn, CODE);
});
// --- QR codes on cards ----------------------------------------------------------------------------------
import { qrMatrix } from '../server/pdf/qr.ts';
import { encodeCardCode } from '../shared/cardcode.ts';
function qrPixels(text: string, px: number): Pixels {
const m = qrMatrix(text), q = 4, size = (m.length + 2 * q) * px, data = new Uint8ClampedArray(size * size * 4).fill(255);
for (let r = 0; r < m.length; r++) for (let c = 0; c < m.length; c++) {
if (!m[r]![c]) continue;
for (let y = 0; y < px; y++) for (let x = 0; x < px; x++) {
const i = (((r + q) * px + y) * size + (c + q) * px + x) * 4;
data[i] = data[i + 1] = data[i + 2] = 0;
}
}
return { data, width: size, height: size };
}
const CARD_TEXT = encodeCardCode({ callNumber: 'QA76.73.R87 K53 2018', approximate: false, title: 'Les Misérables', authors: ['Victor Hugo'], isbn13: null, year: null });
test('a card QR code is read live and by the Capture burst', async () => {
const p = qrPixels(CARD_TEXT, 4);
assert.equal((await decodeLive(p, newLiveState())).out.card, CARD_TEXT);
assert.equal((await decodeThorough(p, null)).card, CARD_TEXT);
});
test('a QR code that is not a card is ignored without a trace', async () => {
const p = qrPixels('https://example.com/some/book', 4);
const live = (await decodeLive(p, newLiveState())).out;
assert.deepEqual(live, { isbn: null, other: null, card: null });
assert.deepEqual(await decodeThorough(p, null), { isbn: null, other: null, card: null });
});
+23 -11
View File
@@ -1,10 +1,12 @@
import { readBarcodes } from 'zxing-wasm/reader';
import type { ReaderOptions } from 'zxing-wasm/reader';
import { normalizeIsbn } from '../shared/isbn.ts';
import { parseCardCode } from '../shared/cardcode.ts';
/** RGBA pixels, as from ImageData. Plain data so that this module runs in Node tests. */
export interface Pixels { data: Uint8ClampedArray | Uint8Array; width: number; height: number }
export interface DecodeOutcome { isbn: string | null; other: string | null }
/** `card` is the text of a Booksorter card's QR code; QR codes that are not cards are dropped without a trace. */
export interface DecodeOutcome { isbn: string | null; other: string | null; card: string | null }
// ---- image operations (grey, one byte per pixel) -------------------------------------------------------
@@ -86,6 +88,12 @@ export const BASE: ReaderOptions = {
formats: ['EAN13', 'UPCA'], tryHarder: true, tryDownscale: true, tryRotate: false, tryInvert: false, maxNumberOfSymbols: 2,
};
/**
* QR codes are looked for only on the variants that keep 2D detail (plain and enlarged); the row-averaged ones
* smear a QR code to nothing and stay EAN-only, so their speed and reliability are as before.
*/
const WITH_QR: ReaderOptions = { ...BASE, formats: ['EAN13', 'UPCA', 'QRCode'] };
export interface Variant { name: string; opts: ReaderOptions; prep: (g: Grey) => Grey }
const rowSmooth = (g: Grey) => upscale(rowAverage(g, 6), 2);
@@ -97,18 +105,19 @@ const rowSmooth = (g: Grey) => upscale(rowAverage(g, 6), 2);
export const VARIANTS: Variant[] = [
{ name: 'rows+sharp2x', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => sharpenAcross(rowSmooth(g), 3, 1.2) },
{ name: 'rows2x', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: rowSmooth },
{ name: 'crop', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => g },
{ name: 'up2x', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: g => upscale(g, 2) },
{ name: 'up3x', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => upscale(g, 3) },
{ name: 'crop', opts: { ...WITH_QR, binarizer: 'LocalAverage' }, prep: g => g },
{ name: 'up2x', opts: { ...WITH_QR, binarizer: 'GlobalHistogram' }, prep: g => upscale(g, 2) },
{ name: 'up3x', opts: { ...WITH_QR, binarizer: 'LocalAverage' }, prep: g => upscale(g, 3) },
];
/** For the whole frame, which is too big to enlarge: no upscaling. */
export const WHOLE_VARIANTS: Variant[] = [
{ name: 'whole', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => g },
{ name: 'whole', opts: { ...WITH_QR, binarizer: 'LocalAverage' }, prep: g => g },
{ name: 'whole-rows', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: g => sharpenAcross(rowAverage(g, 6), 1, 1) },
];
function judge(codes: { text: string }[], into: DecodeOutcome): void {
function judge(codes: { text: string; format?: string }[], into: DecodeOutcome): void {
for (const c of codes) {
if (c.format === 'QRCode') { if (parseCardCode(c.text)) into.card ??= c.text; continue; }
const isbn = /^\d{13}$/.test(c.text) ? normalizeIsbn(c.text) : null;
if (isbn) into.isbn ??= isbn; else into.other ??= c.text;
}
@@ -118,6 +127,9 @@ async function tryVariant(g: Grey, v: Variant, extra: ReaderOptions, into: Decod
judge(await readBarcodes(toImage(v.prep(g)) as ImageData, { ...v.opts, ...extra }), into);
}
/** A book ISBN or a card was read: nothing more to try on this frame. */
const found = (o: DecodeOutcome): boolean => o.isbn !== null || o.card !== null;
export interface LiveState { round: number; cursor: number }
export const newLiveState = (): LiveState => ({ round: 0, cursor: 0 });
/** Every FULL_EVERY-th live round looks at the whole frame instead of the crop. */
@@ -134,14 +146,14 @@ export const wantsFull = (st: LiveState): boolean => st.round % FULL_EVERY === F
* stopped, so that slow machines still get through every variant across frames.
*/
export async function decodeLive(p: Pixels, st: LiveState, now: () => number = () => performance.now()): Promise<{ out: DecodeOutcome; state: LiveState }> {
const out: DecodeOutcome = { isbn: null, other: null };
const out: DecodeOutcome = { isbn: null, other: null, card: null };
const began = now(), g = toGrey(p);
let cursor = st.cursor;
if (wantsFull(st)) {
for (const v of WHOLE_VARIANTS) if (!out.isbn) await tryVariant(g, v, {}, out);
for (const v of WHOLE_VARIANTS) if (!found(out)) await tryVariant(g, v, {}, out);
} else {
await tryVariant(g, VARIANTS[0]!, {}, out);
for (let i = 0; i < REST.length && !out.isbn && now() - began <= LIVE_BUDGET_MS; i++) {
for (let i = 0; i < REST.length && !found(out) && now() - began <= LIVE_BUDGET_MS; i++) {
await tryVariant(g, REST[cursor]!, {}, out);
cursor = (cursor + 1) % REST.length;
}
@@ -151,12 +163,12 @@ export async function decodeLive(p: Pixels, st: LiveState, now: () => number = (
/** Everything we have on one frame, for the Capture burst: every variant, rotated too, crop then whole frame. */
export async function decodeThorough(crop: Pixels, whole: Pixels | null): Promise<DecodeOutcome> {
const out: DecodeOutcome = { isbn: null, other: null };
const out: DecodeOutcome = { isbn: null, other: null, card: null };
for (const p of whole ? [crop, whole] : [crop]) {
const g = toGrey(p);
for (const v of p === crop ? VARIANTS : WHOLE_VARIANTS) {
await tryVariant(g, v, { tryRotate: true, tryInvert: true }, out);
if (out.isbn) return out;
if (found(out)) return out;
}
}
return out;
+11 -1
View File
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
import { acceptCard, acceptRead, markCardEmitted, markEmitted, newReadState } from './readstate.ts';
const ISBN = '9780306406157';
@@ -46,3 +46,13 @@ test('markEmitted silences the loop for 5 s', () => {
assert.equal(acceptRead(s, ISBN, 2000).emit, null);
assert.equal(acceptRead(s, ISBN, 6100).emit, ISBN);
});
test('a card is announced once per 5 s per text, independently of ISBNs', () => {
let r = acceptCard(newReadState(), 'card A', 0);
assert.equal(r.emit, 'card A');
r = acceptCard(r.state, 'card A', 4900);
assert.equal(r.emit, null);
assert.equal(acceptCard(r.state, 'card B', 4900).emit, 'card B');
assert.equal(acceptCard(r.state, 'card A', 5100).emit, 'card A');
assert.equal(acceptCard(markCardEmitted(newReadState(), 'card A', 0), 'card A', 100).emit, null);
});
+12
View File
@@ -35,3 +35,15 @@ export function acceptRead(
export function markEmitted(state: ReadState, isbn: string, now: number): ReadState {
return { ...state, emittedAt: { ...state.emittedAt, [isbn]: now } };
}
/** A card's QR code, repeat-protected like an ISBN: once per REPEAT_MS per distinct text. */
export function acceptCard(state: ReadState, text: string, now: number): { state: ReadState; emit: string | null } {
const key = 'card:' + text;
const last = state.emittedAt[key];
if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null };
return { state: { ...state, emittedAt: { ...state.emittedAt, [key]: now } }, emit: text };
}
export function markCardEmitted(state: ReadState, text: string, now: number): ReadState {
return { ...state, emittedAt: { ...state.emittedAt, ['card:' + text]: now } };
}
+15 -4
View File
@@ -1,5 +1,5 @@
import { prepareZXingModule } from 'zxing-wasm/reader';
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
import { acceptCard, acceptRead, markCardEmitted, markEmitted, newReadState } from './readstate.ts';
import { cropRect } from './frame.ts';
import { decodeLive, decodeThorough, newLiveState, sharpness, wantsFull } from './decode.ts';
import type { DecodeOutcome, Pixels } from './decode.ts';
@@ -62,6 +62,8 @@ function nextFrame(video: HTMLVideoElement, fallbackMs: number): Promise<void> {
export interface ScannerHandlers {
/** A valid ISBN-13 was read (at most once per 5 seconds per book). */
onIsbn(isbn13: string): void;
/** A Booksorter card's QR code was read (at most once per 5 seconds per card). */
onCard(text: 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). */
@@ -148,6 +150,11 @@ export async function startScanner(
const r = await decodeLive(grab(video, c.x, c.y, c.w, c.h), live);
live = r.state;
if (stopped || burst) { /* a burst took over: drop this result */ } else {
if (r.out.card) {
const a = acceptCard(state, r.out.card, Date.now());
state = a.state;
if (a.emit) handlers.onCard(a.emit);
}
for (const code of [r.out.isbn, r.out.other]) {
if (!code) continue;
const a = acceptRead(state, code, Date.now());
@@ -180,13 +187,17 @@ export async function startScanner(
if (!best || score > best.score) best = { full, score };
const out = await decodeThorough(crop, full);
other ??= out.other;
if (out.card) {
state = markCardEmitted(state, out.card, Date.now());
return { isbn: null, other, card: out.card, saved: null };
}
if (out.isbn) {
state = markEmitted(state, out.isbn, Date.now());
return { isbn: out.isbn, other, saved: null };
return { isbn: out.isbn, other, card: null, saved: null };
}
}
if (other) return { isbn: null, other, saved: null };
return { isbn: null, other: null, saved: best ? await saveFailed(best.full) : null };
if (other) return { isbn: null, other, card: null, saved: null };
return { isbn: null, other: null, card: null, saved: best ? await saveFailed(best.full) : null };
} finally {
burst = false;
}
+2 -9
View File
@@ -1,4 +1,5 @@
import type { Book } from '../shared/types.ts';
import { compareShelf } from '../shared/shelf.ts';
export interface BookState { byId: Record<number, Book> }
export type BookAction =
@@ -25,15 +26,7 @@ export function reduce(state: BookState, action: BookAction): BookState {
}
}
/** Shelf order: by sortKey, books without one last, then title. */
export function compareShelf(a: Book, b: Book): number {
if (a.sortKey !== b.sortKey) {
if (a.sortKey === null) return 1;
if (b.sortKey === null) return -1;
return a.sortKey < b.sortKey ? -1 : 1;
}
return a.title.localeCompare(b.title);
}
export { compareShelf };
export function shelfOrder(state: BookState): Book[] {
return Object.values(state.byId).sort(compareShelf);
+14 -4
View File
@@ -37,7 +37,7 @@ const CameraIcon = () => (
* The live camera with its controls on a bar along the bottom edge. `onIsbn` gets every ISBN it reads.
* `captureRef.current` is set to a function that takes one careful picture (it returns false when the camera is off).
*/
export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void; captureRef: { current: (() => boolean) | null } }) {
export function Camera({ onIsbn, onCard, captureRef }: { onIsbn: (isbn: string) => void; onCard: (text: string) => void; captureRef: { current: (() => boolean) | null } }) {
const cam = useCamera();
const video = useRef<HTMLVideoElement>(null);
const scanner = useRef<Scanner | null>(null);
@@ -65,9 +65,18 @@ export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void;
say(`Read ${isbn}`, 'ok');
onIsbn(isbn);
};
const handlers = useRef({ onIsbn: gotIsbn, onOther: () => {}, onEnded: () => {} });
const gotCard = (text: string) => {
beepAccept();
setFlash(true);
clearTimeout(flashTimer.current);
flashTimer.current = setTimeout(() => setFlash(false), 600);
say('Read a card', 'ok');
onCard(text);
};
const handlers = useRef({ onIsbn: gotIsbn, onCard: gotCard, onOther: () => {}, onEnded: () => {} });
handlers.current = {
onIsbn: gotIsbn,
onCard: gotCard,
onOther: () => { beepLow(); say('That barcode is not an ISBN', 'warn'); },
onEnded: () => {
scanner.current = null; setState('off'); setStatus(null); updateCamera({ resolution: '' });
@@ -91,7 +100,7 @@ export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void;
setState('starting'); setProblem('');
try {
const sc = await startScanner(video.current, getCamera().deviceId || undefined, {
onIsbn: i => handlers.current.onIsbn(i), onOther: c => handlers.current.onOther(), onEnded: () => handlers.current.onEnded(),
onIsbn: i => handlers.current.onIsbn(i), onCard: t => handlers.current.onCard(t), onOther: c => handlers.current.onOther(), onEnded: () => handlers.current.onEnded(),
}, ac.signal);
if (!sc) return; // turned off or left the screen while the permission prompt was open
if (ac.signal.aborted) { sc.stop(); return; }
@@ -121,7 +130,8 @@ export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void;
try {
const r = await sc.capture(n => say(`Trying… ${n} frames`, 'info', true));
if (scanner.current !== sc) return;
if (r.isbn) gotIsbn(r.isbn);
if (r.card) gotCard(r.card);
else if (r.isbn) gotIsbn(r.isbn);
else if (r.other) { beepLow(); say('That barcode is not an ISBN', 'warn', true); }
else { beepLow(); say(r.saved ? NOT_FOUND_SAVED : NOT_FOUND, 'warn', true); }
} catch {
+3 -2
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef } from 'preact/hooks';
import { addByIsbn } from '../actions.ts';
import { addByIsbn, addFromCard } from '../actions.ts';
import { dialogOpen } from '../dialog.ts';
import { unlockAudio } from '../sound.ts';
import type { EditorTarget } from '../components/Editor.tsx';
@@ -53,7 +53,8 @@ export function Scan({ onEdit }: { onEdit: (t: EditorTarget) => void }) {
return (
<div class="scan">
<div class="scan-left">
<Camera captureRef={capture} onIsbn={isbn => { void addByIsbn(isbn); }} />
<Camera captureRef={capture} onIsbn={isbn => { void addByIsbn(isbn); }}
onCard={text => { void addFromCard(text, id => onEdit({ kind: 'edit', id })); }} />
<LastScan onFix={fix} />
<Entry inputRef={entry} onEdit={onEdit} />
</div>