Print the subject hierarchy as a tree on cards, remove the QR code

Each card now shows, under the call number, the Library of Congress
outline levels for its class (from the published outline, down to the
narrowest range) followed by the place or topic from the catalogue
record's subject heading, one level per line. Existing books get the
subject part filled in by a background job at startup that changes
nothing else about them.

The QR code and everything that read it are removed; the subjects line
on the card is replaced by the tree.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 14:06:50 -07:00
1 parent c9b2c2e8c9
commit 7ae1bcef0a
46 files changed
+8591 -545

No files matched your search

-2
View File
@@ -24,8 +24,6 @@ The header has **Scan**, **Library (N)** and a gear for settings.
1. Open the PDF and print at **Actual size / 100%** (never "Fit to page"), **single-sided**, through the **manual feed slot**.
2. When the cards came out correctly, answer **Yes, clear them** so they are not printed twice.
Each card also carries a QR code (about 1.25 inches square, above the ISBN line). It holds the book's record as plain text: call number, title, the first two authors, ISBN and year, so a card still means something if the database is lost, and a phone camera shows it as readable text. Hold a card up to the scanner: the book is found in your library, or added from the card (already resolved, and not queued for printing again). Cards for books with no barcode can be scanned this way too. Other QR codes, such as those on a back cover, are ignored.
**Library** shows every book in shelf order, grouped by main class, with search and a *Needs attention* filter. Click a book to edit it, print another card, look it up again, or delete it. A number marked `~` was borrowed from another edition or from similar books; check those.
**How a number is found.** A number is only ever printed without `~` when it came word for word from a catalogue record (Library of Congress, then Open Library) for this exact ISBN or LCCN, and has at least one cutter. Nothing is generated for those. A record that gives only a bare class (such as `GV199.42`, which in that class needs a place cutter next, not an author) is treated as a hint: the app then looks at other editions of the same book in that class, then at similar books in that class, and borrows from them with `~`. If it finds nothing better it prints the bare class and this edition's year with `~`. Books that share a number are shelved by the first author's surname, then title. **Look up again** ignores every saved answer and asks the catalogues afresh.
+2 -8
View File
@@ -7,6 +7,7 @@
"": {
"name": "booksorter",
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"@hono/node-server": "^2.1.9",
"@pdf-lib/fontkit": "^1.1.1",
@@ -15,8 +16,7 @@
"fast-xml-parser": "^5.12.1",
"hono": "^4.13.19",
"pdf-lib": "^1.17.1",
"preact": "^11.2.0",
"qrcode-generator": "^2.0.4"
"preact": "^11.2.0"
},
"devDependencies": {
"@types/node": "^26.6.6",
@@ -1053,12 +1053,6 @@
}
}
},
"node_modules/qrcode-generator": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
"integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==",
"license": "MIT"
},
"node_modules/strnum": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.5.1.tgz",
+2 -3
View File
@@ -5,7 +5,7 @@
"private": true,
"type": "module",
"scripts": {
"test": "node --test \"src/**/*.test.ts\"",
"test": "node --test \"src/**/*.test.ts\" \"scripts/**/*.test.ts\"",
"typecheck": "tsc --noEmit",
"build": "node scripts/build-web.ts",
"start": "npm run build && node src/server/main.ts"
@@ -18,8 +18,7 @@
"fast-xml-parser": "^5.12.1",
"hono": "^4.13.19",
"pdf-lib": "^1.17.1",
"preact": "^11.2.0",
"qrcode-generator": "^2.0.4"
"preact": "^11.2.0"
},
"devDependencies": {
"@types/node": "^26.6.6",
+30 -3
View File
@@ -1,17 +1,21 @@
// Generates src/shared/lcc-outline.ts from the Library of Congress Classification
// Outline (https://www.loc.gov/catdir/cpso/lcco/), a US government publication.
// Generates src/shared/lcc-outline.ts (main classes and subclasses, used by the web app too) and
// src/server/lcc-ranges.ts (every nested number range with its caption, server only) from the Library of
// Congress Classification Outline (https://www.loc.gov/catdir/cpso/lcco/), a US government publication.
// Usage: node scripts/gen-lcc-outline.ts [cacheDir] (or env LCC_CACHE_DIR)
// Requires `pdftotext` (poppler). Downloads are cached outside the repo.
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { parseOutlineText } from './lcc-parse.ts';
import type { Range } from './lcc-parse.ts';
const INDEX = 'https://www.loc.gov/catdir/cpso/lcco/';
const UA = 'Mozilla/5.0 (compatible; lcc-outline-generator)';
const cache = process.argv[2] ?? process.env.LCC_CACHE_DIR ?? join(tmpdir(), 'lcc-outline-cache');
mkdirSync(cache, { recursive: true });
const out = new URL('../src/shared/lcc-outline.ts', import.meta.url);
const outRanges = new URL('../src/server/lcc-ranges.ts', import.meta.url);
// Fix-ups applied to names after sentence-casing / extraction.
const MAIN_FIXES: Record<string, string> = {
@@ -61,12 +65,17 @@ if (hrefs.length < 20) throw new Error(`expected ~20 class PDFs, found ${hrefs.l
const MAIN: Record<string, string> = {};
const SUB: Record<string, string> = {};
const RANGES = new Map<string, Range[]>();
for (const href of hrefs) {
const name = href.split('/').pop()!;
const pdf = join(cache, name);
await get(new URL(href, INDEX).href, name);
const lines = execFileSync('pdftotext', ['-layout', pdf, '-'], { encoding: 'utf8', maxBuffer: 1 << 28 }).split('\n');
const text = execFileSync('pdftotext', ['-layout', pdf, '-'], { encoding: 'utf8', maxBuffer: 1 << 28 });
const lines = text.split('\n');
const parsed = parseOutlineText(text);
for (const [letters, rows] of parsed.ranges) RANGES.set(letters, rows);
for (const p of parsed.problems) console.warn(`${name}: skipped "${p}"`);
// Title: "CLASS Q - SCIENCE", possibly wrapped onto following lines.
const ti = lines.findIndex((l) => /^\s*CLASS [A-Z](-[A-Z])? - /.test(l));
@@ -116,3 +125,21 @@ export function classNames(letters: string): { className: string | null; subclas
`;
writeFileSync(out, src);
console.log(`wrote ${Object.keys(MAIN).length} main classes, ${Object.keys(SUB).length} subclasses`);
const rangesSrc = `// GENERATED by scripts/gen-lcc-outline.ts -- do not edit by hand.
// Source: Library of Congress Classification Outline, ${INDEX}
// (a US government publication). Re-run: node scripts/gen-lcc-outline.ts
// Server only: the web app does not import this file.
/** [lo, hi, caption], or [lo, hi, caption, cutterLo, cutterHi] for a range bounded by cutters. Captions are verbatim. */
export type OutlineRange = [lo: number, hi: number, caption: string, cutterLo?: string, cutterHi?: string];
/** Every range of the outline by class letters, in outline order (a range comes before the ranges nested in it). */
export const OUTLINE_RANGES: Record<string, OutlineRange[]> = {
${[...RANGES.keys()].sort().map((k) => ` ${k}: [\n${RANGES.get(k)!.map((r) => ' ' + JSON.stringify(r)).join(',\n')},\n ],`).join('\n')}
};
`;
writeFileSync(outRanges, rangesSrc);
const perClass: Record<string, number> = {};
for (const [k, rows] of RANGES) perClass[k[0]!] = (perClass[k[0]!] ?? 0) + rows.length;
console.log(`wrote ${[...RANGES.values()].reduce((n, r) => n + r.length, 0)} ranges in ${RANGES.size} subclasses; per main class: ${Object.entries(perClass).map(([k, n]) => k + '=' + n).join(' ')}`);
+67
View File
@@ -0,0 +1,67 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { cleanCaption, parseBounds, parseOutlineText } from './lcc-parse.ts';
test('number ranges in every form the outline uses', () => {
assert.deepEqual(parseBounds('191.2-200.66'), { lo: 191.2, hi: 200.66 });
assert.deepEqual(parseBounds('1201.5'), { lo: 1201.5, hi: 1201.5 });
assert.deepEqual(parseBounds('1115-(1193)'), { lo: 1115, hi: 1193 });
assert.deepEqual(parseBounds('(1)-1281'), { lo: 1, hi: 1281 });
assert.deepEqual(parseBounds('1569.C2'), { lo: 1569, hi: 1569, cutterLo: 'C2', cutterHi: 'C2' });
assert.deepEqual(parseBounds('469.M21-.M38'), { lo: 469, hi: 469, cutterLo: 'M21', cutterHi: 'M38' });
assert.deepEqual(parseBounds('990.U45-U46', 'DA'), { lo: 990, hi: 990, cutterLo: 'U45', cutterHi: 'U46' });
assert.deepEqual(parseBounds('1.A5-3.3'), { lo: 1, hi: 3.3, cutterLo: 'A5' });
assert.deepEqual(parseBounds('12.5-.9'), { lo: 12.5, hi: 12.9 });
assert.deepEqual(parseBounds('1003-Z1005.5', 'Z'), { lo: 1003, hi: 1005.5 });
assert.equal(parseBounds('4440-4406'), null);
assert.equal(parseBounds('274.5-6'), null);
});
test('captions: wraps joined, notes dropped, headers and breaks ignored, nesting kept in order', () => {
const text = [
' LIBRARY OF CONGRESS CLASSIFICATION OUTLINE',
'Subclass GV Recreation. Leisure',
'Subclass GV',
'',
'GV1-1860 Recreation. Leisure',
'GV191.2-200.66 Outdoor life. Outdoor recreation',
'GV199-199.62 Hiking. Pedestrian tours',
'GV346-351.5 School and college athletics. Intramural',
' and interscholastic athletics',
'GV401-433 Physical education facilities.',
' Including gymnasiums, athletic fields,',
' playgrounds, etc.',
'\fGV1470-1511 Parties. Party games and stunts',
'GV1201.5 Hobbies (General)',
'Subclass GX',
'GX5 Heading',
' Individual states',
].join('\n');
const { ranges, problems } = parseOutlineText(text);
assert.deepEqual(problems, []);
assert.deepEqual(ranges.get('GV'), [
[1, 1860, 'Recreation. Leisure'],
[191.2, 200.66, 'Outdoor life. Outdoor recreation'],
[199, 199.62, 'Hiking. Pedestrian tours'],
[346, 351.5, 'School and college athletics. Intramural and interscholastic athletics'],
[401, 433, 'Physical education facilities'],
[1470, 1511, 'Parties. Party games and stunts'],
[1201.5, 1201.5, 'Hobbies (General)'],
]);
assert.deepEqual(ranges.get('GX'), [[5, 5, 'Heading']]);
});
test('unreadable ranges are reported, not guessed', () => {
const { ranges, problems } = parseOutlineText('Subclass KZ\nKZD4440-4406 Liability for accidents\nKZ5 Fine\n');
assert.equal(problems.length, 1);
assert.deepEqual(ranges.get('KZ'), [[5, 5, 'Fine']]);
});
test('caption clean-up trims debris only', () => {
assert.equal(cleanCaption(' Law and\n order , '), 'Law and order');
assert.equal(cleanCaption('Museology. Museum methods, technique, etc.'), 'Museology. Museum methods, technique, etc.');
assert.equal(cleanCaption('Purānas .'), 'Purānas');
assert.equal(cleanCaption('1789­'), '1789-');
assert.equal(cleanCaption('1871- . Later 19th century'), '1871- . Later 19th century');
assert.equal(cleanCaption('Persian wars, 499-479 B.C.'), 'Persian wars, 499-479 B.C.');
});
+112
View File
@@ -0,0 +1,112 @@
// Parses the text of one Library of Congress Classification Outline PDF (from `pdftotext -layout`)
// into its number ranges with their captions. Used by gen-lcc-outline.ts; no I/O here.
/** [lo, hi, caption] or, for ranges bounded by cutters, [lo, hi, caption, cutterLo, cutterHi]. */
export type Range = [lo: number, hi: number, caption: string, cutterLo?: string, cutterHi?: string];
export interface Parsed {
/** Ranges by class letters (PS, GV, KBM), in the order they appear in the outline. */
ranges: Map<string, Range[]>;
/** Lines that looked like a range but could not be read; reported by the generator. */
problems: string[];
}
const NUM = String.raw`\(?(\d+(?:\.\d+)?)\)?`;
const START = new RegExp(String.raw`^${NUM}(?:\.([A-Z]\d*))?$`);
const END_NUMBER = new RegExp(String.raw`^([A-Z]{1,3}(?=[\d(]))?${NUM}(?:\.([A-Z]\d*))?$`);
const END_DECIMAL = /^\.(\d+)$/;
const END_CUTTER = /^\.?([A-Z]\d*)$/;
const NOTE = /^(Including|Class |For |See |Subarrange|Cf\.)/;
export interface Bounds { lo: number; hi: number; cutterLo?: string; cutterHi?: string }
/** The number part of a code such as `191.2-200.66`, `1569.C2`, `469.M21-.M38` or `1115-(1193)`; null if unreadable. */
export function parseBounds(code: string, letters = ''): Bounds | null {
const dash = code.indexOf('-');
const startText = dash < 0 ? code : code.slice(0, dash);
const s = START.exec(startText);
if (!s) return null;
const lo = Number(s[1]);
const out: Bounds = { lo, hi: lo };
if (s[2]) out.cutterLo = s[2];
if (dash < 0) { if (s[2]) out.cutterHi = s[2]; return out; }
const endText = code.slice(dash + 1);
let m: RegExpExecArray | null;
// "U46" after "DA990.U45" is a cutter; "Z1003.5" after "Z1" repeats the class letters. Tell them apart by the letters.
if ((m = END_NUMBER.exec(endText)) && (!m[1] || m[1] === letters) && Number(m[2]) >= lo) {
out.hi = Number(m[2]);
if (m[3]) out.cutterHi = m[3];
} else if ((m = END_DECIMAL.exec(endText))) {
out.hi = Number(`${Math.trunc(lo)}.${m[1]}`);
} else if ((m = END_CUTTER.exec(endText))) {
out.cutterHi = m[1]!;
} else return null;
if (out.hi < out.lo) return null;
return out;
}
/** A caption as published: one line of text, no stray marks; a lone full stop (a diacritic dot the PDF set on its own line) is dropped. */
export function cleanCaption(raw: string): string {
let s = raw.replace(/­/g, '-').replace(/\s+/g, ' ').trim();
s = s.replace(/(?<!-) \.(?= |$)/g, '').replace(/\s+/g, ' ').trim();
// Trailing debris only: commas, semicolons, colons and a lone full stop after a word; "etc." and "Co." style stops stay.
s = s.replace(/[,;:\s]+$/, '');
if (/[a-z]{3,}\.$/.test(s) && !/\betc\.$/.test(s)) s = s.slice(0, -1);
return s;
}
export function parseOutlineText(text: string): Parsed {
const ranges = new Map<string, Range[]>();
const problems: string[] = [];
let started = false;
let cur: { letters: string; index: number; capCol: number; caption: string } | null = null;
let inNote = false;
const finish = () => {
if (!cur) return;
const list = ranges.get(cur.letters)!;
const r = list[cur.index]!;
r[2] = cleanCaption(cur.caption);
cur = null;
};
for (const rawLine of text.split('\n')) {
const line = rawLine.replace(/\f/g, '').replace(/\s+$/, '');
if (/^(?:Sub)?[Cc]lass [A-Z]{1,3}\s*$/.test(line)) { finish(); started = true; inNote = false; continue; }
if (!started || !line.trim()) continue;
const codeLine = /^([A-Z]{1,3})((?:\(\d+\)|\d)\S*)\s+(\S.*)$/.exec(line) ?? /^([A-Z]{1,3})((?:\(\d+\)|\d)\S*)\s*$/.exec(line);
if (codeLine) {
finish();
inNote = false;
const [, letters, code, caption = ''] = codeLine as unknown as [string, string, string, string?];
const b = parseBounds(code, letters);
if (!b) { problems.push(line.trim()); continue; }
if (!ranges.has(letters)) ranges.set(letters, []);
const list = ranges.get(letters)!;
const row: Range = [b.lo, b.hi, ''];
if (b.cutterLo !== undefined || b.cutterHi !== undefined) { row[3] = b.cutterLo ?? ''; row[4] = b.cutterHi ?? ''; }
list.push(row);
cur = { letters, index: list.length - 1, capCol: line.length - caption.length, caption };
continue;
}
// Anything else: a wrapped caption, a note under a caption, or a heading without a range.
const indent = line.length - line.trimStart().length;
const t = line.trim();
if (!cur) continue;
if (indent <= cur.capCol) { finish(); inNote = false; continue; } // a heading line, not part of the range above
if (inNote) continue;
if (NOTE.test(t)) { inNote = true; continue; }
cur.caption += ' ' + t;
}
finish();
for (const [letters, list] of ranges) {
ranges.set(letters, list.filter((r) => {
if (r[2]) return true;
problems.push(`${letters}${r[0]}-${r[1]}: empty caption`);
return false;
}));
}
return { ranges, problems };
}
+19 -39
View File
@@ -17,7 +17,7 @@ function setupRecording(fresh: (boolean | undefined)[]) {
function setup(resolve: (i?: any, o?: any) => Promise<Resolution> = async () => found, port?: number) {
const db = openDb(':memory:');
const events = createEventBus();
const resolver = { resolve, search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
const resolver = { resolve, tail: async () => [], search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0], log: () => {} });
const pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = [];
const app = createApp({
@@ -134,8 +134,7 @@ test('print passes cards in shelf order and honours start; confirm clears queue'
const call = pdfCalls[0]!;
assert.deepEqual(call.cards.map((c) => c.title), ['Approx', 'First', 'Second']);
assert.equal(call.opts.startPosition, 2);
assert.equal(call.cards[1]!.className, 'Class P');
assert.equal(call.cards[1]!.subclassName, 'Sub PS');
assert.deepEqual(call.cards[1]!.hierarchy, { outline: ['Class P', 'Sub PS'], tail: [] });
assert.equal(call.cards[0]!.approximate, true);
assert.equal(call.cards[1]!.approximate, false);
const ids = r.headers.get('x-book-ids')!.split(',').map(Number);
@@ -234,7 +233,7 @@ test('debug capture: saves a PNG, keeps the newest 30, refuses other bodies', as
const dir = mkdtempSync(join(tmpdir(), 'captures-'));
try {
const db = openDb(':memory:');
const resolver = { resolve: async () => found, search: async () => [] };
const resolver = { resolve: async () => found, tail: async () => [], search: async () => [] };
const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} });
const app = createApp({
db, jobs, resolver, capturesDir: join(dir, 'captures'),
@@ -254,41 +253,6 @@ test('debug capture: saves a PNG, keeps the newest 30, refuses other bodies', as
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('from-card: parses, adds a resolved book that is not queued, then finds it again', async () => {
const { req, db } = setup();
assert.equal((await req('POST', '/api/books/from-card', { text: 'https://example.com' })).status, 400);
assert.equal((await req('POST', '/api/books/from-card', {})).status, 400);
const text = 'PQ2230.A1 H8 1987 ~\nLes Misérables\nVictor Hugo\nbooksorter 1';
const first = await (await req('POST', '/api/books/from-card', { text })).json() as any;
assert.equal(first.existed, false);
assert.equal(first.book.status, 'resolved');
assert.equal(first.book.source, 'card');
assert.equal(first.book.confidence, 'approximate');
assert.equal(first.book.inQueue, false);
assert.equal(first.book.callNumber, 'PQ2230.A1 H8 1987');
assert.deepEqual(first.book.authors, ['Victor Hugo']);
// same title (any case, padded) with the same call number is the same book; a different call number is not
const again = await (await req('POST', '/api/books/from-card', { text: text.replace('Les Misérables', 'LES MISÉRABLES ') })).json() as any;
assert.equal(again.existed, true);
assert.equal(again.book.id, first.book.id);
const other = await (await req('POST', '/api/books/from-card', { text: text.replace('H8', 'H9') })).json() as any;
assert.equal(other.existed, false);
assert.equal(db.listBooks().length, 2);
});
test('from-card: a card with an ISBN matches by ISBN; cross-origin is refused', async () => {
const { req, db } = setup(undefined, 4321);
const text = 'QA76.73.R87 K53 2018\nThe Rust Programming Language\nSteve Klabnik\nISBN 9781593278281\n2018\nbooksorter 1';
const made = await (await req('POST', '/api/books/from-card', { text }, { origin: 'http://localhost:4321' })).json() as any;
assert.equal(made.book.isbn13, '9781593278281');
assert.equal(made.book.year, 2018);
const found = await (await req('POST', '/api/books/from-card', { text: text.replace('The Rust Programming Language', 'Other') }, { origin: 'http://localhost:4321' })).json() as any;
assert.equal(found.existed, true);
assert.equal(found.book.id, made.book.id);
assert.equal((await req('POST', '/api/books/from-card', { text }, { origin: 'http://evil.example' })).status, 403);
assert.equal(db.listBooks().length, 1);
});
test('retry asks the lookup to ignore its caches', async () => {
const fresh: (boolean | undefined)[] = [];
const { req, jobs } = setupRecording(fresh);
@@ -316,3 +280,19 @@ test('a search result\'s LCCN (work-level) is not saved onto the book', async ()
const f = await (await req('POST', '/api/books/from-search', { result: { title: 'Hit', authors: ['X'], lccn: '96067014', lcc: [] } })).json() as any;
assert.equal(f.book.lccn, null);
});
test('GET /api/books/:id/hierarchy answers with the outline and the stored tail', async () => {
const { req, db } = setup();
const b = db.insertPending({ title: 'H', callNumber: 'PS3558.E63 D8 2005', status: 'resolved', hierarchyTail: ['Utah'] }).book;
const r = await req('GET', `/api/books/${b.id}/hierarchy`);
assert.equal(r.status, 200);
assert.deepEqual(await r.json(), { outline: ['Class P', 'Sub PS'], tail: [] }); // the default builds from class names only
assert.equal((await req('GET', '/api/books/999/hierarchy')).status, 404);
});
test('a cross-origin request that changes state is refused', async () => {
const { req, db } = setup(undefined, 4321);
assert.equal((await req('POST', '/api/books/manual', { title: 'X' }, { origin: 'http://evil.example' })).status, 403);
assert.equal((await req('POST', '/api/books/manual', { title: 'X' }, { origin: 'http://localhost:4321' })).status, 200);
assert.equal(db.listBooks().length, 1);
});
+17 -26
View File
@@ -3,9 +3,8 @@ import { compareShelf } from '../shared/shelf.ts';
import { join } from 'node:path';
import { Hono } from 'hono';
import type { Context } from 'hono';
import type { Book, CardData, SearchResult, Settings } from '../shared/types.ts';
import type { Book, CardData, Hierarchy, SearchResult, Settings } from '../shared/types.ts';
import { normalizeIsbn } from '../shared/isbn.ts';
import { parseCardCode } from '../shared/cardcode.ts';
import { formatCallNumber, parseCallNumber, sortKeyOfRaw } from '../shared/callnumber.ts';
import type { Db, Filter, NewBook } from './db.ts';
import type { Jobs, ResolverLike } from './jobs.ts';
@@ -15,6 +14,8 @@ import type { classNames } from '../shared/lcc-outline.ts';
export type RenderCardsPdf = typeof renderCardsPdf;
export type RenderCalibrationPdf = typeof renderCalibrationPdf;
export type ClassNames = typeof classNames;
/** The plain-word hierarchy of a call number and the book's stored tail (see hierarchy.ts). */
export type HierarchyOf = (callNumber: string | null, tail: string[] | null) => Hierarchy;
export interface EventBus {
on(listener: (event: string, data: unknown) => void): () => void;
@@ -40,6 +41,8 @@ export interface AppDeps {
db: Db; jobs: Jobs; resolver: ResolverLike;
renderCardsPdf: RenderCardsPdf; renderCalibrationPdf: RenderCalibrationPdf;
classNames: ClassNames;
/** Defaults to the main class and subclass names alone (no outline ranges, no tail). */
hierarchy?: HierarchyOf;
events?: EventBus;
/** Where pictures the scanner failed to read are kept for tuning (the newest 30). */
capturesDir?: string;
@@ -75,6 +78,11 @@ function cacheKeys(book: Book): string[] {
export function createApp(deps: AppDeps): Hono {
const { db, jobs, resolver, classNames } = deps;
const hierarchyOf: HierarchyOf = deps.hierarchy ?? ((callNumber) => {
const cn = callNumber ? parseCallNumber(callNumber) : null;
const names = classNames(cn?.letters ?? '');
return { outline: [names.className, names.subclassName].filter((x): x is string => !!x), tail: [] };
});
const events = deps.events ?? createEventBus();
const app = new Hono();
@@ -155,26 +163,6 @@ export function createApp(deps: AppDeps): Hono {
return c.json({ book: addPending({ lccn, title: lccn }).book });
});
// A card's QR code carries the whole record, so the book is made straight from it, with no lookup. It is not
// queued for printing: it already has its card.
app.post('/api/books/from-card', async (c) => {
const text = (await body(c)).text;
const card = typeof text === 'string' ? parseCardCode(text) : null;
if (!card) throw new HttpError(400, 'Not a Booksorter card');
const sortKey = sortKeyOfRaw(card.callNumber);
const title = card.title.trim();
const same = (b: Book) => b.title.trim().toLowerCase() === title.toLowerCase() && b.sortKey === sortKey;
const existing = card.isbn13 ? db.findByIsbn(card.isbn13) : db.listBooks().find(same) ?? null;
if (existing) return c.json({ book: existing, existed: true });
const { book, created } = db.insertPending({
isbn13: card.isbn13, title: title || card.callNumber, authors: card.authors, year: card.year,
callNumber: card.callNumber, sortKey, confidence: card.approximate ? 'approximate' : 'exact', source: 'card',
status: 'resolved', manualOverride: false, inQueue: false,
});
if (created) events.emitBook(book);
return c.json({ book, existed: !created });
});
app.get('/api/search', async (c) => {
const title = c.req.query('title')?.trim() ?? '';
const author = c.req.query('author')?.trim() ?? '';
@@ -206,6 +194,12 @@ export function createApp(deps: AppDeps): Hono {
return c.json({ book: addPending(fields).book });
});
app.get('/api/books/:id/hierarchy', (c) => {
const book = db.getBook(Number(c.req.param('id')));
if (!book) throw new HttpError(404, 'No such book');
return c.json(hierarchyOf(book.callNumber, book.hierarchyTail));
});
app.get('/api/books', (c) => {
const f = c.req.query('filter');
const filter: Filter = f === 'queue' || f === 'attention' ? f : 'all';
@@ -277,11 +271,8 @@ export function createApp(deps: AppDeps): Hono {
.sort(compareShelf);
if (!books.length) throw new HttpError(400, 'Nothing to print');
const cards: CardData[] = books.map((b) => {
const cn = parseCallNumber(b.callNumber!);
const letters = cn?.letters ?? /^[A-Z]*/.exec(b.callNumber!)![0];
const names = classNames(letters);
return {
callNumber: b.callNumber!, className: names.className, subclassName: names.subclassName,
callNumber: b.callNumber!, hierarchy: hierarchyOf(b.callNumber, b.hierarchyTail),
title: b.subtitle ? `${b.title}: ${b.subtitle}` : b.title, authors: b.authors, publisher: b.publisher, year: b.year,
subjects: b.subjects, isbn13: b.isbn13, approximate: b.confidence === 'approximate',
};
+46
View File
@@ -59,3 +59,49 @@ test('settings and cache', () => {
db.cache.set('k', 'w');
assert.equal(db.cache.get('k'), 'w');
});
test('a database made before the hierarchy tail gets the column; old books read as not looked for', async () => {
const { DatabaseSync } = await import('node:sqlite');
const { mkdtempSync, rmSync } = await import('node:fs');
const { tmpdir } = await import('node:os');
const { join } = await import('node:path');
const dir = mkdtempSync(join(tmpdir(), 'booksorter-migrate-'));
try {
const path = join(dir, 'old.db');
const old = new DatabaseSync(path);
old.exec(`
CREATE TABLE books (
id INTEGER PRIMARY KEY AUTOINCREMENT, isbn13 TEXT UNIQUE, lccn TEXT, title TEXT NOT NULL, subtitle TEXT,
authors TEXT NOT NULL DEFAULT '[]', publisher TEXT, year INTEGER, subjects TEXT NOT NULL DEFAULT '[]',
call_number TEXT, sort_key TEXT, confidence TEXT, source TEXT, dewey TEXT,
status TEXT NOT NULL DEFAULT 'pending', attention_reason TEXT, manual_override INTEGER NOT NULL DEFAULT 0,
in_queue INTEGER NOT NULL DEFAULT 0, printed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
);
CREATE TABLE source_cache (key TEXT PRIMARY KEY, body TEXT NOT NULL);
CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
INSERT INTO books (isbn13, title, call_number, sort_key, confidence, source, status, in_queue, printed_at, created_at, updated_at)
VALUES ('9780874805451', 'Canyoneering 3', 'GV199.42.U82 G733 1997', 'GV 0199.42 U82 G733 1997', 'exact', 'loc-isbn',
'resolved', 1, '2026-01-02T00:00:00.000Z', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z');
`);
old.close();
const db = openDb(path);
const before = db.listBooks()[0]!;
assert.equal(before.hierarchyTail, null);
assert.equal(before.callNumber, 'GV199.42.U82 G733 1997');
assert.deepEqual(db.listTailMissingIds(), [before.id]);
const after = db.updateBook(before.id, { hierarchyTail: ['Utah'] })!;
assert.deepEqual(after.hierarchyTail, ['Utah']);
assert.equal(after.printedAt, before.printedAt);
assert.equal(db.updateBook(before.id, { hierarchyTail: [] })!.hierarchyTail?.length, 0);
assert.deepEqual(db.listTailMissingIds(), []);
assert.equal(db.updateBook(before.id, { hierarchyTail: null })!.hierarchyTail, null);
db.close();
const again = openDb(path); // opening a migrated database again is harmless
assert.equal(again.listBooks().length, 1);
again.close();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+17 -5
View File
@@ -12,7 +12,7 @@ export interface NewBook {
authors?: string[]; publisher?: string | null; year?: number | null; subjects?: string[];
callNumber?: string | null; sortKey?: string | null; confidence?: Confidence | null;
source?: Source | null; dewey?: string | null; status?: Status; attentionReason?: string | null;
manualOverride?: boolean; inQueue?: boolean;
manualOverride?: boolean; inQueue?: boolean; hierarchyTail?: string[] | null;
}
export type BookPatch = Partial<Omit<Book, 'id' | 'createdAt' | 'updatedAt'>>;
export type Filter = 'all' | 'queue' | 'attention';
@@ -25,6 +25,8 @@ export interface Db {
updateBook(id: number, patch: BookPatch): Book | null;
deleteBook(id: number): boolean;
listPendingIds(): number[];
/** Books that are not pending and whose hierarchy tail has not been looked for yet. */
listTailMissingIds(): number[];
getSettings(): Settings;
putSettings(s: Settings): void;
cache: ForgettableCache;
@@ -38,12 +40,13 @@ const COLUMNS: Record<keyof BookPatch, string> = {
publisher: 'publisher', year: 'year', subjects: 'subjects', callNumber: 'call_number',
sortKey: 'sort_key', confidence: 'confidence', source: 'source', dewey: 'dewey',
status: 'status', attentionReason: 'attention_reason', manualOverride: 'manual_override',
inQueue: 'in_queue', printedAt: 'printed_at',
inQueue: 'in_queue', printedAt: 'printed_at', hierarchyTail: 'hierarchy_tail',
};
const JSON_FIELDS = new Set(['authors', 'subjects']);
const BOOL_FIELDS = new Set(['manualOverride', 'inQueue']);
function toRow(key: string, v: unknown): unknown {
if (key === 'hierarchyTail') return v == null ? null : JSON.stringify(v); // null stays NULL: not looked for yet
if (JSON_FIELDS.has(key)) return JSON.stringify(v ?? []);
if (BOOL_FIELDS.has(key)) return v ? 1 : 0;
return v === undefined ? null : v;
@@ -57,6 +60,7 @@ function toBook(r: Row): Book {
confidence: r.confidence, source: r.source, dewey: r.dewey, status: r.status,
attentionReason: r.attention_reason, manualOverride: !!r.manual_override,
inQueue: !!r.in_queue, printedAt: r.printed_at, createdAt: r.created_at, updatedAt: r.updated_at,
hierarchyTail: r.hierarchy_tail == null ? null : JSON.parse(r.hierarchy_tail),
};
}
@@ -94,12 +98,17 @@ export function openDb(path: string): Db {
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
`);
// Additive migration: a database made before the hierarchy tail existed gets the column; nothing else changes.
if (!(db.prepare('PRAGMA table_info(books)').all() as Row[]).some((c) => c.name === 'hierarchy_tail')) {
db.exec('ALTER TABLE books ADD COLUMN hierarchy_tail TEXT');
}
const getById = db.prepare('SELECT * FROM books WHERE id = ?');
const getByIsbn = db.prepare('SELECT * FROM books WHERE isbn13 = ?');
const insert = db.prepare(`INSERT INTO books (isbn13, lccn, title, subtitle, authors, publisher, year,
subjects, call_number, sort_key, confidence, source, dewey, status, attention_reason,
manual_override, in_queue, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
manual_override, in_queue, created_at, updated_at, hierarchy_tail)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(isbn13) DO NOTHING`);
const self: Db = {
@@ -110,7 +119,7 @@ export function openDb(path: string): Db {
f.publisher ?? null, f.year ?? null, JSON.stringify(f.subjects ?? []), f.callNumber ?? null,
f.sortKey ?? null, f.confidence ?? null, f.source ?? null, f.dewey ?? null,
f.status ?? 'pending', f.attentionReason ?? null, f.manualOverride ? 1 : 0,
(f.inQueue ?? true) ? 1 : 0, now, now,
(f.inQueue ?? true) ? 1 : 0, now, now, f.hierarchyTail == null ? null : JSON.stringify(f.hierarchyTail),
);
if (r.changes === 0 && f.isbn13) return { book: self.findByIsbn(f.isbn13)!, created: false };
return { book: self.getBook(Number(r.lastInsertRowid))!, created: true };
@@ -153,6 +162,9 @@ export function openDb(path: string): Db {
listPendingIds() {
return (db.prepare("SELECT id FROM books WHERE status = 'pending' ORDER BY id").all() as Row[]).map((r) => r.id);
},
listTailMissingIds() {
return (db.prepare("SELECT id FROM books WHERE hierarchy_tail IS NULL AND status != 'pending' ORDER BY id").all() as Row[]).map((r) => r.id);
},
getSettings() {
const r = db.prepare("SELECT value FROM settings WHERE key = 'settings'").get() as Row | undefined;
return r ? { ...DEFAULT_SETTINGS, ...JSON.parse(r.value) } : { ...DEFAULT_SETTINGS };
+65
View File
@@ -0,0 +1,65 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { hasClassCutter, hierarchyOf, outlineLevels, outlineRangesFor } from './hierarchy.ts';
import { OUTLINE_RANGES } from './lcc-ranges.ts';
test('GV199.42 nests Hiking inside Outdoor life inside Recreation', () => {
assert.deepEqual(outlineLevels('GV199.42'), [
'Geography. Anthropology. Recreation', 'Recreation. Leisure',
'Outdoor life. Outdoor recreation', 'Hiking. Pedestrian tours',
]);
});
test('spot checks across the outline', () => {
const last = (cn: string) => outlineLevels(cn).at(-1);
assert.equal(last('QA76.73'), 'Electronic computers. Computer science');
assert.equal(last('QE28'), 'General');
assert.equal(last('F824.3'), 'Utah');
assert.equal(last('F867'), 'California');
assert.equal(last('RD563'), 'Surgery by region, system, or organ');
assert.equal(last('SH456.27'), 'Angling');
assert.equal(last('TX907.3'), 'Hospitality industry. Hotels, clubs, restaurants, etc. Food service');
assert.equal(outlineLevels('PS3545').at(-1), '1900-1960');
});
test('decimals are compared as numbers, and the cutters after the class do not matter', () => {
assert.deepEqual(outlineLevels('GV199.42.U82 U564 2024'), outlineLevels('GV199.42'));
assert.notDeepEqual(outlineLevels('GV199.7'), outlineLevels('GV199.42')); // between 199.62 and 199.8
assert.ok(!outlineLevels('GV199.7').includes('Hiking. Pedestrian tours'));
assert.ok(!outlineLevels('GV199.8').includes('Hiking. Pedestrian tours'));
});
test('consecutive duplicate captions collapse; letters outside the outline stop at what is known', () => {
const levels = outlineLevels('GV199.42');
assert.equal(levels.filter((l) => l === 'Recreation. Leisure').length, 1);
assert.deepEqual(outlineLevels('ZZ1'), ['Bibliography. Library science. Information resources (General)']);
assert.deepEqual(outlineLevels('not a number'), []);
});
test('a range ending on a whole number holds that number\'s decimals; a sibling that starts later wins', () => {
assert.ok(outlineLevels('HD5660.5').some((l) => l.startsWith('Employee participation')));
assert.ok(!outlineLevels('HD5661').some((l) => l.startsWith('Employee participation')));
});
test('ranges bounded by cutters apply to the first cutter only', () => {
const rows = OUTLINE_RANGES['DT']!.filter((r) => r[3] !== undefined);
assert.ok(rows.length > 0);
assert.ok(outlineLevels('F1569.C2').includes('Canal Zone. Panama Canal'));
assert.ok(outlineLevels('F1569.C23 Z8').includes('Canal Zone. Panama Canal')); // C23 continues C2
assert.ok(!outlineLevels('F1569.D3').includes('Canal Zone. Panama Canal'));
assert.ok(!outlineLevels('F1569').includes('Canal Zone. Panama Canal'));
assert.ok(outlineRangesFor('DT', 469, { letter: 'M', digits: '25' }).includes('Madagascar'));
assert.ok(!outlineRangesFor('DT', 469, { letter: 'M', digits: '5' }).includes('Madagascar'));
});
test('the tail is used only when the class part carries a cutter', () => {
assert.equal(hasClassCutter('GV199.42.U82 U564 2024'), true);
assert.equal(hasClassCutter('QE28 .L22 2007'), false);
assert.equal(hasClassCutter('GV199.42'), false);
const h = hierarchyOf('GV199.42.U82 U564 2024', ['Utah', 'Uinta Mountains']);
assert.deepEqual(h.tail, ['Utah', 'Uinta Mountains']);
assert.equal(h.outline.at(-1), 'Hiking. Pedestrian tours');
assert.deepEqual(hierarchyOf('QE28 .L22 2007', ['Utah']).tail, []);
assert.deepEqual(hierarchyOf('GV199.42.U82 U564 2024', null).tail, []);
assert.deepEqual(hierarchyOf(null, ['Utah']), { outline: [], tail: [] });
});
+79
View File
@@ -0,0 +1,79 @@
// The plain-word hierarchy of a call number: outline levels from the LC Classification Outline (decided by the
// letters and number alone), then the tail taken from the catalogue record's subject heading (stored per book).
import { parseCallNumber } from '../shared/callnumber.ts';
import { classNames } from '../shared/lcc-outline.ts';
import type { Hierarchy } from '../shared/types.ts';
import { OUTLINE_RANGES } from './lcc-ranges.ts';
import type { OutlineRange } from './lcc-ranges.ts';
type Cutter = { letter: string; digits: string };
/** Compare a call number's cutter with a bound such as "U45" or "Z": letter first, then the digits as a decimal. */
function cmpCutter(c: Cutter, bound: string): number {
const bl = bound[0]!;
if (c.letter !== bl) return c.letter < bl ? -1 : 1;
const a = c.digits.replace(/[a-z]+$/, ''), b = bound.slice(1);
const n = Math.max(a.length, b.length);
const x = a.padEnd(n, '0'), y = b.padEnd(n, '0');
return x < y ? -1 : x > y ? 1 : 0;
}
/** At or below an upper bound; a cutter that only continues the bound's digits ("M385" for "M38") is inside it. */
function atMost(c: Cutter, bound: string): boolean {
return cmpCutter(c, bound) <= 0 || (c.letter === bound[0] && c.digits.startsWith(bound.slice(1)));
}
interface Hit { r: OutlineRange; index: number; ext: boolean }
/** The ranges of the outline that contain this number, broadest first. */
export function outlineRangesFor(letters: string, x: number, firstCutter: Cutter | null): string[] {
const rows = OUTLINE_RANGES[letters];
if (!rows) return [];
const hits: Hit[] = [];
rows.forEach((r, index) => {
const [lo, hi, , cl, ch] = r;
const cutters = cl !== undefined || ch !== undefined;
// A range that ends on a whole number also takes that number's decimals (HD5650-5660 holds HD5660.5);
// a single number is exactly itself.
const ext = !cutters && hi > lo && Number.isInteger(hi) && x > hi && x < hi + 1;
if (x < lo || (x > hi && !ext)) return;
if (cutters) {
if (x === lo && cl) { if (!firstCutter || cmpCutter(firstCutter, cl) < 0) return; }
if (x === hi && ch) { if (!firstCutter || !atMost(firstCutter, ch)) return; }
if (lo === hi && !firstCutter) return;
}
hits.push({ r, index, ext });
});
// A range reached only through the decimal extension is dropped when another range that holds the number
// is neither around it nor inside it (two siblings cannot both be right).
const sure = hits.filter((h) => !h.ext);
const kept = hits.filter((h) => !h.ext || sure.every((s) =>
(s.r[0] <= h.r[0] && s.r[1] >= h.r[1]) || (s.r[0] >= h.r[0] && s.r[1] <= h.r[1] + 1)));
kept.sort((a, b) => a.r[0] - b.r[0] || b.r[1] - a.r[1] || (a.r[3] === undefined ? 0 : 1) - (b.r[3] === undefined ? 0 : 1) || a.index - b.index);
return kept.map((h) => h.r[2]);
}
function collapse(levels: string[]): string[] {
return levels.filter((l, i) => l && l !== levels[i - 1]);
}
/** Main class, subclass, then every nested outline range, general to specific. */
export function outlineLevels(callNumber: string): string[] {
const cn = parseCallNumber(callNumber);
if (!cn) return [];
const names = classNames(cn.letters);
const x = Number(cn.number + (cn.decimal ? '.' + cn.decimal : ''));
const ranges = outlineRangesFor(cn.letters, x, cn.cutters[0] ?? null);
return collapse([names.className ?? '', names.subclassName ?? '', ...ranges]);
}
/** The tail applies only when the class part of the number (card line 1) carries a cutter, as in GV199.42.U82 U564. */
export function hasClassCutter(callNumber: string): boolean {
const cn = parseCallNumber(callNumber);
return !!cn && cn.cutters.length >= 2;
}
export function hierarchyOf(callNumber: string | null, tail: string[] | null): Hierarchy {
if (!callNumber) return { outline: [], tail: [] };
const outline = outlineLevels(callNumber);
return { outline, tail: hasClassCutter(callNumber) ? collapse(tail ?? []) : [] };
}
+83 -1
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { openDb } from './db.ts';
import { createJobs, DEFAULT_RETRY_DELAYS_MS } from './jobs.ts';
import type { ResolverLike } from './jobs.ts';
import type { NewBook } from './db.ts';
import type { Book, Resolution } from '../shared/types.ts';
class TemporaryError extends Error {}
@@ -17,7 +18,7 @@ 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 resolver: ResolverLike = { resolve, tail: async () => [], search: async () => [] };
const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: delays, log: (l) => logs.push(l) });
return { db, jobs, changes, logs };
}
@@ -258,3 +259,84 @@ test('an LCCN placeholder title counts as empty', async () => {
await jobs.idle();
assert.equal(db.getBook(book.id)!.title, 'The Rust Book');
});
function tailBook(db: ReturnType<typeof openDb>, over: Partial<NewBook>) {
return db.insertPending({
status: 'resolved', callNumber: 'GV199.42.U82 U564 2024', sortKey: 'GV 0199.42 U82', confidence: 'exact',
source: 'loc-isbn', inQueue: false, title: 'T', ...over,
}).book;
}
test('lookup stores the tail; the tail stays unknown (NULL) when the catalogue could not be asked', async () => {
const a = setup(async () => ({ ...found, tail: ['Utah'] }));
const x = a.db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }).book;
a.jobs.enqueue(x.id);
await a.jobs.idle();
assert.deepEqual(a.db.getBook(x.id)!.hierarchyTail, ['Utah']);
const b = setup(async () => ({ ...found, tail: null }));
const y = b.db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }).book;
b.jobs.enqueue(y.id);
await b.jobs.idle();
assert.equal(b.db.getBook(y.id)!.status, 'resolved');
assert.equal(b.db.getBook(y.id)!.hierarchyTail, null);
});
test('tail backfill changes only the tail, emits the update, and never touches status or the number', async () => {
const calls: unknown[] = [];
const { db, changes } = setup(async () => found);
const resolver: ResolverLike = {
resolve: async () => { throw new Error('no lookup'); }, search: async () => [],
tail: async (i) => { calls.push(i); return ['Utah', 'Uinta Mountains']; },
};
const j = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0], log: () => {} });
const printed = '2026-02-03T00:00:00.000Z';
const b = tailBook(db, { isbn13: '9781593278281' });
db.updateBook(b.id, { printedAt: printed, inQueue: true, confidence: 'approximate' });
const before = db.getBook(b.id)!;
j.resumeTails();
await j.idle();
const after = db.getBook(b.id)!;
assert.deepEqual(after.hierarchyTail, ['Utah', 'Uinta Mountains']);
for (const k of ['callNumber', 'sortKey', 'confidence', 'source', 'status', 'attentionReason', 'inQueue', 'printedAt', 'manualOverride'] as const) {
assert.deepEqual(after[k], before[k], k);
}
assert.ok(changes.some((c) => c.id === b.id && c.hierarchyTail !== null), 'book-updated event');
assert.equal(calls.length, 1);
});
test('tail backfill: no identifiers, hand entries and similar numbers get [] without asking', async () => {
const { db } = setup(async () => found);
const asked: unknown[] = [];
const resolver: ResolverLike = { resolve: async () => found, search: async () => [], tail: async (i) => { asked.push(i); return ['X']; } };
const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} });
const none = tailBook(db, { title: 'no ids' });
const manual = tailBook(db, { isbn13: '9780000000002', manualOverride: true, source: 'manual' });
const similar = tailBook(db, { isbn13: '9780000000019', source: 'similar' });
const byHand = tailBook(db, { lccn: '2012047313', source: 'manual' });
const pending = db.insertPending({ isbn13: '9780000000026', title: 'p' }).book; // status pending: the lookup's job
jobs.resumeTails();
await jobs.idle();
for (const b of [none, manual, similar, byHand]) assert.deepEqual(db.getBook(b.id)!.hierarchyTail, [], b.title);
assert.equal(db.getBook(pending.id)!.hierarchyTail, null);
assert.equal(asked.length, 0);
});
test('tail backfill: a temporary failure is retried, then left NULL for the next start; a missing record stores []', async () => {
const { db } = setup(async () => found);
let n = 0;
const logs: string[] = [];
const resolver: ResolverLike = {
resolve: async () => found, search: async () => [],
tail: async (i) => { n++; if (i.isbn13 === '9780000000002') throw new TemporaryError('loc.gov busy'); return []; },
};
const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0, 0], isTemporary: (e) => e instanceof TemporaryError, log: (l) => logs.push(l) });
const busy = tailBook(db, { isbn13: '9780000000002' });
const empty = tailBook(db, { isbn13: '9780000000019' });
jobs.resumeTails();
await jobs.idle();
assert.equal(db.getBook(busy.id)!.hierarchyTail, null);
assert.equal(db.getBook(busy.id)!.status, 'resolved');
assert.deepEqual(db.getBook(empty.id)!.hierarchyTail, []);
assert.equal(n, 4); // busy: first try and two retries; empty: once
assert.ok(logs.some((l) => l.includes('left for the next start')));
});
+67 -9
View File
@@ -10,6 +10,11 @@ export interface Jobs {
/** `fresh`: the lookup ignores every cached source answer ("Look up again"), through its retries too. */
enqueue(id: number, opts?: { fresh?: boolean }): void;
resume(): void;
/**
* Backfill, for books made before the hierarchy tail existed: look up only the tail (nothing else about the book
* changes). Books that cannot have one get [] at once; a temporary failure leaves NULL for the next start.
*/
resumeTails(): void;
idle(): Promise<void>;
}
@@ -43,6 +48,9 @@ export function createJobs(deps: {
const fresh = new Set<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>>();
// The tail backfill queues behind real lookups, and retries on its own timers.
const tailQueue: number[] = [];
const tailAttempts = new Map<number, number>();
let running: Promise<void> | null = null;
let idlers = 0;
let wake: (() => void)[] = [];
@@ -105,18 +113,19 @@ export function createJobs(deps: {
if (!cur) return;
if (res.meta) applyMeta(id, res.meta);
const dewey = res.dewey ?? cur.dewey ?? undefined;
const tail = res.tail !== undefined && res.tail !== null ? { hierarchyTail: res.tail } : {};
if (cur.manualOverride) {
emit(id, { dewey });
emit(id, { dewey, ...(cur.hierarchyTail === null ? { hierarchyTail: [] } : {}) });
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,
source: res.source, dewey, status: 'resolved', attentionReason: null, ...tail,
});
log(`[lookup] ${label}: ${res.callNumber} (${res.source === 'similar' && similar ? `similar ${similar}` : res.source}) in ${took()}`);
} else {
const reason = res.reason ?? 'No Library of Congress number found';
emit(id, { dewey, status: 'needs_attention', attentionReason: reason });
emit(id, { dewey, status: 'needs_attention', attentionReason: reason, ...tail });
log(`[lookup] ${label}: no call number, ${reason} in ${took()}`);
}
} catch (e) {
@@ -138,17 +147,62 @@ export function createJobs(deps: {
}
}
/** Sources whose number never comes with a tail of its own: borrowed from similar books, or entered by hand. */
const NO_TAIL_SOURCES = new Set(['similar', 'manual']);
async function backfillTail(id: number): Promise<void> {
const book = db.getBook(id);
if (!book || book.hierarchyTail !== null || book.status === 'pending') { tailAttempts.delete(id); return; }
const label = book.isbn13 ?? book.lccn ?? book.title;
// Only the tail column is ever written here: the number, sort key, confidence, source, status, queue flag and
// printed date stay as they are.
if ((!book.isbn13 && !book.lccn) || book.manualOverride || (book.source && NO_TAIL_SOURCES.has(book.source))) {
tailAttempts.delete(id);
emit(id, { hierarchyTail: [] });
return;
}
const n = tailAttempts.get(id) ?? 0;
try {
const tail = await resolver.tail({
...(book.isbn13 ? { isbn13: book.isbn13 } : {}), ...(book.lccn ? { lccn: book.lccn } : {}),
title: book.title, ...(book.authors[0] ? { author: book.authors[0] } : {}),
viaTitle: book.source === 'loc-title' || book.source === 'ol-work',
});
tailAttempts.delete(id);
emit(id, { hierarchyTail: tail });
log(`[tail] ${label}: ${tail.length ? tail.join(' / ') : 'no usable subject heading'}`);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
if (isTemporary(e) && n < delays.length) {
tailAttempts.set(id, n + 1);
const delay = delays[n]!;
log(`[tail] ${label}: ${message}; trying again in ${Math.round(delay / 1000)} s`);
const t = setTimeout(() => { waiting.delete(-id); tailQueue.push(id); start(); notify(); }, delay);
if (idlers === 0) t.unref();
waiting.set(-id, t); // a negative key keeps tail retries apart from lookup retries
return;
}
tailAttempts.delete(id);
log(`[tail] ${label}: left for the next start, ${message}`); // NULL stays: the next start tries again
}
}
async function drain(): Promise<void> {
while (queue.length) {
const id = queue.shift()!;
queued.delete(id);
try { await attempt(id); } catch { /* a failure on one book must not stop the queue */ }
while (queue.length || tailQueue.length) {
if (queue.length) {
const id = queue.shift()!;
queued.delete(id);
try { await attempt(id); } catch { /* a failure on one book must not stop the queue */ }
} else {
const id = tailQueue.shift()!;
try { await backfillTail(id); } catch { /* ditto */ }
}
}
}
function start(): void {
if (running) return;
running = drain().finally(() => { running = null; if (queue.length) start(); notify(); });
running = drain().finally(() => { running = null; if (queue.length || tailQueue.length) start(); notify(); });
}
return {
@@ -163,11 +217,15 @@ export function createJobs(deps: {
start();
},
resume() { for (const id of db.listPendingIds()) this.enqueue(id); },
resumeTails() {
for (const id of db.listTailMissingIds()) if (!tailQueue.includes(id)) tailQueue.push(id);
start();
},
async idle() {
idlers++;
for (const t of waiting.values()) t.ref();
try {
while (running || queue.length || waiting.size) {
while (running || queue.length || tailQueue.length || waiting.size) {
if (running) await running;
else await new Promise<void>((r) => { wake.push(r); });
}
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -8,6 +8,7 @@ import { createApp, createEventBus } from './app.ts';
import { createResolver, TemporaryError } from './resolve/resolver.ts';
import { renderCalibrationPdf, renderCardsPdf } from './pdf/render.ts';
import { classNames } from '../shared/lcc-outline.ts';
import { hierarchyOf } from './hierarchy.ts';
const port = Number(process.env.PORT ?? 4321);
const dbPath = process.env.BOOKSORTER_DB ?? 'data/booksorter.db';
@@ -26,7 +27,7 @@ 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({ port, db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events, capturesDir });
const app = createApp({ port, db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, hierarchy: hierarchyOf, events, capturesDir });
app.get('*', (c) => {
if (!existsSync(join(webRoot, 'index.html'))) {
@@ -40,6 +41,7 @@ app.get('*', (c) => {
const server = serve({ fetch: app.fetch, port, hostname: '127.0.0.1' }, () => {
console.log(`Booksorter running at http://localhost:${port}`);
jobs.resume();
jobs.resumeTails();
});
server.on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EADDRINUSE') console.error(`Port ${port} is already in use. Is Booksorter already running?`);
+103 -7
View File
@@ -1,15 +1,17 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { layoutCard, wrap } from './card.ts';
import { layoutCard as layout, wrap } from './card.ts';
import type { CardData } from '../../shared/types.ts';
const measure = (t: string, size: number, _b: boolean) => Array.from(t).length * size * 0.55;
const base: CardData = {
callNumber: 'QA76.73.R87 K53 2018', className: 'Science', subclassName: 'Mathematics',
callNumber: 'QA76.73.R87 K53 2018', hierarchy: { outline: ['Science', 'Mathematics'], tail: [] },
title: 'The Rust Programming Language', authors: ['Steve Klabnik', 'Carol Nichols'],
publisher: 'No Starch Press', year: 2018, subjects: ['Rust (Computer program language)'],
isbn13: '9781593278281', approximate: true,
};
/** The text runs only; the tree and rule are tested through layout() itself. */
const layoutCard = (c: CardData, m: typeof measure) => layout(c, m).runs;
const widthOf = (r: { text: string; size: number; bold: boolean }) => measure(r.text, r.size, r.bold);
function checkBounds(runs: ReturnType<typeof layoutCard>) {
@@ -69,18 +71,112 @@ test('wrap breaks a word wider than the line and terminates', () => {
assert.deepEqual(wrap('', 10, false, measure), []);
});
test('omitted pieces: no subclass duplicate, no isbn, no tilde', () => {
const runs = layoutCard({ ...base, subclassName: 'Science', isbn13: null, approximate: false }, measure);
test('omitted pieces: no duplicate level, no isbn, no tilde', () => {
const runs = layoutCard({ ...base, hierarchy: { outline: ['Science', 'Science'], tail: [] }, isbn13: null, approximate: false }, measure);
assert.equal(runs.filter((r) => r.text === 'Science').length, 1);
assert.ok(!runs.some((r) => r.text.startsWith('ISBN') || r.text === '~'));
});
test('no text block goes below y 132 (room for the QR code)', () => {
test('no text block goes below y 30 (above the ISBN line)', () => {
const many: CardData = {
...base, title: 'A long title '.repeat(12), authors: ['One Author', 'Two Author', 'Three Author'],
subjects: ['A long first subject heading '.repeat(4), 'A long second subject heading '.repeat(4)],
};
const runs = layoutCard(many, measure);
assert.ok(runs.filter((r) => r.y > 20).every((r) => r.y > 132));
assert.ok(runs.filter((r) => r.y > 20).every((r) => r.y > 30));
assert.ok(runs.some((r) => r.text.startsWith('ISBN') && r.y === 16));
});
// ---- the hierarchy tree, the rule and the space priority ----
const levelRuns = (runs: ReturnType<typeof layoutCard>, rule: number) =>
runs.filter((r) => r.size <= 8.5 && r.size >= 7 && r.y < 292 && r.y > rule && r.text !== '~' && !r.text.startsWith('ISBN'));
const GV = ['Recreation. Leisure', 'Outdoor life. Outdoor recreation', 'Hiking. Pedestrian tours', 'Utah', 'Uinta Mountains'];
const gv = (outline: string[], tail: string[] = []): CardData => ({ ...base, callNumber: 'GV199.42.U82 U564 2024', hierarchy: { outline, tail } });
test('a five-level tree: one level per line, general first, each 7 pt further in, every level in the same plain gray', () => {
const l = layout(gv(['Geography. Anthropology. Recreation', ...GV.slice(0, 3)], GV.slice(3)), measure);
const lv = levelRuns(l.runs, l.ruleY);
assert.deepEqual(lv.map((r) => r.text), GV);
lv.forEach((r, i) => {
assert.equal(r.x, 14 + 7 * i);
assert.equal(r.size, 8.5);
assert.equal(r.bold, false);
assert.equal(r.gray, 0.35);
if (i) assert.ok(r.y < lv[i - 1]!.y, 'general at the top');
if (i) assert.ok(Math.abs(lv[i - 1]!.y - r.y - 10.5) < 1e-9, 'pitch 10.5');
});
assert.equal(l.connectors.length, 8); // an elbow (down, across) from each parent to its child
for (const c of l.connectors) { assert.equal(c.thickness, 0.5); assert.ok(c.x1 === c.x2 || c.y1 === c.y2); }
assert.ok(l.ruleY < lv[4]!.y && Math.abs(lv[4]!.y - l.ruleY - 8) < 1e-9, 'the rule sits 8 pt under the last line');
const title = l.runs.find((r) => r.text.startsWith('The Rust'))!;
assert.ok(title.y < l.ruleY, 'WHAT is below the rule');
assert.ok(!l.runs.some((r) => r.text.startsWith('Geography')), 'starts at the subclass');
});
test('one level: a single plain gray line, no connector', () => {
const l = layout({ ...base, hierarchy: { outline: ['Science'], tail: [] } }, measure);
const lv = levelRuns(l.runs, l.ruleY);
assert.equal(lv.length, 1);
assert.equal(lv[0]!.bold, false);
assert.equal(lv[0]!.gray, 0.35);
assert.equal(l.connectors.length, 0);
const none = layout({ ...base, hierarchy: { outline: [], tail: [] } }, measure);
assert.equal(none.ruleY, 286);
assert.equal(none.connectors.length, 0);
});
test('a caption too wide for its indent shrinks, not below 7 pt', () => {
// measure: 0.55 em per char; 188 pt at 8.5 pt holds 40 chars, at 7 pt 48.
const cap = 'x'.repeat(44);
const l = layout({ ...base, hierarchy: { outline: ['Science', cap, 'Short'], tail: [] } }, measure);
const run = l.runs.find((r) => r.text === cap)!;
assert.ok(run.size < 8.5 && run.size >= 7);
assert.ok(widthOf(run) + run.x <= 202 + 1e-9);
});
test('a caption that cannot fit even at 7 pt wraps once at the same indent, whole words', () => {
const words = Array.from({ length: 14 }, (_, i) => `word${i}`).join(' '); // 90+ chars
const l = layout({ ...base, hierarchy: { outline: ['Science', 'Math', words], tail: [] } }, measure);
const parts = l.runs.filter((r) => !r.bold && r.x === 21 && r.size <= 8.5);
assert.equal(parts.length, 2);
assert.equal(parts.map((r) => r.text).join(' '), words, 'no word is cut or truncated');
assert.ok(parts.every((r) => r.size >= 7 && widthOf(r) + r.x <= 202 + 1e-9));
assert.ok(parts[0]!.y > parts[1]!.y);
});
test('more than five levels: the general end is dropped, the specific end kept', () => {
const l = layout(gv(['Main', 'Sub', 'A', 'B', 'C', 'D'], ['E', 'F']), measure);
assert.deepEqual(levelRuns(l.runs, l.ruleY).map((r) => r.text), ['B', 'C', 'D', 'E', 'F']);
});
test('title and authors are kept: the publisher goes first, then tree levels (not below two)', () => {
const title = 'Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu';
// The first `tall` of the five levels are long captions that wrap to several lines at 7 pt.
const levels5 = (tall: number, words: number) => ['A', 'B', 'C', 'D', 'E'].map((t, i) => (i < tall ? Array.from({ length: words }, (_, k) => `${t}word${k}`).join(' ') : t));
const make = (levels: string[], pub = 'No Starch Press'): CardData => ({
...gv(['Main', ...levels.slice(0, -1)], levels.slice(-1)), title, authors: ['First Author', 'Second Author'], publisher: pub,
});
const inWhat = (l: ReturnType<typeof layout>) => l.runs.filter((r) => r.y < l.ruleY && r.y > 30);
const levelCount = (l: ReturnType<typeof layout>) => new Set(levelRuns(l.runs, l.ruleY).map((r) => r.x)).size;
// Plenty of room: everything prints, including the publisher.
const roomy = layout(make(['A', 'B', 'C', 'D', 'E']), measure);
assert.equal(levelCount(roomy), 5);
assert.ok(inWhat(roomy).some((r) => r.text.includes('No Starch')));
// Five tall levels: the publisher is the first thing to go; the tree and title and authors stay.
const tall = layout(make(levels5(3, 24)), measure);
assert.equal(inWhat(tall).filter((r) => r.bold && r.size === 13).length, 3, 'title');
assert.ok(inWhat(tall).some((r) => r.text.includes('Author')), 'authors');
assert.ok(!inWhat(tall).some((r) => r.text.includes('No Starch')), 'publisher dropped first');
assert.equal(levelCount(tall), 5, 'the tree is untouched while title and authors still fit');
// Taller still: the general end of the tree goes, never below two levels; title and authors still print.
const huge = layout(make(levels5(4, 28)), measure);
const n = levelCount(huge);
assert.ok(n >= 2 && n < 5, `levels ${n}`);
assert.ok(inWhat(huge).some((r) => r.bold && r.size >= 11), 'title');
assert.ok(inWhat(huge).some((r) => r.text.includes('Author')), 'authors');
assert.equal(levelRuns(huge.runs, huge.ruleY).at(-1)!.text, 'E', 'the specific end is kept');
assert.ok(huge.runs.filter((r) => r.y > 20).every((r) => r.y > 30));
});
+113 -37
View File
@@ -1,17 +1,18 @@
import { parseCallNumber, cardLines } from '../../shared/callnumber.ts';
import type { CardData } from '../../shared/types.ts';
import { displayLevels } from '../../shared/hierarchy.ts';
export interface TextRun { text: string; x: number; y: number; size: number; bold: boolean; gray: number }
export type Measure = (text: string, size: number, bold: boolean) => number;
export const MARGIN_X = 14;
export const TEXT_WIDTH = 188;
/** Where the rule sits when there is no hierarchy tree above it. */
export const RULE_Y = 286;
const GRAY = 0.35;
const BLOCK_START = 268;
const BLOCK_GAP = 8;
/** Text stays above the QR code: its top edge is y 122 plus 9 pt of clear space, rounded up. */
const BLOCK_FLOOR = 132;
/** Text stays above the ISBN line (baseline 16, 8 pt). */
const BLOCK_FLOOR = 30;
const ELLIPSIS = '…';
/** Largest size (1 pt steps, down to min) at which text fits; text is truncated if min still overflows. */
@@ -34,26 +35,26 @@ function truncate(text: string, size: number, bold: boolean, m: Measure): string
}
/** Break one over-long word into pieces that each fit. Always consumes at least one character per piece. */
function breakWord(word: string, size: number, bold: boolean, m: Measure): string[] {
function breakWord(word: string, size: number, bold: boolean, m: Measure, width = TEXT_WIDTH): string[] {
const out: string[] = [];
let cur = '';
for (const ch of Array.from(word)) {
if (cur && m(cur + ch, size, bold) > TEXT_WIDTH) { out.push(cur); cur = ch; } else cur += ch;
if (cur && m(cur + ch, size, bold) > width) { out.push(cur); cur = ch; } else cur += ch;
}
if (cur) out.push(cur);
return out;
}
export function wrap(text: string, size: number, bold: boolean, m: Measure): string[] {
export function wrap(text: string, size: number, bold: boolean, m: Measure, width = TEXT_WIDTH): string[] {
const words = text.split(/\s+/).filter(Boolean);
const lines: string[] = [];
let cur = '';
for (const word of words) {
const joined = cur ? cur + ' ' + word : word;
if (m(joined, size, bold) <= TEXT_WIDTH) { cur = joined; continue; }
if (m(joined, size, bold) <= width) { cur = joined; continue; }
if (cur) { lines.push(cur); cur = ''; }
if (m(word, size, bold) <= TEXT_WIDTH) { cur = word; continue; }
const pieces = breakWord(word, size, bold, m);
if (m(word, size, bold) <= width) { cur = word; continue; }
const pieces = breakWord(word, size, bold, m, width);
cur = pieces.pop() ?? '';
lines.push(...pieces);
}
@@ -75,7 +76,99 @@ interface Block { size: number; bold: boolean; gray: number; lines: string[] }
const LEADING = 1.2;
export function layoutCard(card: CardData, measure: Measure): TextRun[] {
export interface Segment { x1: number; y1: number; x2: number; y2: number; thickness: number; gray: number }
export interface CardLayout {
runs: TextRun[];
/** The tree's elbow connectors, as thin gray vector lines. */
connectors: Segment[];
/** Where the hairline rule between WHERE (call number, tree) and WHAT (title, authors) goes. */
ruleY: number;
}
// The hierarchy tree under the call number: one level per line, general at the top, each level indented further.
export const TREE_TOP = 292;
export const TREE_PITCH = 10.5;
const TREE_INDENT = 7;
const TREE_SIZE = 8.5;
const TREE_MIN_SIZE = 7;
const TREE_MAX_LEVELS = 5;
const TREE_MIN_LEVELS = 2;
const TREE_GRAY = 0.35;
const CONNECTOR_GRAY = 0.5;
const RULE_GAP = 8;
interface Tree { runs: TextRun[]; connectors: Segment[]; ruleY: number }
/** One level: the largest size down to 7 pt at which it fits on one line; else wrapped (shrunk as needed to fit two lines). */
function fitLevel(text: string, width: number, bold: boolean, m: Measure): { size: number; lines: string[] } {
for (let size = TREE_SIZE; size >= TREE_MIN_SIZE; size -= 0.5) {
if (m(text, size, bold) <= width) return { size, lines: [text] };
}
for (let size = TREE_SIZE; size >= TREE_MIN_SIZE; size -= 0.5) {
const lines = wrap(text, size, bold, m, width);
if (lines.length <= 2) return { size, lines };
}
return { size: TREE_MIN_SIZE, lines: wrap(text, TREE_MIN_SIZE, bold, m, width) }; // never truncated, however long
}
function layoutTree(levels: string[], m: Measure): Tree {
const runs: TextRun[] = [];
const connectors: Segment[] = [];
let line = 0; // index of the next line slot
let prev: { x: number; lastBaseline: number } | null = null;
const baselineOf = (slot: number) => TREE_TOP - slot * TREE_PITCH - TREE_SIZE * 0.85;
for (const [i, text] of levels.entries()) {
const x = MARGIN_X + TREE_INDENT * i;
const { size, lines } = fitLevel(text, TEXT_WIDTH - TREE_INDENT * i, false, m);
const firstBaseline = baselineOf(line);
lines.forEach((t, k) => {
runs.push({ text: t, x, y: baselineOf(line + k), size, bold: false, gray: TREE_GRAY });
});
if (prev) {
// Down from just under the parent's text, then across to the child, at the height of its lower-case letters.
const vx = prev.x + 2.5;
const midY = firstBaseline + 2.4;
connectors.push({ x1: vx, y1: prev.lastBaseline - 2.2, x2: vx, y2: midY, thickness: 0.5, gray: CONNECTOR_GRAY });
connectors.push({ x1: vx, y1: midY, x2: x - 1.2, y2: midY, thickness: 0.5, gray: CONNECTOR_GRAY });
}
prev = { x, lastBaseline: baselineOf(line + lines.length - 1) };
line += lines.length;
}
const ruleY = prev ? prev.lastBaseline - RULE_GAP : RULE_Y;
return { runs, connectors, ruleY };
}
/** What goes below the rule, in priority order; each block is dropped whole if it does not fit above the ISBN line. */
function whatBlocks(card: CardData, measure: Measure): { required: Block[]; publisher: Block | null } {
const required: Block[] = [];
if (card.title.trim()) {
let t = wrapLimited(card.title, 13, true, 3, measure);
let size = 13;
if (t.overflow) { size = 11; t = wrapLimited(card.title, 11, true, 3, measure); }
required.push({ size, bold: true, gray: 0, lines: t.lines });
}
if (card.authors.length) {
const list = card.authors.length > 3 ? card.authors.slice(0, 3).join(', ') + ' et al.' : card.authors.join(', ');
required.push({ size: 10, bold: false, gray: 0, lines: wrapLimited(list, 10, false, 2, measure).lines });
}
const pub = [card.publisher, card.year != null ? String(card.year) : null].filter(Boolean).join(', ');
return { required, publisher: pub ? { size: 9, bold: false, gray: 0, lines: [truncate(pub, 9, false, measure)] } : null };
}
/** Bottom edge of blocks stacked from `top`. */
function stackBottom(top: number, blocks: Block[]): number {
let t = top;
for (const b of blocks) t -= b.lines.length * b.size * LEADING + BLOCK_GAP;
return t + BLOCK_GAP;
}
/**
* Space priority, highest first: the call number; the title and the authors; the tree's last two levels; the tree's
* upper levels (up to 5 in all); the publisher and year. When the title and authors do not fit above the ISBN line,
* the publisher goes first (it only prints if it still fits), then the tree loses levels from its general end,
* down to a minimum of two.
*/
export function layoutCard(card: CardData, measure: Measure): CardLayout {
const runs: TextRun[] = [];
const cn = parseCallNumber(card.callNumber);
const [l1, l2] = cn ? cardLines(cn) : [card.callNumber, ''];
@@ -86,34 +179,17 @@ export function layoutCard(card: CardData, measure: Measure): TextRun[] {
runs.push({ text: b.text, x: MARGIN_X, y: 300, size: b.size, bold: true, gray: 0 });
}
const blocks: Block[] = [];
const names: string[] = [];
if (card.className) names.push(card.className);
if (card.subclassName && card.subclassName !== card.className) names.push(card.subclassName);
if (names.length) {
blocks.push({ size: 9, bold: false, gray: GRAY, lines: names.map((n) => truncate(n, 9, false, measure)) });
const all = displayLevels(card.hierarchy).slice(-TREE_MAX_LEVELS);
const { required, publisher } = whatBlocks(card, measure);
let tree = layoutTree(all, measure);
for (let drop = 0; drop <= all.length - TREE_MIN_LEVELS; drop++) {
tree = layoutTree(all.slice(drop), measure);
if (stackBottom(tree.ruleY - 18, required) >= BLOCK_FLOOR) break;
}
if (card.title.trim()) {
let t = wrapLimited(card.title, 13, true, 3, measure);
let size = 13;
if (t.overflow) { size = 11; t = wrapLimited(card.title, 11, true, 3, measure); }
blocks.push({ size, bold: true, gray: 0, lines: t.lines });
}
if (card.authors.length) {
const list = card.authors.length > 3 ? card.authors.slice(0, 3).join(', ') + ' et al.' : card.authors.join(', ');
blocks.push({ size: 10, bold: false, gray: 0, lines: wrapLimited(list, 10, false, 2, measure).lines });
}
const pub = [card.publisher, card.year != null ? String(card.year) : null].filter(Boolean).join(', ');
if (pub) blocks.push({ size: 9, bold: false, gray: 0, lines: [truncate(pub, 9, false, measure)] });
for (const s of card.subjects.slice(0, 2)) {
if (s.trim()) blocks.push({ size: 9, bold: false, gray: GRAY, lines: wrapLimited(s, 9, false, 2, measure).lines });
}
let top = BLOCK_START;
runs.push(...tree.runs);
const blocks = publisher ? [...required, publisher] : required;
let top = tree.ruleY - 18;
for (const b of blocks) {
const lh = b.size * LEADING;
const bottom = top - b.lines.length * lh;
@@ -131,5 +207,5 @@ export function layoutCard(card: CardData, measure: Measure): TextRun[] {
const w = measure('~', 12, true);
runs.push({ text: '~', x: MARGIN_X + TEXT_WIDTH - w, y: 16, size: 12, bold: true, gray: 0 });
}
return runs;
return { runs, connectors: tree.connectors, ruleY: tree.ruleY };
}
-68
View File
@@ -1,68 +0,0 @@
import { test, before } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
import { qrMatrix, qrRects, QR_BOTTOM, QR_SIZE, QR_TOP, QR_X } from './qr.ts';
import { encodeCardCode, parseCardCode } from '../../shared/cardcode.ts';
import type { CardCode } from '../../shared/cardcode.ts';
const short = 'QA76.73.R87 K53 2018\nThe Rust Programming Language\nSteve Klabnik; Carol Nichols\nISBN 9781718500440\n2018\nbooksorter 1';
test('the symbol is 90 pt square, flush left, from y 32 to 122, for any version', () => {
const longest = encodeCardCode({
callNumber: 'QA76.73.C153 S77 K47 2013', approximate: true, title: 'x'.repeat(200), authors: ['a'.repeat(60)], isbn13: '9781718500440', year: 2018,
});
for (const payload of [short, longest, 'booksorter 1']) {
const { rects, version } = qrRects(payload);
assert.ok(version >= 1 && version <= 6, `version ${version}`);
const x0 = Math.min(...rects.map(r => r.x)), x1 = Math.max(...rects.map(r => r.x + r.width));
const y0 = Math.min(...rects.map(r => r.y)), y1 = Math.max(...rects.map(r => r.y + r.height));
// finder patterns sit in every corner except bottom-right, so all four edges are touched
assert.ok(Math.abs(x0 - QR_X) < 1e-9 && Math.abs(x1 - (QR_X + QR_SIZE)) < 1e-9);
assert.ok(Math.abs(y0 - QR_BOTTOM) < 1e-9 && Math.abs(y1 - QR_TOP) < 1e-9);
assert.equal(QR_X, 14);
}
});
test('horizontal runs are merged: rectangles cover exactly the dark modules', () => {
const m = qrMatrix(short), n = m.length, mod = QR_SIZE / n;
const { rects } = qrRects(short);
let dark = 0;
for (const row of m) for (const v of row) if (v) dark++;
const area = rects.reduce((a, r) => a + r.width * r.height, 0);
assert.ok(Math.abs(area - dark * mod * mod) < 1e-6);
assert.ok(rects.length < dark);
for (const r of rects) assert.ok(Math.abs(r.height - mod) < 1e-9);
});
// ---- round trip: draw the symbol into pixels and read it back with zxing-wasm ----------------------
before(async () => {
const wasm = readFileSync(createRequire(import.meta.url).resolve('zxing-wasm/reader').replace(/dist[\\/].*$/, 'dist/reader/zxing_reader.wasm'));
await prepareZXingModule({ overrides: { wasmBinary: wasm.buffer.slice(wasm.byteOffset, wasm.byteOffset + wasm.byteLength) as ArrayBuffer }, fireImmediately: true });
});
function raster(matrix: boolean[][], px = 6, quiet = 4): { data: Uint8ClampedArray; width: number; height: number } {
const n = matrix.length, size = (n + 2 * quiet) * px, data = new Uint8ClampedArray(size * size * 4).fill(255);
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
if (!matrix[r]![c]) continue;
for (let y = 0; y < px; y++) for (let x = 0; x < px; x++) {
const i = (((r + quiet) * px + y) * size + (c + quiet) * px + x) * 4;
data[i] = data[i + 1] = data[i + 2] = 0;
}
}
return { data, width: size, height: size };
}
test('a printed symbol with a non-ASCII title reads back to the same payload', async () => {
const card: CardCode = {
callNumber: 'PQ2230.A1 H8 1987', approximate: false, title: 'Les Misérables',
authors: ['Victor Hugo'], isbn13: '9780140444308', year: 1987,
};
const payload = encodeCardCode(card);
const [hit] = await readBarcodes(raster(qrMatrix(payload)) as ImageData, { formats: ['QRCode'], tryHarder: true });
assert.ok(hit, 'zxing found no QR code');
assert.equal(hit.format, 'QRCode');
assert.equal(hit.text, payload);
assert.deepEqual(parseCardCode(hit.text), card);
});
-43
View File
@@ -1,43 +0,0 @@
import qrcode from 'qrcode-generator';
/** Card-local geometry of the QR symbol (dark-module area, not counting the quiet zone). */
export const QR_SIZE = 90;
export const QR_X = 14; // flush with the text margin (MARGIN_X in card.ts)
export const QR_BOTTOM = 32;
export const QR_TOP = QR_BOTTOM + QR_SIZE;
/** Nothing else is drawn within this distance of the symbol. */
export const QR_CLEAR = 9;
// The payload is UTF-8; the library's default byte encoder is not.
qrcode.stringToBytes = (s: string) => Array.from(new TextEncoder().encode(s));
/** Dark modules of the smallest error-level-L byte-mode symbol that holds the payload: matrix[row][col]. */
export function qrMatrix(payload: string): boolean[][] {
const qr = qrcode(0, 'L');
qr.addData(payload, 'Byte');
qr.make();
const n = qr.getModuleCount();
return Array.from({ length: n }, (_, r) => Array.from({ length: n }, (_, c) => qr.isDark(r, c)));
}
export interface Rect { x: number; y: number; width: number; height: number }
/**
* Filled rectangles (card-local points) for the dark modules, scaled so the symbol is QR_SIZE square.
* Each horizontal run of dark modules is one rectangle, so there are no hairline gaps between neighbours.
*/
export function qrRects(payload: string): { version: number; rects: Rect[] } {
const m = qrMatrix(payload), n = m.length, module = QR_SIZE / n;
const rects: Rect[] = [];
for (let r = 0; r < n; r++) {
let c = 0;
while (c < n) {
if (!m[r]![c]) { c++; continue; }
let end = c;
while (end < n && m[r]![end]) end++;
rects.push({ x: QR_X + c * module, y: QR_TOP - (r + 1) * module, width: (end - c) * module, height: module });
c = end;
}
}
return { version: (n - 17) / 4, rects };
}
+1 -1
View File
@@ -6,7 +6,7 @@ import type { CardData } from '../../shared/types.ts';
const zero = { offsetXmm: 0, offsetYmm: 0 };
const card: CardData = {
callNumber: 'QA76.73.R87 K53 2018', className: 'Science', subclassName: 'Mathematics',
callNumber: 'QA76.73.R87 K53 2018', hierarchy: { outline: ['Science', 'Mathematics'], tail: [] },
title: 'The Rust Programming Language', authors: ['Steve Klabnik'], publisher: 'No Starch Press',
year: 2018, subjects: [], isbn13: null, approximate: false,
};
+9 -12
View File
@@ -5,10 +5,8 @@ import { PDFDocument, rgb, pushGraphicsState, popGraphicsState, concatTransforma
import type { PDFFont, PDFPage } from 'pdf-lib';
import fontkit from '@pdf-lib/fontkit';
import type { CardData, Settings } from '../../shared/types.ts';
import { layoutCard, MARGIN_X, TEXT_WIDTH, RULE_Y } from './card.ts';
import { layoutCard, MARGIN_X, TEXT_WIDTH } from './card.ts';
import { SHEET, CARD, cardMatrix } from './layout.ts';
import { qrRects } from './qr.ts';
import { encodeCardCode } from '../../shared/cardcode.ts';
interface Fonts { regular: PDFFont; bold: PDFFont; has: (cp: number) => boolean }
@@ -46,7 +44,8 @@ function cleanCard(c: CardData, f: Fonts): CardData {
const n = (s: string | null) => (s == null ? null : clean(s, f));
return {
...c,
callNumber: clean(c.callNumber, f), className: n(c.className), subclassName: n(c.subclassName),
callNumber: clean(c.callNumber, f),
hierarchy: { outline: c.hierarchy.outline.map((x) => clean(x, f)), tail: c.hierarchy.tail.map((x) => clean(x, f)) },
title: clean(c.title, f), authors: c.authors.map((s) => clean(s, f)), publisher: n(c.publisher),
subjects: c.subjects.map((s) => clean(s, f)), isbn13: n(c.isbn13),
};
@@ -61,19 +60,17 @@ function inCardSpace(page: PDFPage, m: ReturnType<typeof cardMatrix>, draw: () =
function drawCard(page: PDFPage, card: CardData, fonts: Fonts) {
const measure = (t: string, size: number, bold: boolean) =>
(bold ? fonts.bold : fonts.regular).widthOfTextAtSize(clean(t, fonts), size);
for (const r of layoutCard(cleanCard(card, fonts), measure)) {
const layout = layoutCard(cleanCard(card, fonts), measure);
for (const r of layout.runs) {
page.drawText(clean(r.text, fonts), {
x: r.x, y: r.y, size: r.size, font: r.bold ? fonts.bold : fonts.regular, color: rgb(r.gray, r.gray, r.gray),
});
}
// The payload carries the real text, not the font-safe copy the card text is drawn from.
const payload = encodeCardCode({
callNumber: card.callNumber, approximate: card.approximate, title: card.title,
authors: card.authors, isbn13: card.isbn13, year: card.year,
});
for (const r of qrRects(payload).rects) page.drawRectangle({ ...r, color: rgb(0, 0, 0), borderWidth: 0 });
for (const c of layout.connectors) {
page.drawLine({ start: { x: c.x1, y: c.y1 }, end: { x: c.x2, y: c.y2 }, thickness: c.thickness, color: rgb(c.gray, c.gray, c.gray) });
}
page.drawLine({
start: { x: MARGIN_X, y: RULE_Y }, end: { x: MARGIN_X + TEXT_WIDTH, y: RULE_Y },
start: { x: MARGIN_X, y: layout.ruleY }, end: { x: MARGIN_X + TEXT_WIDTH, y: layout.ruleY },
thickness: 0.75, color: rgb(0, 0, 0),
});
}
+1 -1
View File
@@ -3,7 +3,7 @@ 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, topics: [], isbns: [] });
const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names, topics: [], isbns: [], subjectTail: [] });
test('normalizeTitle', () => {
assert.equal(normalizeTitle('The Mythical Man-Month: Essays on Software'), 'mythical man month');
+9
View File
@@ -436,3 +436,12 @@ test('an LCCN from the LoC ISBN record\'s own 010 is reported', async () => {
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: SIERRA_SOUTH });
assert.equal(res.meta?.lccn, '2020947927');
});
test('tail: the LoC record\'s first LCSH heading, from lookup and from the tail-only call alike', async () => {
const f = fixtureFetch();
const r = createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep });
const res = await r.resolve({ isbn13: '9781593278281' });
assert.ok(res.tail && res.tail.length > 0, 'a heading was found');
assert.deepEqual(await r.tail({ isbn13: '9781593278281' }), res.tail);
assert.deepEqual(await r.tail({ isbn13: '9780999999998' }), []); // no record at all: looked, none
});
+33 -3
View File
@@ -29,6 +29,13 @@ export interface ResolveOpts {
export interface Resolver {
resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution>;
search(title: string, author: string): Promise<SearchResult[]>;
/**
* Only the hierarchy tail of a book already in the library: the subject heading of its Library of Congress record
* (this edition's by ISBN, then by LCCN; with `viaTitle`, the title match the lookup itself would have used).
* Uses the same rate limit and cache as a lookup. [] when there is no record or no usable heading;
* throws TemporaryError when the catalogue cannot be asked.
*/
tail(input: { isbn13?: string; lccn?: string; title?: string; author?: string; viaTitle?: boolean }): Promise<string[]>;
}
type Partials = (Partial<BookMeta> | null | undefined)[];
@@ -247,20 +254,43 @@ export function createResolver(deps: {
const dewey = locRecs.map((r) => r.dewey).find(Boolean) ?? edition?.dewey ?? work?.dewey
?? locTitleRecs.map((r) => r.dewey).find(Boolean) ?? null;
// The tail comes from this edition's record, else the title-matched record. A number borrowed from similar
// books carries none. When the catalogue could not be asked it stays unknown (null) and is looked for later.
const tail: string[] | null = chosen?.source === 'similar' ? []
: locRecs[0] ? locRecs[0].subjectTail
: locTitleRecs[0] ? locTitleRecs[0].subjectTail
: locError ? null : [];
if (chosen) {
return {
meta, callNumber: chosen.callNumber, sortKey: chosen.sortKey,
confidence: chosen.confidence, source: chosen.source, dewey, reason: null,
confidence: chosen.confidence, source: chosen.source, dewey, tail, reason: null,
};
}
// Open Library had nothing and the LoC could not be asked: report that, not "no number found".
if (locError) throw locError;
if (olError) throw olError;
return {
meta, callNumber: null, sortKey: null, confidence: null, source: null, dewey,
meta, callNumber: null, sortKey: null, confidence: null, source: null, dewey, tail,
reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library or the Library of Congress',
};
}
return { resolve, search: (title, author) => ol.search(title, author) };
async function tail(input: { isbn13?: string; lccn?: string; title?: string; author?: string; viaTitle?: boolean }): Promise<string[]> {
const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined;
let mine: MarcFields[] = [];
if (isbn) mine = await loc.byIsbn(isbn);
if (mine.length === 0 && input.lccn) {
// Same edition only if the book has no ISBN or the record lists this ISBN.
mine = (await loc.byLccn(input.lccn)).filter((r) => !isbn || r.isbns.includes(isbn));
}
if (mine[0]) return mine[0].subjectTail;
if (input.viaTitle && input.title && input.author) {
const found = (await loc.byTitle(input.title, input.author)).filter((r) => recordMatches(r, input.title!, input.author!));
if (found[0]) return found[0].subjectTail;
}
return [];
}
return { resolve, tail, search: (title, author) => ol.search(title, author) };
}
+27
View File
@@ -83,3 +83,30 @@ test('020 ISBNs are read as ISBN-13, ISBN-10 converted, qualifiers dropped, junk
assert.deepEqual(parseMarcXml(xml(['0201835959 (pbk.)', '9780201835953', 'not an isbn']))[0]!.isbns, ['9780201835953']);
assert.deepEqual(parseMarcXml('<record><leader>x</leader></record>')[0]!.isbns, []);
});
const rec = (fields: string) =>
parseMarcXml(`<collection><record>${fields}</record></collection>`)[0]!;
const f = (tag: string, ind2: string, subs: [string, string][]) =>
`<datafield tag="${tag}" ind1=" " ind2="${ind2}">${subs.map(([c, v]) => `<subfield code="${c}">${v}</subfield>`).join('')}</datafield>`;
test('subject tail: the $z chain of the first 650 that has one, without $v and full stops', () => {
const r = rec(
f('650', '0', [['a', 'Canyoneering'], ['z', 'Utah'], ['z', 'Grand Staircase-Escalante National Monument'], ['v', 'Guidebooks.']]) +
f('651', '0', [['a', 'Grand Staircase-Escalante National Monument (Utah)'], ['v', 'Guidebooks.']]));
assert.deepEqual(r.subjectTail, ['Utah', 'Grand Staircase-Escalante National Monument']);
assert.deepEqual(rec(f('650', '0', [['a', 'Canyoneering'], ['z', 'Utah.'], ['v', 'Guidebooks.']])).subjectTail, ['Utah']);
});
test('subject tail: a 650 with $z wins over an earlier one without; else the first 650 $a; else the first 651 $a', () => {
const both = rec(f('650', '0', [['a', 'Hiking.']]) + f('650', '0', [['a', 'Trails'], ['z', 'Utah.']]));
assert.deepEqual(both.subjectTail, ['Utah']);
const topical = rec(f('650', '0', [['a', 'Rust (Computer program language)'], ['v', 'Handbooks.']]) + f('650', '0', [['a', 'Programming.']]));
assert.deepEqual(topical.subjectTail, ['Rust (Computer program language)']);
assert.deepEqual(rec(f('651', '0', [['a', 'Uinta Mountains (Utah and Wyo.)']])).subjectTail, ['Uinta Mountains (Utah and Wyo.)']);
});
test('subject tail: other thesauri are ignored, and no heading gives an empty tail', () => {
const fast = rec(f('650', '7', [['a', 'Hiking'], ['z', 'Utah']]) + f('650', '6', [['a', 'Randonnee'], ['z', 'Utah']]));
assert.deepEqual(fast.subjectTail, []);
assert.deepEqual(rec(f('245', '0', [['a', 'Title']])).subjectTail, []);
});
+23 -1
View File
@@ -14,6 +14,8 @@ export interface MarcFields {
topics: string[];
/** The ISBNs the record lists (020 $a), as ISBN-13: an ISBN-10 is converted, the "(pbk.)" qualifier dropped. */
isbns: string[];
/** Place words for the card's hierarchy, from the first usable Library of Congress subject heading; see subjectTail(). */
subjectTail: string[];
}
type Node = Record<string, unknown>;
@@ -86,6 +88,26 @@ export function displayName(name: string): string {
return [forenames, surname, ...suffix].join(' ');
}
/** A heading without its closing ISBD full stop: "Utah." -> "Utah". */
const noStop = (s: string) => s.trim().replace(/\.+$/, '').trim();
/**
* The tail of a call number's hierarchy, from the record's subject headings (LCSH only: second indicator 0).
* The geographic subdivisions ($z, in order) of the first 650 that has any; else the $a of the first 650; else the
* $a of the first 651. Form subdivisions ($v) and $x are not part of it.
*/
function subjectTail(fields: Field[]): string[] {
const lcsh = (tag: string) => fields.filter((f) => f.tag === tag && f.ind2 === '0');
const f650 = lcsh('650');
const withZ = f650.find((f) => f.subs.some((s) => s.code === 'z' && s.value));
if (withZ) return withZ.subs.filter((s) => s.code === 'z' && s.value).map((s) => noStop(s.value)).filter(Boolean);
for (const f of [...f650, ...lcsh('651')]) {
const a = noStop(sub(f, 'a'));
if (a) return [a];
}
return [];
}
export function parseMarcRecord(rec: Node): MarcFields {
const fields = fieldsOf(rec);
const all = (tag: string) => fields.filter((f) => f.tag === tag);
@@ -131,7 +153,7 @@ export function parseMarcRecord(rec: Node): MarcFields {
if (ym) meta.year = Number(ym[1]);
if (lccn) meta.lccn = lccn;
const isbns = uniq(all('020').flatMap((f) => f.subs.filter((x) => x.code === 'a').map((x) => normalizeIsbn(x.value.split(/\s/)[0] ?? '')).filter((x): x is string => x !== null)));
return { lccn, lcc, dewey, meta, names, topics, isbns };
return { lccn, lcc, dewey, meta, names, topics, isbns, subjectTail: subjectTail(fields) };
}
/** Parse every MARC record in an SRU response or a bare LCCN permalink record. */
-58
View File
@@ -1,58 +0,0 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { encodeCardCode, parseCardCode } from './cardcode.ts';
import type { CardCode } from './cardcode.ts';
const rust: CardCode = {
callNumber: 'QA76.73.R87 K53 2018', approximate: false, title: 'The Rust Programming Language',
authors: ['Steve Klabnik', 'Carol Nichols', 'Third Person'], isbn13: '9781718500440', year: 2018,
};
const bytes = (s: string) => new TextEncoder().encode(s).length;
test('encodes the documented layout', () => {
assert.equal(
encodeCardCode(rust),
'QA76.73.R87 K53 2018\nThe Rust Programming Language\nSteve Klabnik; Carol Nichols\nISBN 9781718500440\n2018\nbooksorter 1',
);
});
test('optional lines are left out, the authors line stays; approximate adds a tilde', () => {
assert.equal(
encodeCardCode({ ...rust, authors: [], isbn13: null, year: null, approximate: true }),
'QA76.73.R87 K53 2018 ~\nThe Rust Programming Language\n\nbooksorter 1',
);
});
test('round trip', () => {
assert.deepEqual(parseCardCode(encodeCardCode(rust)), { ...rust, authors: ['Steve Klabnik', 'Carol Nichols'] });
const bare = { ...rust, authors: [], isbn13: null, year: null, approximate: true };
assert.deepEqual(parseCardCode(encodeCardCode(bare)), bare);
});
test('long text is cut to 130 bytes, authors first to 40 bytes, with an ellipsis', () => {
const c = { ...rust, title: 'A very long title '.repeat(12), authors: ['Alexandrina Victoria Hanover-Windsor', 'Bartholomew Montgomery Fitzgerald'] };
const text = encodeCardCode(c);
assert.ok(bytes(text) <= 130, String(bytes(text)));
const lines = text.split('\n');
assert.ok(bytes(lines[2]!) <= 40 && lines[2]!.endsWith('…'));
assert.ok(lines[1]!.endsWith('…'));
assert.equal(lines[0], rust.callNumber);
assert.equal(lines.at(-1), 'booksorter 1');
assert.ok(lines.includes('ISBN 9781718500440') && lines.includes('2018'));
});
test('multi-byte characters are never split', () => {
const c = { ...rust, title: 'é'.repeat(100), authors: ['日本語の著者'.repeat(10)] };
const text = encodeCardCode(c);
assert.ok(bytes(text) <= 130);
assert.ok(!text.includes('�'));
assert.equal(parseCardCode(text)?.callNumber, rust.callNumber);
});
test('parse ignores other codes and tolerates CRLF, trailing spaces and unknown lines', () => {
assert.equal(parseCardCode('https://example.com/book'), null);
assert.equal(parseCardCode('QA76.73.R87 K53 2018\nTitle\nA\nsomething else'), null);
assert.equal(parseCardCode('not a call number\nTitle\nA\nbooksorter 1'), null);
const p = parseCardCode('QA76.73.R87 K53 2018 ~ \r\nTitle \r\nA; B\r\n2018\r\nfuture: thing\r\nISBN 9781718500440\r\nbooksorter 2 \r\n');
assert.deepEqual(p, { callNumber: 'QA76.73.R87 K53 2018', approximate: true, title: 'Title', authors: ['A', 'B'], isbn13: '9781718500440', year: 2018 });
});
-68
View File
@@ -1,68 +0,0 @@
import { parseCallNumber } from './callnumber.ts';
/** What the QR code on a printed card says. See README: plain text, one fact per line. */
export interface CardCode {
callNumber: string; approximate: boolean; title: string; authors: string[];
isbn13: string | null; year: number | null;
}
export const MARKER_NAME = 'booksorter';
export const MARKER = `${MARKER_NAME} 1`;
export const MAX_BYTES = 130;
export const MAX_AUTHOR_BYTES = 40;
const ELLIPSIS = '…';
const encoder = new TextEncoder();
const byteLength = (s: string): number => encoder.encode(s).length;
const oneLine = (s: string): string => s.replace(/\s+/g, ' ').trim();
/** Shorten to at most `max` UTF-8 bytes, ending in an ellipsis when something was cut. Never splits a character. */
function fit(s: string, max: number): string {
if (byteLength(s) <= max) return s;
const chars = Array.from(s);
while (chars.length > 0) {
chars.pop();
const t = chars.join('').trimEnd() + ELLIPSIS;
if (byteLength(t) <= max) return t;
}
return max >= byteLength(ELLIPSIS) ? ELLIPSIS : '';
}
export function encodeCardCode(c: CardCode): string {
const callNumber = oneLine(c.callNumber) + (c.approximate ? ' ~' : '');
const tail: string[] = [];
if (c.isbn13) tail.push(`ISBN ${c.isbn13}`);
if (c.year != null) tail.push(String(c.year));
tail.push(MARKER);
let authors = oneLine(c.authors.slice(0, 2).join('; '));
let title = oneLine(c.title);
const build = () => [callNumber, title, authors, ...tail].join('\n');
if (byteLength(build()) > MAX_BYTES) {
authors = fit(authors, MAX_AUTHOR_BYTES);
title = '';
const room = MAX_BYTES - byteLength(build());
title = fit(oneLine(c.title), Math.max(0, room));
}
return build();
}
/** Returns null for anything that is not a Booksorter card (other QR codes on a book, for example). */
export function parseCardCode(text: string): CardCode | null {
const lines = text.split(/\r?\n/).map((l) => l.trimEnd());
while (lines.length > 0 && lines[lines.length - 1]!.trim() === '') lines.pop();
if (lines.length < 4) return null;
if (!/^booksorter \d+$/.test(lines[lines.length - 1]!.trim())) return null;
let callNumber = lines[0]!.trim();
let approximate = false;
if (callNumber.endsWith(' ~')) { approximate = true; callNumber = callNumber.slice(0, -2).trim(); }
if (!callNumber || !parseCallNumber(callNumber)) return null;
const authors = lines[2]!.split(';').map((a) => a.trim()).filter(Boolean);
let isbn13: string | null = null, year: number | null = null;
for (const line of lines.slice(3, -1)) {
const t = line.trim();
const isbn = /^ISBN (\d{13})$/.exec(t);
if (isbn) { isbn13 = isbn[1]!; continue; }
if (/^\d{4}$/.test(t)) year = Number(t);
}
return { callNumber, approximate, title: lines[1]!.trim(), authors, isbn13, year };
}
+7
View File
@@ -0,0 +1,7 @@
import type { Hierarchy } from './types.ts';
/** The levels worth showing, general to specific: from the subclass down (the main class only when nothing else is known). */
export function displayLevels(h: Hierarchy): string[] {
const outline = h.outline.length > 1 ? h.outline.slice(1) : h.outline;
return [...outline, ...h.tail].filter((l, i, a) => l.trim() && l !== a[i - 1]);
}
+8 -2
View File
@@ -1,6 +1,6 @@
export type Confidence = 'exact' | 'approximate' | 'manual';
export type Status = 'pending' | 'resolved' | 'needs_attention';
export type Source = 'loc-isbn' | 'loc-lccn' | 'ol-edition' | 'loc-title' | 'ol-work' | 'similar' | 'manual' | 'card';
export type Source = 'loc-isbn' | 'loc-lccn' | 'ol-edition' | 'loc-title' | 'ol-work' | 'similar' | 'manual';
export interface Book {
id: number; isbn13: string | null; lccn: string | null;
title: string; subtitle: string | null; authors: string[];
@@ -9,7 +9,11 @@ export interface Book {
confidence: Confidence | null; source: Source | null; dewey: string | null;
status: Status; attentionReason: string | null; manualOverride: boolean;
inQueue: boolean; printedAt: string | null; createdAt: string; updatedAt: string;
/** Place words from the catalogue record's subject heading. null: not looked for yet; []: looked, none. */
hierarchyTail: string[] | null;
}
/** A call number explained in plain words: `outline` from the LC outline (main class first), `tail` from the record's subject. */
export interface Hierarchy { outline: string[]; tail: string[] }
export interface BookMeta {
title: string; subtitle?: string; authors: string[]; publisher?: string;
year?: number; subjects: string[]; lccn?: string;
@@ -25,10 +29,12 @@ export interface Resolution {
callNumber: string | null; sortKey: string | null;
confidence: 'exact' | 'approximate' | null; source: Source | null;
dewey: string | null;
/** The tail for this book; null when the catalogue could not be asked (so it is looked for again later). */
tail?: string[] | null;
reason: string | null; // set when callNumber is null
}
export interface CardData {
callNumber: string; className: string | null; subclassName: string | null;
callNumber: string; hierarchy: Hierarchy;
title: string; authors: string[]; publisher: string | null; year: number | null;
subjects: string[]; isbn13: string | null; approximate: boolean;
}
+1 -31
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, showToast } from './toast-store.ts';
import { showError } 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,33 +41,3 @@ 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;
}
+2 -2
View File
@@ -1,4 +1,4 @@
import type { Book, SearchResult, Settings } from '../shared/types.ts';
import type { Book, Hierarchy, SearchResult, Settings } from '../shared/types.ts';
export class ApiError extends Error {}
@@ -34,7 +34,6 @@ 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)}`),
@@ -42,6 +41,7 @@ export const api = {
addManual: async (input: ManualInput) => toBook(await request('POST', '/api/books/manual', input)),
listBooks: (filter: 'all' | 'queue' | 'attention' = 'all', q = '') =>
request<Book[]>('GET', `/api/books?filter=${filter}&q=${encodeURIComponent(q)}`),
hierarchy: (id: number) => request<Hierarchy>('GET', `/api/books/${id}/hierarchy`),
patchBook: async (id: number, patch: BookPatch) => toBook(await request('PATCH', `/api/books/${id}`, patch)),
deleteBook: (id: number) => request<void>('DELETE', `/api/books/${id}`),
/** Fire and forget while the page is closing. */
+1 -1
View File
@@ -8,7 +8,7 @@ function book(id: number, over: Partial<Book>): Book {
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: `2026-01-01T00:00:0${id}Z`, updatedAt: '', ...over,
printedAt: null, hierarchyTail: null, createdAt: `2026-01-01T00:00:0${id}Z`, updatedAt: '', ...over,
};
}
const ready = (id: number, over: Partial<Book> = {}) => book(id, { status: 'resolved', callNumber: 'QA76.73 .R87 K53 2018', sortKey: 'k' + id, ...over });
+1 -2
View File
@@ -2,12 +2,11 @@ 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 : source === 'card' ? CARD_TIP : APPROX_TIP;
const tip = similar ? SIMILAR_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);
+17
View File
@@ -11,6 +11,7 @@ import { Panel } from './Panel.tsx';
import { moveActive, ResultList } from './Results.tsx';
import { Spinner } from './StateMark.tsx';
import { composeNumber, findNeighbours } from '../shelve.ts';
import { displayLevels } from '../../shared/hierarchy.ts';
/** `new` may carry what was typed in the entry box. */
export type EditorTarget = { kind: 'edit'; id: number } | { kind: 'new'; title?: string; authors?: string };
@@ -48,6 +49,15 @@ function EditorForm({ book, fixing, initial, onClose }: {
const [busy, setBusy] = useState(false);
const [confirming, setConfirming] = useState(false);
// Where the call number sits in the classification, in words (from the server, which holds the outline).
const [levels, setLevels] = useState<string[]>([]);
useEffect(() => {
if (!book) return;
let current = true;
api.hierarchy(book.id).then(h => { if (current) setLevels(displayLevels(h)); }, () => {});
return () => { current = false; };
}, [book?.id, book?.callNumber, book?.hierarchyTail]);
async function run(fn: () => Promise<void>) {
setBusy(true); setError('');
try { await fn(); } catch (e) { setError((e as Error).message); }
@@ -123,6 +133,13 @@ function EditorForm({ book, fixing, initial, onClose }: {
<input class="mono" value={callNumber} onInput={e => setCallNumber(e.currentTarget.value)} />
<span class="help">{book ? 'Changing this locks the number' : 'Optional. Leave it empty to have it looked up.'}</span>
</label>
{book && levels.length ? (
<p class="crumbs" aria-label="Where this number sits in the classification">
{levels.map((l, i) => i === levels.length - 1
? <span key={i} class="crumb-last">{l}</span>
: <span key={i}>{l} <span aria-hidden="true">›</span> </span>)}
</p>
) : null}
<ShelveWith exclude={book?.id} compose={neighbour => composeNumber(neighbour, splitAuthors(authors), title, yearValue(year))}
onChoose={setCallNumber} />
{error ? <p class="error" role="alert">{error}</p> : null}
-31
View File
@@ -118,34 +118,3 @@ 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 });
});
+11 -23
View File
@@ -1,12 +1,10 @@
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 }
/** `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 }
export interface DecodeOutcome { isbn: string | null; other: string | null }
// ---- image operations (grey, one byte per pixel) -------------------------------------------------------
@@ -88,12 +86,6 @@ 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);
@@ -105,19 +97,18 @@ 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: { ...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) },
{ 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) },
];
/** For the whole frame, which is too big to enlarge: no upscaling. */
export const WHOLE_VARIANTS: Variant[] = [
{ name: 'whole', opts: { ...WITH_QR, binarizer: 'LocalAverage' }, prep: g => g },
{ name: 'whole', opts: { ...BASE, 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; format?: string }[], into: DecodeOutcome): void {
function judge(codes: { text: 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;
}
@@ -127,9 +118,6 @@ 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. */
@@ -146,14 +134,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, card: null };
const out: DecodeOutcome = { isbn: null, other: null };
const began = now(), g = toGrey(p);
let cursor = st.cursor;
if (wantsFull(st)) {
for (const v of WHOLE_VARIANTS) if (!found(out)) await tryVariant(g, v, {}, out);
for (const v of WHOLE_VARIANTS) if (!out.isbn) await tryVariant(g, v, {}, out);
} else {
await tryVariant(g, VARIANTS[0]!, {}, out);
for (let i = 0; i < REST.length && !found(out) && now() - began <= LIVE_BUDGET_MS; i++) {
for (let i = 0; i < REST.length && !out.isbn && now() - began <= LIVE_BUDGET_MS; i++) {
await tryVariant(g, REST[cursor]!, {}, out);
cursor = (cursor + 1) % REST.length;
}
@@ -163,12 +151,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, card: null };
const out: DecodeOutcome = { isbn: null, other: 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 (found(out)) return out;
if (out.isbn) return out;
}
}
return out;
+1 -1
View File
@@ -8,7 +8,7 @@ function book(id: number, over: Partial<Book>): Book {
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: 'resolved', attentionReason: null, manualOverride: false, inQueue: false,
printedAt: null, createdAt: '', updatedAt: '', ...over,
printedAt: null, hierarchyTail: null, createdAt: '', updatedAt: '', ...over,
};
}
const qa = (id: number, key: string) => book(id, { callNumber: 'QA76.73 .R87', sortKey: key });
+1 -11
View File
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { acceptCard, acceptRead, markCardEmitted, markEmitted, newReadState } from './readstate.ts';
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
const ISBN = '9780306406157';
@@ -46,13 +46,3 @@ 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,15 +35,3 @@ 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 } };
}
+4 -15
View File
@@ -1,5 +1,5 @@
import { prepareZXingModule } from 'zxing-wasm/reader';
import { acceptCard, acceptRead, markCardEmitted, markEmitted, newReadState } from './readstate.ts';
import { acceptRead, 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,8 +62,6 @@ 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). */
@@ -150,11 +148,6 @@ 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());
@@ -187,17 +180,13 @@ 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, card: null, saved: null };
return { isbn: out.isbn, other, saved: 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 };
if (other) return { isbn: null, other, saved: null };
return { isbn: null, other: null, saved: best ? await saveFailed(best.full) : null };
} finally {
burst = false;
}
+1 -1
View File
@@ -8,7 +8,7 @@ function book(id: number, title: string, sortKey: string | null): Book {
id, isbn13: null, lccn: null, title, subtitle: null, authors: [], publisher: null, year: null,
subjects: [], callNumber: null, sortKey, confidence: null, source: null, dewey: null,
status: 'resolved', attentionReason: null, manualOverride: false, inQueue: true,
printedAt: null, createdAt: '', updatedAt: '',
printedAt: null, hierarchyTail: null, createdAt: '', updatedAt: '',
};
}
+4
View File
@@ -297,3 +297,7 @@ main { max-width: var(--page-max); margin: 0 auto; padding: var(--space-6) var(-
.scan-left { position: static; }
.panel { width: 100%; }
}
/* Where a call number sits in the classification: one line of secondary text, the most specific level in full colour. */
.crumbs { margin: 0; font-size: var(--text-sm); color: var(--muted); line-height: var(--leading); }
.crumb-last { color: var(--text); }
+4 -14
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, onCard, captureRef }: { onIsbn: (isbn: string) => void; onCard: (text: string) => void; captureRef: { current: (() => boolean) | null } }) {
export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void; captureRef: { current: (() => boolean) | null } }) {
const cam = useCamera();
const video = useRef<HTMLVideoElement>(null);
const scanner = useRef<Scanner | null>(null);
@@ -65,18 +65,9 @@ export function Camera({ onIsbn, onCard, captureRef }: { onIsbn: (isbn: string)
say(`Read ${isbn}`, 'ok');
onIsbn(isbn);
};
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: () => {} });
const handlers = useRef({ onIsbn: gotIsbn, 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: '' });
@@ -100,7 +91,7 @@ export function Camera({ onIsbn, onCard, captureRef }: { onIsbn: (isbn: string)
setState('starting'); setProblem('');
try {
const sc = await startScanner(video.current, getCamera().deviceId || undefined, {
onIsbn: i => handlers.current.onIsbn(i), onCard: t => handlers.current.onCard(t), onOther: c => handlers.current.onOther(), onEnded: () => handlers.current.onEnded(),
onIsbn: i => handlers.current.onIsbn(i), 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; }
@@ -130,8 +121,7 @@ export function Camera({ onIsbn, onCard, captureRef }: { onIsbn: (isbn: string)
try {
const r = await sc.capture(n => say(`Trying… ${n} frames`, 'info', true));
if (scanner.current !== sc) return;
if (r.card) gotCard(r.card);
else if (r.isbn) gotIsbn(r.isbn);
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 {
+2 -3
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef } from 'preact/hooks';
import { addByIsbn, addFromCard } from '../actions.ts';
import { addByIsbn } from '../actions.ts';
import { dialogOpen } from '../dialog.ts';
import { unlockAudio } from '../sound.ts';
import type { EditorTarget } from '../components/Editor.tsx';
@@ -53,8 +53,7 @@ export function Scan({ onEdit }: { onEdit: (t: EditorTarget) => void }) {
return (
<div class="scan">
<div class="scan-left">
<Camera captureRef={capture} onIsbn={isbn => { void addByIsbn(isbn); }}
onCard={text => { void addFromCard(text, id => onEdit({ kind: 'edit', id })); }} />
<Camera captureRef={capture} onIsbn={isbn => { void addByIsbn(isbn); }} />
<LastScan onFix={fix} />
<Entry inputRef={entry} onEdit={onEdit} />
</div>