Redesign the interface around Scan and Library, classify uncatalogued books from similar ones
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
308c0e1ed3
commit
6cec404e21
71 files changed
+8634
-1502
No files matched your search
+3
-2
@@ -90,9 +90,10 @@ export function createJobs(deps: {
|
||||
if (book.year) input.year = book.year;
|
||||
const label = book.isbn13 ?? book.title;
|
||||
const started = Date.now();
|
||||
let similar = '';
|
||||
const took = () => `${Date.now() - started} ms`;
|
||||
try {
|
||||
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final });
|
||||
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final, onSimilar: (d) => { similar = d; } });
|
||||
attempts.delete(id);
|
||||
const cur = db.getBook(id);
|
||||
if (!cur) return;
|
||||
@@ -106,7 +107,7 @@ export function createJobs(deps: {
|
||||
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
|
||||
source: res.source, dewey, status: 'resolved', attentionReason: null,
|
||||
});
|
||||
log(`[lookup] ${label}: ${res.callNumber} (${res.source}) in ${took()}`);
|
||||
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 });
|
||||
|
||||
@@ -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 });
|
||||
const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names, topics: [] });
|
||||
|
||||
test('normalizeTitle', () => {
|
||||
assert.equal(normalizeTitle('The Mythical Man-Month: Essays on Software'), 'mythical man month');
|
||||
|
||||
@@ -217,7 +217,7 @@ test('title tier is skipped when the book has no author', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ title: 'The Mythical Man-Month' });
|
||||
assert.equal(res.callNumber, null);
|
||||
assert.equal(f.locCalls().length, 0);
|
||||
assert.equal(f.locCalls().filter((c) => decodeURIComponent(c).includes('bath.title')).length, 0);
|
||||
});
|
||||
|
||||
test('title tier ignores records for a different author', async () => {
|
||||
@@ -255,3 +255,69 @@ test('tolerateLocFailure: nothing from Open Library either still fails', async (
|
||||
const r = createResolver({ fetch: locDown(f), cache: memCache(), sleep: noSleep });
|
||||
await assert.rejects(r.resolve({ isbn13: '9780999999998' }, { tolerateLocFailure: true }), TemporaryError);
|
||||
});
|
||||
|
||||
const WIND_RIVER = { title: 'Beyond Trails in the Wind River Mountains of Wyoming', author: 'Nancy Pallister', year: 2025 };
|
||||
|
||||
test('similar tier: a book no catalogue has borrows the class of books on its subject', async () => {
|
||||
const f = fixtureFetch();
|
||||
let detail = '';
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep })
|
||||
.resolve(WIND_RIVER, { onSimilar: (d) => { detail = d; } });
|
||||
assert.equal(res.callNumber, 'GV199.42.W82 P35 2025');
|
||||
assert.equal(res.source, 'similar');
|
||||
assert.equal(res.confidence, 'approximate');
|
||||
assert.match(detail, /^GV199\.42\.W82 \(\d+ of \d+ candidates\)$/);
|
||||
});
|
||||
|
||||
test('similar tier: nonsense words find nothing', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep })
|
||||
.resolve({ title: 'Xyzzy Plugh Quux Handbook', author: 'A. Nobody', year: 2020 });
|
||||
assert.equal(res.callNumber, null);
|
||||
assert.equal(res.source, null);
|
||||
});
|
||||
|
||||
test('similar tier: not tried for a book with no title', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780999999998' });
|
||||
assert.equal(res.callNumber, null);
|
||||
assert.equal(f.calls.some((c) => c.includes('q=')), false);
|
||||
});
|
||||
|
||||
test('similar tier: searches are cached and make at most 3 Open Library and 2 LoC requests', async () => {
|
||||
const f = fixtureFetch();
|
||||
const cache = memCache();
|
||||
const r = createResolver({ fetch: f.fetch, cache, sleep: noSleep });
|
||||
await r.resolve(WIND_RIVER);
|
||||
const ol = f.calls.filter((c) => c.includes('openlibrary.org') && c.includes('q=')).length;
|
||||
assert.ok(ol >= 1 && ol <= 3, String(ol));
|
||||
assert.ok(f.locCalls().filter((c) => decodeURIComponent(c).includes('bath.any')).length <= 2);
|
||||
const before = f.calls.length;
|
||||
const again = await r.resolve(WIND_RIVER);
|
||||
assert.equal(again.callNumber, 'GV199.42.W82 P35 2025');
|
||||
// Only the (uncached) title search and nothing for the similar tier.
|
||||
assert.equal(f.calls.slice(before).filter((c) => c.includes('q=') || c.includes('bath.any')).length, 0);
|
||||
});
|
||||
|
||||
test('similar tier: the first four tiers win when they find a number', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281' });
|
||||
assert.equal(res.source, 'loc-isbn');
|
||||
assert.equal(f.calls.some((c) => c.includes('bath.any')), false);
|
||||
});
|
||||
|
||||
test('similar tier: if the LoC is down, Open Library candidates alone vote', async () => {
|
||||
const f = fixtureFetch();
|
||||
const inner = f.fetch;
|
||||
const failLoc = ((u: string | URL | Request) => String(u).includes('loc.gov') ? Promise.reject(new Error('down')) : inner(u)) as typeof fetch;
|
||||
const res = await createResolver({ fetch: failLoc, cache: memCache(), sleep: noSleep }).resolve(WIND_RIVER, { tolerateLocFailure: true });
|
||||
assert.equal(res.callNumber, 'GV199.42.W82 P35 2025');
|
||||
assert.equal(res.source, 'similar');
|
||||
});
|
||||
|
||||
test('similar tier: a LoC failure is still an error when not tolerated and nothing was found', async () => {
|
||||
const f = fixtureFetch();
|
||||
const inner = f.fetch;
|
||||
const failLoc = ((u: string | URL | Request) => String(u).includes('loc.gov') ? Promise.reject(new Error('down')) : inner(u)) as typeof fetch;
|
||||
await assert.rejects(createResolver({ fetch: failLoc, cache: memCache(), sleep: noSleep }).resolve(WIND_RIVER), TemporaryError);
|
||||
});
|
||||
@@ -4,6 +4,8 @@ import { chooseCallNumber } from './choose.ts';
|
||||
import { createLoc } from '../sources/loc.ts';
|
||||
import { createOpenLibrary } from '../sources/openlibrary.ts';
|
||||
import type { OlInfo } from '../sources/openlibrary.ts';
|
||||
import { classified, finishSimilar, keywordsOf, mergeCandidates, queryPlan, voteSimilar } from './similar.ts';
|
||||
import type { SimilarCandidate } from './similar.ts';
|
||||
import type { MarcFields } from '../sources/marc.ts';
|
||||
import { TemporaryError } from '../sources/http.ts';
|
||||
import { recordMatches } from './match.ts';
|
||||
@@ -16,6 +18,8 @@ export interface ResolveOpts {
|
||||
onMeta?: (meta: BookMeta) => void;
|
||||
/** Last-attempt mode: a Library of Congress failure is not fatal; use Open Library's numbers if it has any. */
|
||||
tolerateLocFailure?: boolean;
|
||||
/** Called when the similar-books tier chose the number, for example "GV199.42.W8 (4 of 9 candidates)". */
|
||||
onSimilar?: (detail: string) => void;
|
||||
}
|
||||
|
||||
export interface Resolver {
|
||||
@@ -51,11 +55,13 @@ export function createResolver(deps: {
|
||||
sleep?: (ms: number) => Promise<void>;
|
||||
}): Resolver {
|
||||
const ol = createOpenLibrary({ fetch: deps.fetch, cache: deps.cache });
|
||||
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
||||
const loc = createLoc({
|
||||
fetch: deps.fetch, cache: deps.cache,
|
||||
intervalMs: deps.locIntervalMs ?? 6000,
|
||||
sleep: deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))),
|
||||
sleep,
|
||||
});
|
||||
const OL_GAP_MS = 1000;
|
||||
|
||||
async function resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution> {
|
||||
// In tolerant mode the first LoC failure switches the LoC tiers off for the rest of this lookup.
|
||||
@@ -151,6 +157,46 @@ export function createResolver(deps: {
|
||||
forChoose(meta), exactSource,
|
||||
);
|
||||
|
||||
// Tier 5: borrow the class from similar books. Last resort, and only for a book with a title.
|
||||
let olError: unknown = null;
|
||||
if (!chosen && meta?.title) {
|
||||
const kw = keywordsOf(meta.title, meta.subtitle, meta.subjects);
|
||||
const groups: SimilarCandidate[][] = [];
|
||||
let found = 0;
|
||||
const plan = kw.title.length >= 2 ? queryPlan(kw.title) : queryPlan([...kw.title, ...kw.extra].slice(0, 3), 1);
|
||||
for (const [i, words] of plan.entries()) {
|
||||
if (i > 0) await sleep(OL_GAP_MS);
|
||||
try {
|
||||
const docs = await ol.similar(words);
|
||||
groups.push(docs.map((d) => ({ title: d.title, ...(d.subtitle ? { subtitle: d.subtitle } : {}), subjects: d.subjects, lcc: d.lcc })));
|
||||
} catch (e) {
|
||||
if (e instanceof TemporaryError) { olError = e; break; }
|
||||
throw e;
|
||||
}
|
||||
found = classified(groups.flat());
|
||||
if (found >= 5) break;
|
||||
}
|
||||
const locWords = kw.title.slice(0, 3);
|
||||
if (locWords.length > 0) {
|
||||
for (const words of locWords.length > 2 ? [locWords, locWords.slice(0, 2)] : [locWords]) {
|
||||
const recs = await locCall(() => loc.byKeywords(words));
|
||||
groups.push(recs.map((r) => ({
|
||||
title: r.meta.title ?? '', ...(r.meta.subtitle ? { subtitle: r.meta.subtitle } : {}),
|
||||
subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((c) => c.raw),
|
||||
})));
|
||||
if (classified(groups.at(-1)!) >= 5 || locError) break;
|
||||
}
|
||||
}
|
||||
const vote = voteSimilar(kw, mergeCandidates(groups));
|
||||
if (vote) {
|
||||
const done = finishSimilar(vote.key, forChoose(meta));
|
||||
if (done) {
|
||||
chosen = { callNumber: done.callNumber, sortKey: done.sortKey, confidence: 'approximate', source: 'similar' };
|
||||
opts?.onSimilar?.(`${vote.key} (${vote.support} of ${vote.counted} candidates)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const dewey = locRecs.map((r) => r.dewey).find(Boolean) ?? edition?.dewey ?? work?.dewey
|
||||
?? locTitleRecs.map((r) => r.dewey).find(Boolean) ?? null;
|
||||
|
||||
@@ -162,6 +208,7 @@ export function createResolver(deps: {
|
||||
}
|
||||
// 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,
|
||||
reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library or the Library of Congress',
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { classified, finishSimilar, keywordsOf, mergeCandidates, queryPlan, stem, voteSimilar } from './similar.ts';
|
||||
import type { SimilarCandidate } from './similar.ts';
|
||||
import { parseMarcXml } from '../sources/marc.ts';
|
||||
import { parseSimilar } from '../sources/openlibrary.ts';
|
||||
|
||||
const FIX = join(import.meta.dirname, '..', 'sources', 'fixtures');
|
||||
const c = (title: string, lcc: string[], subjects: string[] = []): SimilarCandidate => ({ title, subjects, lcc });
|
||||
|
||||
test('stem folds plurals and -ing', () => {
|
||||
assert.equal(stem('hikes'), stem('hiking'));
|
||||
assert.equal(stem('mountains'), stem('mountain'));
|
||||
assert.equal(stem('birds'), stem('bird'));
|
||||
});
|
||||
|
||||
test('keywords drop stop and generic words, numbers and short words', () => {
|
||||
const k = keywordsOf('Beyond Trails in the Wind River Mountains of Wyoming');
|
||||
assert.deepEqual([...k.title].sort(), ['mountains', 'river', 'trails', 'wind', 'wyoming']);
|
||||
assert.equal(k.title[0], 'mountains'); // longest first
|
||||
assert.deepEqual(keywordsOf('100 Classic Hikes Utah').title.sort(), ['hikes', 'utah']);
|
||||
assert.deepEqual(keywordsOf('The Complete Guide to the New Edition').title, []);
|
||||
});
|
||||
|
||||
test('subjects add extra keywords, without noise or repeats of title words', () => {
|
||||
const k = keywordsOf('Guns of August', undefined, ['World War, 1914-1918', 'Accessible book', 'Campaigns', 'Guns']);
|
||||
assert.ok(k.extra.includes('campaigns'));
|
||||
assert.ok(!k.extra.includes('accessible'));
|
||||
assert.ok(!k.extra.includes('guns'));
|
||||
});
|
||||
|
||||
test('query plan: widest first, fewer keywords after, at most 3, never one word for a multi-word title', () => {
|
||||
const plan = queryPlan(['a1', 'b2', 'c3', 'd4', 'e5']);
|
||||
assert.deepEqual(plan.map((p) => p.length), [5, 4, 3]);
|
||||
assert.deepEqual(plan[2], ['a1', 'b2', 'c3']);
|
||||
assert.deepEqual(queryPlan(['aa', 'bb']), [['aa', 'bb']]);
|
||||
assert.deepEqual(queryPlan([]), []);
|
||||
});
|
||||
|
||||
test('the same book from two searches counts once', () => {
|
||||
const m = mergeCandidates([[c('Hiking Utah', ['GV199.42.U8 A1'])], [c('hiking utah', ['GV199.42.U8 B2'], ['Utah'])]]);
|
||||
assert.equal(m.length, 1);
|
||||
assert.equal(m[0]!.lcc.length, 2);
|
||||
assert.equal(classified(m), 1);
|
||||
});
|
||||
|
||||
test('votes by class key; two agreeing books win', () => {
|
||||
const kw = keywordsOf('Hiking Utah Canyons');
|
||||
const v = voteSimilar(kw, [
|
||||
c('Hiking Utah canyons', ['GV199.42.U8 B1 2001']),
|
||||
c('Utah canyons hiking guide', ['GV199.42.U8 C2 2005']),
|
||||
c('Utah hiking', ['GV199.42.U8 D3 2010']),
|
||||
c('Canyons of the Southwest', ['F788 .E5']),
|
||||
]);
|
||||
assert.ok(v);
|
||||
assert.equal(v.key, 'GV199.42.U8');
|
||||
assert.equal(v.support, 3);
|
||||
});
|
||||
|
||||
test('one unrelated popular book does not capture a generic title', () => {
|
||||
const kw = keywordsOf('Summer Guns');
|
||||
const v = voteSimilar(kw, [
|
||||
c('Guns of August', ['D530 .T8']),
|
||||
c('Gun control', ['HV7436 .G86']),
|
||||
c('Summer nights', ['PS3566 .A1']),
|
||||
c('Summer rain', ['QC925 .R3']),
|
||||
]);
|
||||
assert.equal(v, null);
|
||||
});
|
||||
|
||||
test('a single candidate needs to match most of the keywords', () => {
|
||||
const kw = keywordsOf('Alpine Wildflowers Colorado');
|
||||
assert.equal(voteSimilar(kw, [c('Alpine wildflowers of Colorado', ['QK144 .A4'])])?.key, 'QK144');
|
||||
assert.equal(voteSimilar(kw, [c('Alpine skiing', ['GV854 .A4']), c('Colorado history', ['F776 .H5'])]), null);
|
||||
});
|
||||
|
||||
test('candidates matching too few keywords are ignored', () => {
|
||||
const kw = keywordsOf('Alpine Wildflowers Colorado');
|
||||
assert.equal(voteSimilar(kw, [c('Alpine skiing', ['GV854 .A4']), c('Alpine lakes', ['GB1 .A1']), c('Alpine huts', ['GV854 .B1'])]), null);
|
||||
});
|
||||
|
||||
test('scattered fine keys fall back to the class, and scattered classes return nothing', () => {
|
||||
const kw = keywordsOf('Bread Baking Pizza');
|
||||
const v = voteSimilar(kw, [
|
||||
c('Bread baking', ['TX769 .A1 2000']),
|
||||
c('Pizza and bread', ['TX770.P58 B1 2001']),
|
||||
c('Baking bread, pizza', ['TX770.P58 C1 2002']),
|
||||
c('Baking pizza', ['TX770.P6 D1 2003']),
|
||||
]);
|
||||
assert.ok(v);
|
||||
assert.match(v.key, /^TX7/);
|
||||
assert.equal(voteSimilar(kw, [c('Bread baking', ['TX769 .A1']), c('Pizza bread', ['QA76 .B1']), c('Baking pizza', ['HD9 .C1'])]), null);
|
||||
});
|
||||
|
||||
test('neighbouring classes do not cancel each other out', () => {
|
||||
const kw = keywordsOf('Western Birds Field');
|
||||
const v = voteSimilar(kw, [
|
||||
c('Western birds', ['QL683.W4 A1']), c('Field birds western', ['QL683.W4 B1']),
|
||||
c('Birds field', ['QL681 .C1']), c('Birds of the field', ['QL681 .D1']),
|
||||
]);
|
||||
assert.ok(v);
|
||||
assert.match(v.key, /^QL68[13]/);
|
||||
});
|
||||
|
||||
test('author-numbered literature classes are never borrowed', () => {
|
||||
const kw = keywordsOf('Dark Summer Novel');
|
||||
assert.equal(voteSimilar(kw, [c('Dark summer', ['PS3562 .A1']), c('Summer dark novel', ['PS3562 .A2'])]), null);
|
||||
});
|
||||
|
||||
test('candidates without a parseable call number do not vote', () => {
|
||||
const kw = keywordsOf('Hiking Utah');
|
||||
assert.equal(voteSimilar(kw, [c('Hiking Utah', ['CPB Box no. 1']), c('Utah hiking', [])]), null);
|
||||
});
|
||||
|
||||
test('finish: own author cutter and year after the borrowed key', () => {
|
||||
assert.deepEqual(finishSimilar('GV199.42.W8', { authors: ['Nancy Pallister'], title: 'Beyond Trails', year: 2025 })!.callNumber, 'GV199.42.W8 P35 2025');
|
||||
assert.equal(finishSimilar('TX769', { authors: ['Ken Forkish'], title: 'Flour', year: 2012 })!.callNumber, 'TX769.F67 2012');
|
||||
assert.equal(finishSimilar('QL683', { authors: [], title: 'A Field Guide' })!.callNumber, 'QL683.F54');
|
||||
assert.equal(finishSimilar('???', { authors: [], title: 'x' }), null);
|
||||
});
|
||||
|
||||
test('real responses: Wind River Mountains votes for hiking in Wyoming, nonsense for nothing', () => {
|
||||
const ol = parseSimilar(readFileSync(join(FIX, 'ol-similar-mountains-wyoming-trails.json'), 'utf8'));
|
||||
const loc = parseMarcXml(readFileSync(join(FIX, 'loc-similar-mountains-wyoming.xml'), 'utf8'));
|
||||
const cands = mergeCandidates([
|
||||
ol.map((d) => ({ title: d.title, ...(d.subtitle ? { subtitle: d.subtitle } : {}), subjects: d.subjects, lcc: d.lcc })),
|
||||
loc.map((r) => ({ title: r.meta.title ?? '', subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((x) => x.raw) })),
|
||||
]);
|
||||
const v = voteSimilar(keywordsOf('Beyond Trails in the Wind River Mountains of Wyoming'), cands);
|
||||
assert.ok(v);
|
||||
assert.match(v.key, /^GV199\.42/);
|
||||
assert.ok(v.support >= 2);
|
||||
assert.equal(voteSimilar(keywordsOf('Xyzzy Plugh Quux Handbook'), cands), null);
|
||||
});
|
||||
|
||||
test('real responses: bread books vote for TX769', () => {
|
||||
const loc = parseMarcXml(readFileSync(join(FIX, 'loc-similar-artisan-flour.xml'), 'utf8'));
|
||||
const cands = loc.map((r) => ({ title: r.meta.title ?? '', subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((x) => x.raw) }));
|
||||
const v = voteSimilar(keywordsOf('Artisan Flour Water Bread'), cands);
|
||||
assert.equal(v?.key, 'TX769');
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
import type { CallNumber } from '../../shared/callnumber.ts';
|
||||
import { cardLines, formatCallNumber, parseCallNumber, sortKey, withYear } from '../../shared/callnumber.ts';
|
||||
import { cutterFor, mainEntry } from '../../shared/cutter.ts';
|
||||
|
||||
// The fifth tier: when no catalogue has the book, shelve it where books on the same subject are shelved.
|
||||
// Everything here is pure: the searches live in sources/, the wiring in resolver.ts.
|
||||
|
||||
/** A book found by a keyword search, from either Open Library or the Library of Congress. */
|
||||
export interface SimilarCandidate { title: string; subtitle?: string; subjects: string[]; lcc: string[] }
|
||||
|
||||
export interface Keywords {
|
||||
/** From the title and subtitle, most distinctive first. These drive the queries and the support rules. */
|
||||
title: string[];
|
||||
/** From the book's own subjects; they only add a little to a candidate's score. */
|
||||
extra: string[];
|
||||
}
|
||||
|
||||
export interface Vote {
|
||||
/** The class key the winners share, for example GV199.42.W8 or TX769. */
|
||||
key: string;
|
||||
/** How many candidates voted for it, and how many candidates were counted at all. */
|
||||
support: number;
|
||||
counted: number;
|
||||
level: 'fine' | 'cutter' | 'class';
|
||||
}
|
||||
|
||||
const STOP = new Set(`a an the of in on at to for from by with without and or nor but as is are be was were it its this that these
|
||||
those into onto about over under between through up down out off than then so not no your you my our their his her
|
||||
guide guides book books edition editions complete completely new newly revised updated update third second first fourth fifth
|
||||
beyond handbook introduction intro essential essentials ultimate definitive classic classics best great little big way ways
|
||||
fundamentals basic basics practical modern vol volume part series story stories tales tale
|
||||
user users reference manual illustrated annotated expanded anniversary collection selected works day days year years
|
||||
one two three your more most all how what why who when where`.split(/\s+/));
|
||||
|
||||
// Words that turn up in Open Library subject lists without saying what a book is about.
|
||||
const SUBJECT_NOISE = new Set(`accessible protected daisy large print fiction nonfiction juvenile general history study
|
||||
lending library internet archive open in miscellanea miscellaneous`.split(/\s+/));
|
||||
|
||||
const plain = (s: string): string => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
|
||||
|
||||
/** A rough stem, so "hikes" matches "hiking" and "mountains" matches "mountain". */
|
||||
export function stem(w: string): string {
|
||||
let s = w;
|
||||
if (s.length > 4 && s.endsWith('ies')) s = s.slice(0, -3) + 'y';
|
||||
else if (s.length > 4 && /(ss|x|ch|sh)es$/.test(s)) s = s.slice(0, -2);
|
||||
else if (s.length > 3 && s.endsWith('s') && !s.endsWith('ss') && !s.endsWith('us')) s = s.slice(0, -1);
|
||||
if (s.length > 5 && s.endsWith('ing')) s = s.slice(0, -3);
|
||||
else if (s.length > 5 && s.endsWith('ed')) s = s.slice(0, -2);
|
||||
if (s.length > 3 && s.endsWith('e')) s = s.slice(0, -1);
|
||||
return s;
|
||||
}
|
||||
|
||||
function words(s: string): string[] {
|
||||
return plain(s).replace(/['’]s\b/g, '').split(/[^a-z0-9]+/).filter(Boolean);
|
||||
}
|
||||
|
||||
function usable(w: string): boolean {
|
||||
return w.length >= 3 && !/^\d+$/.test(w) && !STOP.has(w);
|
||||
}
|
||||
|
||||
/** Distinct words, longer (so rarer, on the whole) first; ties keep their order in the title. */
|
||||
function ranked(ws: string[]): string[] {
|
||||
const seen = new Set<string>();
|
||||
const out: { w: string; i: number }[] = [];
|
||||
ws.forEach((w, i) => {
|
||||
const s = stem(w);
|
||||
if (seen.has(s)) return;
|
||||
seen.add(s);
|
||||
out.push({ w, i });
|
||||
});
|
||||
return out.sort((a, b) => b.w.length - a.w.length || a.i - b.i).map((x) => x.w);
|
||||
}
|
||||
|
||||
export function keywordsOf(title: string, subtitle?: string, subjects: string[] = []): Keywords {
|
||||
const t = ranked(words(`${title} ${subtitle ?? ''}`).filter(usable));
|
||||
const have = new Set(t.map(stem));
|
||||
const counts = new Map<string, number>();
|
||||
for (const s of subjects) {
|
||||
for (const w of new Set(words(s).filter((x) => usable(x) && !SUBJECT_NOISE.has(x)))) {
|
||||
if (!have.has(stem(w))) counts.set(w, (counts.get(w) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
const extra = [...counts].sort((a, b) => b[1] - a[1] || b[0].length - a[0].length).slice(0, 4).map((x) => x[0]);
|
||||
return { title: t.slice(0, 8), extra };
|
||||
}
|
||||
|
||||
/** Normalised form of the keywords; the cache key for a search. */
|
||||
export function keywordKey(kws: string[]): string {
|
||||
return [...kws].map(stem).sort().join(' ');
|
||||
}
|
||||
|
||||
/** The keyword sets to try, widest first: all of them, then progressively fewer (dropping the shortest). At most `max`. */
|
||||
export function queryPlan(kws: string[], max = 3): string[][] {
|
||||
if (kws.length === 0) return [];
|
||||
const sizes = [kws.length, Math.ceil(kws.length * 0.7), Math.ceil(kws.length * 0.5)]
|
||||
.map((n) => (kws.length >= 2 ? Math.max(2, n) : n));
|
||||
const out: string[][] = [];
|
||||
for (const n of sizes) {
|
||||
if (out.length < max && !out.some((o) => o.length === n)) out.push(kws.slice(0, n));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Normalised main title, for spotting the same book coming back from two searches. */
|
||||
function titleId(c: SimilarCandidate): string {
|
||||
return plain(c.title.split(':')[0]!).replace(/[^a-z0-9]+/g, ' ').trim().replace(/^(a|an|the) /, '');
|
||||
}
|
||||
|
||||
/** One candidate per book: the same title from Open Library and the Library of Congress counts once. */
|
||||
export function mergeCandidates(groups: SimilarCandidate[][]): SimilarCandidate[] {
|
||||
const byId = new Map<string, SimilarCandidate>();
|
||||
for (const g of groups) {
|
||||
for (const c of g) {
|
||||
const id = titleId(c);
|
||||
if (!id) continue;
|
||||
const have = byId.get(id);
|
||||
if (!have) { byId.set(id, { ...c, subjects: [...c.subjects], lcc: [...c.lcc] }); continue; }
|
||||
have.subjects = [...new Set([...have.subjects, ...c.subjects])];
|
||||
have.lcc = [...have.lcc, ...c.lcc];
|
||||
have.subtitle ??= c.subtitle;
|
||||
}
|
||||
}
|
||||
return [...byId.values()];
|
||||
}
|
||||
|
||||
// Literature classes number each author, so a neighbour's number says nothing about this book.
|
||||
const AUTHOR_CLASSES = new Set(['PQ', 'PR', 'PS', 'PT', 'PZ']);
|
||||
|
||||
interface Keys { fine: string; cutter: string; cls: string }
|
||||
|
||||
/** The three granularities of one call number: with its topical cutter, with that cutter cut short, and the bare class. */
|
||||
function keysOf(cn: CallNumber): Keys | null {
|
||||
if (AUTHOR_CLASSES.has(cn.letters)) return null;
|
||||
const fine = cardLines(cn)[0];
|
||||
const c0 = cn.cutters[0];
|
||||
const cutter = cn.cutters.length >= 2 && c0 ? `${cn.letters}${cn.number}${cn.decimal ? '.' + cn.decimal : ''}.${c0.letter}${c0.digits.slice(0, 1)}` : fine;
|
||||
return { fine, cutter, cls: cn.letters + cn.number };
|
||||
}
|
||||
|
||||
/** A candidate's own keys: the ones its (possibly several) call numbers agree on most. */
|
||||
function candidateKeys(c: SimilarCandidate): Keys | null {
|
||||
const all = c.lcc.map(parseCallNumber).filter((x): x is CallNumber => x !== null).map(keysOf).filter((k): k is Keys => k !== null);
|
||||
if (all.length === 0) return null;
|
||||
const tally = new Map<string, { k: Keys; n: number }>();
|
||||
for (const k of all) {
|
||||
const t = tally.get(k.fine);
|
||||
if (t) t.n++; else tally.set(k.fine, { k, n: 1 });
|
||||
}
|
||||
return [...tally.values()].sort((a, b) => b.n - a.n)[0]!.k;
|
||||
}
|
||||
|
||||
interface Scored { keys: Keys; score: number; matched: number }
|
||||
|
||||
function scoreCandidate(kw: Keywords, c: SimilarCandidate): { score: number; matched: number } {
|
||||
const inTitle = new Set(words(`${c.title} ${c.subtitle ?? ''}`).map(stem));
|
||||
const inSubjects = new Set(c.subjects.flatMap(words).map(stem));
|
||||
let score = 0;
|
||||
let matched = 0;
|
||||
for (const k of kw.title) {
|
||||
const s = stem(k);
|
||||
const t = inTitle.has(s);
|
||||
const j = inSubjects.has(s);
|
||||
if (t || j) { matched++; score += j ? 1.5 : 1; }
|
||||
}
|
||||
for (const k of kw.extra) {
|
||||
const s = stem(k);
|
||||
if (inTitle.has(s) || inSubjects.has(s)) score += 0.5;
|
||||
}
|
||||
return { score, matched };
|
||||
}
|
||||
|
||||
function neighbours(a: string, b: string): boolean {
|
||||
const x = /^([A-Z]+)(\d+)/.exec(a);
|
||||
const y = /^([A-Z]+)(\d+)/.exec(b);
|
||||
return !!x && !!y && x[1] === y[1] && Math.abs(Number(x[2]) - Number(y[2])) <= 10;
|
||||
}
|
||||
|
||||
export interface VoteOpts {
|
||||
/** Share of the counted score the winner must hold. */
|
||||
minShare?: number;
|
||||
/** The winner must beat the runner-up by this factor. */
|
||||
margin?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vote for the class most similar books share. A candidate counts only if it matches enough of the title's
|
||||
* keywords. The winner needs real support (two candidates, or one that matches most keywords), a fair share of
|
||||
* all the score, and a clear lead; otherwise the next coarser key gets the same test, and then nothing wins.
|
||||
*/
|
||||
export function voteSimilar(kw: Keywords, cands: SimilarCandidate[], opts: VoteOpts = {}): Vote | null {
|
||||
const n = kw.title.length;
|
||||
if (n === 0) return null;
|
||||
const minMatched = n >= 3 ? 2 : 1;
|
||||
const minShare = opts.minShare ?? 0.25;
|
||||
const margin = opts.margin ?? 1.3;
|
||||
const counted: Scored[] = [];
|
||||
for (const c of cands) {
|
||||
const keys = candidateKeys(c);
|
||||
if (!keys) continue;
|
||||
const { score, matched } = scoreCandidate(kw, c);
|
||||
if (matched < minMatched) continue;
|
||||
counted.push({ keys, score, matched });
|
||||
}
|
||||
if (counted.length === 0) return null;
|
||||
const total = counted.reduce((a, c) => a + c.score, 0);
|
||||
for (const level of ['fine', 'cutter', 'class'] as const) {
|
||||
const groups = new Map<string, Scored[]>();
|
||||
for (const c of counted) {
|
||||
const key = c.keys[level === 'class' ? 'cls' : level];
|
||||
const g = groups.get(key);
|
||||
if (g) g.push(c); else groups.set(key, [c]);
|
||||
}
|
||||
const sums = [...groups].map(([key, g]) => ({ key, g, sum: g.reduce((a, c) => a + c.score, 0) }))
|
||||
.sort((a, b) => b.sum - a.sum || b.g.length - a.g.length || a.key.length - b.key.length);
|
||||
const win = sums[0]!;
|
||||
// Keys a few class numbers away (QL681 and QL683) are neighbours on the shelf: they do not count as rivals,
|
||||
// and their score counts towards the winner's share.
|
||||
const near = sums.slice(1).filter((x) => neighbours(win.key, x.key));
|
||||
const rival = sums.slice(1).find((x) => !neighbours(win.key, x.key));
|
||||
const family = win.sum + near.reduce((a, x) => a + x.sum, 0);
|
||||
const strong = win.g.length >= 2 || win.g.some((c) => c.matched / n >= 0.6);
|
||||
if (!strong) continue;
|
||||
if (family < minShare * total) continue;
|
||||
if (rival && win.sum < margin * rival.sum) continue;
|
||||
return { key: win.key, support: win.g.length, counted: counted.length, level };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Finish a borrowed class with this book's own author cutter and year, as a cataloguer would. */
|
||||
export function finishSimilar(
|
||||
key: string, meta: { authors: string[]; title: string; year?: number },
|
||||
): { callNumber: string; sortKey: string } | null {
|
||||
const cn = parseCallNumber(key);
|
||||
if (!cn) return null;
|
||||
const c = cutterFor(mainEntry(meta.authors, meta.title));
|
||||
let out: CallNumber = { ...cn, cutters: [...cn.cutters, { letter: c[0]!, digits: c.slice(1) }], suffix: '' };
|
||||
if (meta.year) out = withYear(out, meta.year);
|
||||
return { callNumber: formatCallNumber(out), sortKey: sortKey(out) };
|
||||
}
|
||||
|
||||
/** Does this keyword search return enough classified books to vote on? */
|
||||
export function classified(cands: SimilarCandidate[]): number {
|
||||
return cands.filter((c) => c.lcc.some((l) => parseCallNumber(l) !== null)).length;
|
||||
}
|
||||
@@ -12,9 +12,13 @@ export interface FixtureFetch {
|
||||
locOverride: string | null;
|
||||
}
|
||||
|
||||
const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
|
||||
function pick(u: URL, locOverride: string | null): string | null {
|
||||
if (u.hostname === 'openlibrary.org') {
|
||||
if (u.pathname === '/api/books') return `ol-data-${u.searchParams.get('bibkeys')!.replace('ISBN:', '')}.json`;
|
||||
const kw = u.searchParams.get('q');
|
||||
if (kw) return `ol-similar-${slug(kw)}.json`; // keyword search for the similar-books tier
|
||||
const isbn = u.searchParams.get('isbn');
|
||||
if (isbn) return `ol-search-${isbn}.json`;
|
||||
return 'ol-title-search.json';
|
||||
@@ -24,6 +28,10 @@ function pick(u: URL, locOverride: string | null): string | null {
|
||||
const q = u.searchParams.get('query') ?? '';
|
||||
const m = /^bath\.isbn=(\d+)$/.exec(q);
|
||||
if (m) return `loc-isbn-${m[1]}.xml`;
|
||||
if (q.startsWith('bath.any=')) {
|
||||
const name = `loc-similar-${slug(q.replace(/bath\.any=/g, '').replace(/ and /g, ' '))}.xml`;
|
||||
return existsSync(join(DIR, name)) ? name : 'loc-isbn-9780999999998.xml'; // unknown keywords: zero records
|
||||
}
|
||||
if (q.startsWith('bath.title=')) {
|
||||
return /mythical/i.test(q) ? 'loc-title-mythical-brooks.xml' : 'loc-isbn-9780999999998.xml'; // zero records
|
||||
}
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>2</zs:numberOfRecords><zs:records><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>03204cam a22004214a 4500</leader>
|
||||
<controlfield tag="001">17280132</controlfield>
|
||||
<controlfield tag="005">20250607050442.0</controlfield>
|
||||
<controlfield tag="008">120501s2012 caua 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">17280132</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ecip</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">2 shelf copies</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">xh12 2012-05-01</subfield>
|
||||
<subfield code="i">xh12 2012-05-01 ONIX</subfield>
|
||||
<subfield code="w">rd13 2012-05-02</subfield>
|
||||
<subfield code="a">xn03 2012-09-21 1 copy rec'd., to CIP ver.;</subfield>
|
||||
<subfield code="f">rg07 2012-09-25, c. 1 to CALM</subfield>
|
||||
<subfield code="t">rf18 2013-04-18 copy 2 added</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">LCAP batch update 2025-06-02-04:00: LCAPM-644</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2012012080</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781607742739</subfield>
|
||||
<subfield code="q">hardback</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781607742746</subfield>
|
||||
<subfield code="q">ebook</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">TX769</subfield>
|
||||
<subfield code="b">.F67 2012</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">641.81/5</subfield>
|
||||
<subfield code="2">23</subfield>
|
||||
</datafield>
|
||||
<datafield tag="084" ind1=" " ind2=" ">
|
||||
<subfield code="a">CKB009000</subfield>
|
||||
<subfield code="a">CKB064000</subfield>
|
||||
<subfield code="a">CKB004000</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Forkish, Ken.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0">
|
||||
<subfield code="a">Flour water salt yeast :</subfield>
|
||||
<subfield code="b">the fundamentals of artisan bread and pizza /</subfield>
|
||||
<subfield code="c">Ken Forkish ; photography by Alan Weiner.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">1st ed.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="260" ind1=" " ind2=" ">
|
||||
<subfield code="a">[Berkeley] :</subfield>
|
||||
<subfield code="b">Ten Speed Press,</subfield>
|
||||
<subfield code="c">c2012.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">265 p. :</subfield>
|
||||
<subfield code="b">col. ill. ;</subfield>
|
||||
<subfield code="c">26 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="520" ind1=" " ind2=" ">
|
||||
<subfield code="a">"From Portland's most acclaimed and beloved baker comes this must-have baking guide, featuring scores of recipes for world-class breads and pizzas and a variety of schedules suited for the home baker. In Flour Water Salt Yeast, author Ken Forkish demonstrates that high-quality artisan bread and pizza is within the reach of any home baker. Whether it's a basic straight dough, dough made with a pre-ferment, or a complex levain, each of Forkish's impeccable recipes yields exceptional results. Tips on creating and adapting bread baking schedules that fit in reader's day-to-day lives--enabling them to bake the breads they love in the time they have available--make Flour Water Salt Yeast an indispensable resource for bakers, be they novices or serious enthusiasts"--</subfield>
|
||||
<subfield code="c">Provided by publisher.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="520" ind1=" " ind2=" ">
|
||||
<subfield code="a">"In Flour Water Salt Yeast, author Ken Forkish demonstrates that high-quality artisan bread and pizza is within the reach of any home baker. Whether it's a basic straight dough, dough made with a pre-ferment, or complex levain, each of Forkish's impeccable recipes yields exceptional results. But in addition to the recipes, Flour Water Salt Yeast offers readers a complete baking education, with a thorough yet accessible explanation of the tools and techniques that set artisan bread apart. With a tutorial on baker's percentages, advice for manipulating ingredients ratios to create custom doughs, and tips for creating and adapting bread baking schedules that fit in readers' day-to-day lives (enabling them to bake the breads they love in the time they have available), Flour Water Salt Yeast is an indispensable resource for bakers, be they novices or serious enthusiasts"--</subfield>
|
||||
<subfield code="c">Provided by publisher.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Pizza.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COOKING / Courses & Dishes / Bread.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COOKING / Courses & Dishes / Pizza.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COOKING / Methods / Baking.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="655" ind1=" " ind2="7">
|
||||
<subfield code="a">Cookbooks.</subfield>
|
||||
<subfield code="2">lcgft</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>1</zs:recordPosition></zs:record><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01289cam a2200361 i 4500</leader>
|
||||
<controlfield tag="001">22493436</controlfield>
|
||||
<controlfield tag="005">20250607113011.7</controlfield>
|
||||
<controlfield tag="008">220405s2022 caua 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">22493436</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">2</subfield>
|
||||
<subfield code="e">epcn</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">1 shelf copy</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">xd14 2022-04-05</subfield>
|
||||
<subfield code="a">xn16 2022-12-07 1 copy rec'd., to USASH</subfield>
|
||||
<subfield code="i">rk23 2022-12-09 to PresSvrs</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2022936137</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781984860378</subfield>
|
||||
<subfield code="q">(hardcover)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="z">9781984860385</subfield>
|
||||
<subfield code="q">(ebook)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="b">eng</subfield>
|
||||
<subfield code="e">rda</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">TX769</subfield>
|
||||
<subfield code="b">.F669 2022</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="4">
|
||||
<subfield code="a">641.815</subfield>
|
||||
<subfield code="2">23</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Forkish, Ken,</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0">
|
||||
<subfield code="a">Evolutions in Bread :</subfield>
|
||||
<subfield code="b">artisan pan breads and dutch-oven loaves at home /</subfield>
|
||||
<subfield code="c">Ken Forkish, James Beard Award-winning author of Flour Water Salt Yeast ; photographs by Alan Weiner.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">First edition.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="1">
|
||||
<subfield code="a">[Berkeley] California:</subfield>
|
||||
<subfield code="b">Ten Speed Press,</subfield>
|
||||
<subfield code="c">[2022]</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">249 pages :</subfield>
|
||||
<subfield code="b">color illustrations ;</subfield>
|
||||
<subfield code="c">26 cm</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">still image</subfield>
|
||||
<subfield code="b">sti</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Sourdough bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Baking.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="655" ind1=" " ind2="7">
|
||||
<subfield code="a">Cookbooks.</subfield>
|
||||
<subfield code="2">lcgft</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>2</zs:recordPosition></zs:record></zs:records><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.any=artisan and bath.any=flour and bath.any=water</zs:query><zs:maximumRecords>20</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,625 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>5</zs:numberOfRecords><zs:records><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>03204cam a22004214a 4500</leader>
|
||||
<controlfield tag="001">17280132</controlfield>
|
||||
<controlfield tag="005">20250607050442.0</controlfield>
|
||||
<controlfield tag="008">120501s2012 caua 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">17280132</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ecip</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">2 shelf copies</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">xh12 2012-05-01</subfield>
|
||||
<subfield code="i">xh12 2012-05-01 ONIX</subfield>
|
||||
<subfield code="w">rd13 2012-05-02</subfield>
|
||||
<subfield code="a">xn03 2012-09-21 1 copy rec'd., to CIP ver.;</subfield>
|
||||
<subfield code="f">rg07 2012-09-25, c. 1 to CALM</subfield>
|
||||
<subfield code="t">rf18 2013-04-18 copy 2 added</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">LCAP batch update 2025-06-02-04:00: LCAPM-644</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2012012080</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781607742739</subfield>
|
||||
<subfield code="q">hardback</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781607742746</subfield>
|
||||
<subfield code="q">ebook</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">TX769</subfield>
|
||||
<subfield code="b">.F67 2012</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">641.81/5</subfield>
|
||||
<subfield code="2">23</subfield>
|
||||
</datafield>
|
||||
<datafield tag="084" ind1=" " ind2=" ">
|
||||
<subfield code="a">CKB009000</subfield>
|
||||
<subfield code="a">CKB064000</subfield>
|
||||
<subfield code="a">CKB004000</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Forkish, Ken.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0">
|
||||
<subfield code="a">Flour water salt yeast :</subfield>
|
||||
<subfield code="b">the fundamentals of artisan bread and pizza /</subfield>
|
||||
<subfield code="c">Ken Forkish ; photography by Alan Weiner.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">1st ed.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="260" ind1=" " ind2=" ">
|
||||
<subfield code="a">[Berkeley] :</subfield>
|
||||
<subfield code="b">Ten Speed Press,</subfield>
|
||||
<subfield code="c">c2012.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">265 p. :</subfield>
|
||||
<subfield code="b">col. ill. ;</subfield>
|
||||
<subfield code="c">26 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="520" ind1=" " ind2=" ">
|
||||
<subfield code="a">"From Portland's most acclaimed and beloved baker comes this must-have baking guide, featuring scores of recipes for world-class breads and pizzas and a variety of schedules suited for the home baker. In Flour Water Salt Yeast, author Ken Forkish demonstrates that high-quality artisan bread and pizza is within the reach of any home baker. Whether it's a basic straight dough, dough made with a pre-ferment, or a complex levain, each of Forkish's impeccable recipes yields exceptional results. Tips on creating and adapting bread baking schedules that fit in reader's day-to-day lives--enabling them to bake the breads they love in the time they have available--make Flour Water Salt Yeast an indispensable resource for bakers, be they novices or serious enthusiasts"--</subfield>
|
||||
<subfield code="c">Provided by publisher.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="520" ind1=" " ind2=" ">
|
||||
<subfield code="a">"In Flour Water Salt Yeast, author Ken Forkish demonstrates that high-quality artisan bread and pizza is within the reach of any home baker. Whether it's a basic straight dough, dough made with a pre-ferment, or complex levain, each of Forkish's impeccable recipes yields exceptional results. But in addition to the recipes, Flour Water Salt Yeast offers readers a complete baking education, with a thorough yet accessible explanation of the tools and techniques that set artisan bread apart. With a tutorial on baker's percentages, advice for manipulating ingredients ratios to create custom doughs, and tips for creating and adapting bread baking schedules that fit in readers' day-to-day lives (enabling them to bake the breads they love in the time they have available), Flour Water Salt Yeast is an indispensable resource for bakers, be they novices or serious enthusiasts"--</subfield>
|
||||
<subfield code="c">Provided by publisher.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Pizza.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COOKING / Courses & Dishes / Bread.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COOKING / Courses & Dishes / Pizza.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COOKING / Methods / Baking.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="655" ind1=" " ind2="7">
|
||||
<subfield code="a">Cookbooks.</subfield>
|
||||
<subfield code="2">lcgft</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>1</zs:recordPosition></zs:record><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01289cam a2200361 i 4500</leader>
|
||||
<controlfield tag="001">22493436</controlfield>
|
||||
<controlfield tag="005">20250607113011.7</controlfield>
|
||||
<controlfield tag="008">220405s2022 caua 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">22493436</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">2</subfield>
|
||||
<subfield code="e">epcn</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">1 shelf copy</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">xd14 2022-04-05</subfield>
|
||||
<subfield code="a">xn16 2022-12-07 1 copy rec'd., to USASH</subfield>
|
||||
<subfield code="i">rk23 2022-12-09 to PresSvrs</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2022936137</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781984860378</subfield>
|
||||
<subfield code="q">(hardcover)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="z">9781984860385</subfield>
|
||||
<subfield code="q">(ebook)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="b">eng</subfield>
|
||||
<subfield code="e">rda</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">TX769</subfield>
|
||||
<subfield code="b">.F669 2022</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="4">
|
||||
<subfield code="a">641.815</subfield>
|
||||
<subfield code="2">23</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Forkish, Ken,</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0">
|
||||
<subfield code="a">Evolutions in Bread :</subfield>
|
||||
<subfield code="b">artisan pan breads and dutch-oven loaves at home /</subfield>
|
||||
<subfield code="c">Ken Forkish, James Beard Award-winning author of Flour Water Salt Yeast ; photographs by Alan Weiner.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">First edition.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="1">
|
||||
<subfield code="a">[Berkeley] California:</subfield>
|
||||
<subfield code="b">Ten Speed Press,</subfield>
|
||||
<subfield code="c">[2022]</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">249 pages :</subfield>
|
||||
<subfield code="b">color illustrations ;</subfield>
|
||||
<subfield code="c">26 cm</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">still image</subfield>
|
||||
<subfield code="b">sti</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Sourdough bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Baking.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="655" ind1=" " ind2="7">
|
||||
<subfield code="a">Cookbooks.</subfield>
|
||||
<subfield code="2">lcgft</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>2</zs:recordPosition></zs:record><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01468cam a2200373 i 4500</leader>
|
||||
<controlfield tag="001">20412023</controlfield>
|
||||
<controlfield tag="005">20250607085600.0</controlfield>
|
||||
<controlfield tag="008">180319s2018 caua b 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">20412023</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ecip</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">1 shelf copy</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">rk14 2018-03-19</subfield>
|
||||
<subfield code="i">rk14 2018-03-19 telework to subj rev</subfield>
|
||||
<subfield code="r">rk09 2018-03-20 to Dewey</subfield>
|
||||
<subfield code="w">xm09 2018-03-22</subfield>
|
||||
<subfield code="a">xn11 2019-04-02 1 copy rec'd., to CIP ver.</subfield>
|
||||
<subfield code="a">rk20 2019-04-09 book received in ART</subfield>
|
||||
<subfield code="f">rl06 2019-07-20 to CALM</subfield>
|
||||
<subfield code="s">rk23 2021-01-30 (TW Situational) c. 2 to DISCARDS (0046146872A)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2018009826</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781452167879</subfield>
|
||||
<subfield code="q">(hardcover)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="b">eng</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="e">rda</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">TX769</subfield>
|
||||
<subfield code="b">.K557 2018</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">641.81/5</subfield>
|
||||
<subfield code="2">23</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">King, Ellen,</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0">
|
||||
<subfield code="a">Heritage baking :</subfield>
|
||||
<subfield code="b">recipes for rustic breads and pastries baked with artisanal flour from Hewn Bakery /</subfield>
|
||||
<subfield code="c">by Ellen King with Amelia Levin ; photographs by John Lee.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="1">
|
||||
<subfield code="a">San Francisco :</subfield>
|
||||
<subfield code="b">Chronicle Books,</subfield>
|
||||
<subfield code="c">[2018]</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="4">
|
||||
<subfield code="c">©2018</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">223 pages :</subfield>
|
||||
<subfield code="b">color illustrations ;</subfield>
|
||||
<subfield code="c">24 cm</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Baking.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Grain.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Heirloom varieties (Plants)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="655" ind1=" " ind2="7">
|
||||
<subfield code="a">Cookbooks.</subfield>
|
||||
<subfield code="2">lcgft</subfield>
|
||||
</datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" ">
|
||||
<subfield code="a">Levin, Amelia,</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="710" ind1="2" ind2=" ">
|
||||
<subfield code="a">Hewn Bakery.</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>3</zs:recordPosition></zs:record><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01306cam a2200361 i 4500</leader>
|
||||
<controlfield tag="001">22800345</controlfield>
|
||||
<controlfield tag="005">20250607115436.3</controlfield>
|
||||
<controlfield tag="008">220922t20232023maua 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">22800345</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">2</subfield>
|
||||
<subfield code="e">epcn</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">1 shelf copy</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">xd15 2022-09-22</subfield>
|
||||
<subfield code="a">xn11 2024-01-30 1 copy rec'd., to USASH</subfield>
|
||||
<subfield code="i">rk27 2024-02-13 to Dewey</subfield>
|
||||
<subfield code="w">xm51 2024-03-28</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2022946941</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781645679592</subfield>
|
||||
<subfield code="q">(paperback)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">1645679594</subfield>
|
||||
<subfield code="q">(paperback)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="z">9781645677765</subfield>
|
||||
<subfield code="q">(ebook)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="b">eng</subfield>
|
||||
<subfield code="e">rda</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">TX769</subfield>
|
||||
<subfield code="b">.G5548 2023</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">641.81/5</subfield>
|
||||
<subfield code="2">23/eng/20240328</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Giuffi, Tim,</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="4">
|
||||
<subfield code="a">The fresh-milled flour bread book :</subfield>
|
||||
<subfield code="b">the complete guide to mastering your home mill for artisan sourdough, pizza, croissants and more /</subfield>
|
||||
<subfield code="c">Tim Giuffi, owner of Lyman Ave. Bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="1">
|
||||
<subfield code="a">Salem, MA :</subfield>
|
||||
<subfield code="b">Page Street Publishing Co.,</subfield>
|
||||
<subfield code="c">2023.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="4">
|
||||
<subfield code="c">©2023</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">144 pages :</subfield>
|
||||
<subfield code="b">color illustrations ;</subfield>
|
||||
<subfield code="c">23 cm</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Cooking (Bread)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Baking.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="655" ind1=" " ind2="7">
|
||||
<subfield code="a">Cookbooks.</subfield>
|
||||
<subfield code="2">lcgft</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>4</zs:recordPosition></zs:record><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>03071cam a2200457 i 4500</leader>
|
||||
<controlfield tag="001">18179898</controlfield>
|
||||
<controlfield tag="005">20250607061004.5</controlfield>
|
||||
<controlfield tag="008">140606s2014 nyua 000 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">18179898</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ecip</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">1 shelf copy</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">bd22 2014-06-06</subfield>
|
||||
<subfield code="i">bd22 2014-06-06 ONIX telework to Dewey</subfield>
|
||||
<subfield code="w">xl03 2014-06-09</subfield>
|
||||
<subfield code="a">xn11 2014-10-27 1 copy rec'd., to CIP ver.</subfield>
|
||||
<subfield code="f">rl09 2014-11-05 ; to CALM</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">LCAP batch update 2025-06-02-04:00: LCAPM-821</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2014022132</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9781250018311</subfield>
|
||||
<subfield code="q">hbk</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">1250018315</subfield>
|
||||
<subfield code="q">hbk</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="z">9781250018304 (ebk.)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="z">1250018307 (ebk.)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="b">eng</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="e">rda</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">RM237.86</subfield>
|
||||
<subfield code="b">.H47 2014</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">641.5/638</subfield>
|
||||
<subfield code="2">23</subfield>
|
||||
</datafield>
|
||||
<datafield tag="084" ind1=" " ind2=" ">
|
||||
<subfield code="a">CKB009000</subfield>
|
||||
<subfield code="a">CKB004000</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Hertzberg, Jeff.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0">
|
||||
<subfield code="a">Gluten-free artisan bread in five minutes a day :</subfield>
|
||||
<subfield code="b">the baking revolution continues with 90 new, delicious and easy recipes made with gluten-free flours /</subfield>
|
||||
<subfield code="c">Jeff Hertzberg, MD, and Zoë François ; photographs by Stephen Scott Gross.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">First edition.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="1">
|
||||
<subfield code="a">New York :</subfield>
|
||||
<subfield code="b">Thomas Dunne Books, St. Martin's Press,</subfield>
|
||||
<subfield code="c">2014.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">xi, 291 pages :</subfield>
|
||||
<subfield code="b">illustrations (some color) ;</subfield>
|
||||
<subfield code="c">24 cm</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="504" ind1=" " ind2=" ">
|
||||
<subfield code="a">Includes bibliographical references (pages 275-277) and index.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="520" ind1=" " ind2=" ">
|
||||
<subfield code="a">"Americans are turning in record numbers to gluten-free foods as a means to health, and an often-quoted University of Maryland study estimates that 1 out of 133 Americans (1% of the population) have celiac disease (a debilitating auto-immune disease caused by gluten). As the gluten-free trend has grown, a much larger population is experimenting with the gluten-free lifestyle to treat health symptoms. And one of the number one items those on a gluten-free diet miss most is bread. Based on overwhelming requests from readers at their interactive website BreadIn5.com, Jeff Hertzberg and Zoë François have returned to their test kitchens to build on the popular gluten-free recipes that appeared in their earlier titles for an entirely gluten-free bread cookbook. Gluten-Free Bread in Five Minutes a Day extends their revolutionary stored-dough method to yeasted and unleavened breads made without wheat, barley, or rye. With more than 60 recipes--as well as 100 black-and-white instructional photos and 40 gorgeous color images--the authors adopt the rich palette of world breads to their unique method. With this revolutionary approach, you CAN have mouth-watering gluten-free artisan bread in just five minutes a day!"--</subfield>
|
||||
<subfield code="c">Provided by publisher.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Gluten-free diet</subfield>
|
||||
<subfield code="v">Recipes.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Bread.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Cooking (Bread)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COOKING / Courses & Dishes / Bread.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="7">
|
||||
<subfield code="a">COOKING / Methods / Baking.</subfield>
|
||||
<subfield code="2">bisacsh</subfield>
|
||||
</datafield>
|
||||
<datafield tag="655" ind1=" " ind2="7">
|
||||
<subfield code="a">Cookbooks.</subfield>
|
||||
<subfield code="2">lcgft</subfield>
|
||||
</datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" ">
|
||||
<subfield code="a">François, Zoë.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" ">
|
||||
<subfield code="a">Gross, Stephen Scott,</subfield>
|
||||
<subfield code="e">illustrator.</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>5</zs:recordPosition></zs:record></zs:records><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.any=artisan and bath.any=flour</zs:query><zs:maximumRecords>20</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>0</zs:numberOfRecords><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.any=xyzzy and bath.any=plugh and bath.any=quux</zs:query><zs:maximumRecords>20</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>0</zs:numberOfRecords><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.any=xyzzy and bath.any=plugh</zs:query><zs:maximumRecords>20</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":3,"start":0,"numFoundExact":true,"num_found":3,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"artisan flour water yeast bread pizza salt","offset":null,"docs":[{"author_name":["Ken Forkish"],"first_publish_year":2012,"key":"/works/OL16626586W","lcc":["TX-0769.00000000.F67 2012"],"title":"Flour Water Salt Yeast","subject":["Bread","COOKING / Courses & Dishes / Bread","COOKING / Methods / Baking","COOKING / Courses & Dishes / Pizza","Pizza","Cooking","nyt:advice-how-to-and-miscellaneous=2020-04-26","New York Times bestseller","Baking","U.s. cooking"]},{"author_name":["Rene Abbott"],"first_publish_year":2022,"key":"/works/OL28881815W","title":"Salt Flour Water Yeast"},{"author_name":["Maureen Padgett"],"first_publish_year":2021,"key":"/works/OL35877791W","title":"Element of Flour Water Salt and Yeast"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":5,"start":0,"numFoundExact":true,"num_found":5,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"artisan flour water yeast bread","offset":null,"docs":[{"author_name":["Ken Forkish"],"first_publish_year":2012,"key":"/works/OL16626586W","lcc":["TX-0769.00000000.F67 2012"],"title":"Flour Water Salt Yeast","subject":["Bread","COOKING / Courses & Dishes / Bread","COOKING / Methods / Baking","COOKING / Courses & Dishes / Pizza","Pizza","Cooking","nyt:advice-how-to-and-miscellaneous=2020-04-26","New York Times bestseller","Baking","U.s. cooking"]},{"author_name":["Maria Pizzarotti"],"first_publish_year":2020,"key":"/works/OL22285220W","title":"Italian Bread"},{"author_name":["Rene Abbott"],"first_publish_year":2022,"key":"/works/OL28881815W","title":"Salt Flour Water Yeast"},{"author_name":["Ken Forkish"],"first_publish_year":2022,"key":"/works/OL27849095W","title":"Evolutions in Bread"},{"author_name":["Maureen Padgett"],"first_publish_year":2021,"key":"/works/OL35877791W","title":"Element of Flour Water Salt and Yeast"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":5,"start":0,"numFoundExact":true,"num_found":5,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"artisan flour water yeast","offset":null,"docs":[{"author_name":["Ken Forkish"],"first_publish_year":2012,"key":"/works/OL16626586W","lcc":["TX-0769.00000000.F67 2012"],"title":"Flour Water Salt Yeast","subject":["Bread","COOKING / Courses & Dishes / Bread","COOKING / Methods / Baking","COOKING / Courses & Dishes / Pizza","Pizza","Cooking","nyt:advice-how-to-and-miscellaneous=2020-04-26","New York Times bestseller","Baking","U.s. cooking"]},{"author_name":["Rene Abbott"],"first_publish_year":2022,"key":"/works/OL28881815W","title":"Salt Flour Water Yeast"},{"author_name":["Maria Pizzarotti"],"first_publish_year":2020,"key":"/works/OL22285220W","title":"Italian Bread"},{"author_name":["Maureen Padgett"],"first_publish_year":2021,"key":"/works/OL35877791W","title":"Element of Flour Water Salt and Yeast"},{"author_name":["Ken Forkish"],"first_publish_year":2022,"key":"/works/OL27849095W","title":"Evolutions in Bread"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":3,"start":0,"numFoundExact":true,"num_found":3,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"mountains wyoming trails river wind","offset":null,"docs":[{"first_publish_year":2017,"key":"/works/OL24163660W","title":"Beyond Trails in The Wind River Mountains of Wyoming"},{"author_name":["Ben Adkison"],"first_publish_year":2012,"key":"/works/OL19745445W","lcc":["GV-0199.42000000.W82W5617","GV-0199.42000000.W82 W5617 2018"],"title":"Hiking Wyoming's Wind River Range","subject":["Walking","Guidebooks","Backpacking","Hiking","Trails","Outdoor recreation","Mountaineering","Rock climbing","Wyoming, guidebooks"]},{"author_name":["Ron Adkison"],"first_publish_year":1996,"key":"/works/OL19548745W","lcc":["GV-0199.42000000.W82 W5617 1996","GV-0199.42000000.W82W5617 19"],"title":"I dispacci di Giovanni Michiel","subject":["Guidebooks","Hiking","Mountaineering","Trails","Wyoming, description and travel"]}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":12,"start":0,"numFoundExact":true,"num_found":12,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"mountains wyoming trails river","offset":null,"docs":[{"first_publish_year":2017,"key":"/works/OL24163660W","title":"Beyond Trails in The Wind River Mountains of Wyoming"},{"author_name":["Ben Adkison"],"first_publish_year":2012,"key":"/works/OL19745445W","lcc":["GV-0199.42000000.W82W5617","GV-0199.42000000.W82 W5617 2018"],"title":"Hiking Wyoming's Wind River Range","subject":["Walking","Guidebooks","Backpacking","Hiking","Trails","Outdoor recreation","Mountaineering","Rock climbing","Wyoming, guidebooks"]},{"first_publish_year":1984,"key":"/works/OL17664893M","title":"Beaver Trail","subject":["Beavers.","Nature trails -- Wyoming -- Muddy Mountain.","Muddy Mountain (Wyo.)"]},{"first_publish_year":1984,"key":"/works/OL17831114M","title":"Beaver Trail","subject":["Beavers.","Nature trails -- Wyoming -- Muddy Mountain.","Muddy Mountain (Wyo.)"]},{"first_publish_year":1984,"key":"/works/OL14918027M","title":"Beaver Trail","subject":["Beavers","Nature trails -- Wyoming -- Muddy Mountain","Muddy Mountain (Wyo.)"]},{"author_name":["Earle Crowe"],"first_publish_year":1960,"key":"/works/OL7524672W","title":"General Beale's sheep odessey [sic]","subject":["History","Sheep","Transportation"]},{"first_publish_year":1983,"key":"/works/OL14918025M","title":"Forest ecology/plant identification trail","subject":["Forest ecology -- Wyoming -- Muddy Mountain","Nature trails -- Wyoming -- Muddy Mountain"]},{"author_name":["Ron Adkison"],"first_publish_year":1996,"key":"/works/OL19548745W","lcc":["GV-0199.42000000.W82 W5617 1996","GV-0199.42000000.W82W5617 19"],"title":"I dispacci di Giovanni Michiel","subject":["Guidebooks","Hiking","Mountaineering","Trails","Wyoming, description and travel"]},{"author_name":["Cheryl Harness"],"first_publish_year":2006,"key":"/works/OL15964798W","lcc":["E--0444.00000000.T82 A73 2006","F--0880.00000000.H275 2006","E--0444.00000000.T82A73 2006"],"title":"The tragic tale of Narcissa Whitman and a faithful history of the Oregon Trail","subject":["Women missionaries","Frontier and pioneer life","Women pioneers","Overland journeys to the Pacific","Juvenile literature","Biography","History","African American women","Slaves","Underground railroad","Underground Railroad","African americans, juvenile literature","African americans","Tubman, harriet, 1822-1913","Tubman, harriet, 1822-1913, juvenile literature","Whitman, narcissa (prentiss), 1808-1847","Missionaries","Missionaries, juvenile literature","Frontier and pioneer life, juvenile literature","Overland journeys to the pacific","Overland journeys to the pacific, juvenile literature","Oregon national historic trail","Oregon national historic trail, juvenile literature","Pioneers","Oregon, history"]},{"author_name":["Robert A. Murray"],"first_publish_year":1970,"key":"/works/OL715107W","lcc":["F--0782.00000000.A7 M87"],"title":"Citadel on the Santa Fe Trail","subject":["Fortification","Frontier and pioneer life"]},{"author_name":["Jeff A. Nussbaumer"],"first_publish_year":2013,"key":"/works/OL24847889W","title":"RAD","subject":["Mountain biking","Guidebooks","Bicycle trails"]},{"author_name":["Kemp, James Furman"],"first_publish_year":1887,"key":"/works/OL33051801W","title":"[Collected works by James Furman Kemp.]"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":33,"start":0,"numFoundExact":true,"num_found":33,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"mountains wyoming trails","offset":null,"docs":[{"first_publish_year":2017,"key":"/works/OL24163660W","title":"Beyond Trails in The Wind River Mountains of Wyoming"},{"author_name":["James R. Wolf"],"first_publish_year":1976,"key":"/works/OL4107295W","lcc":["GV-0199.42000000.C84 W64 1991","GV-0199.42000000.C84 W64"],"title":"Guide to the Continental Divide Trail","subject":["Guidebooks","Hiking","Natural history"]},{"author_name":["William Robert Skinner"],"first_publish_year":1966,"key":"/works/OL38530872W","title":"Geologic evolution of the Beartooth Mountains, Montana and Wyoming","subject":["Ultrabasic rocks"]},{"author_name":["Marc Smith"],"first_publish_year":2007,"key":"/works/OL12277591W","lcc":["GV-0199.42000000.W82 M436 2007","GV-0199.42000000.W82 M436 2009"],"title":"Hiking Wyoming's Medicine Bow National Forest","subject":["Guidebooks","Hiking"]},{"author_name":["Jim Russell"],"first_publish_year":1962,"key":"/works/OL43017927W","lcc":["CT-0275.00000000.F728 R8","F--0595.00000000.F95 R87 1962"],"title":"Bob Fudge","subject":["Fudge, Bob, 1862-1933","Frontier and pioneer life--West (U.S.)","Cattle trails--West (U.S.)--History","Pioneers--West (U.S.)--Biography"]},{"author_name":["Keffer, Ken (Naturalist)"],"first_publish_year":2017,"key":"/works/OL20054997W","lcc":["GV-0199.42000000","GV-0199.42000000.W82 B533 2017"],"title":"Hiking Wyoming's Bighorn Mountains","subject":["Trails","Guidebooks","Hiking","Wyoming, guidebooks","Montana, guidebooks"]},{"first_publish_year":1984,"key":"/works/OL17664893M","title":"Beaver Trail","subject":["Beavers.","Nature trails -- Wyoming -- Muddy Mountain.","Muddy Mountain (Wyo.)"]},{"first_publish_year":1984,"key":"/works/OL17831114M","title":"Beaver Trail","subject":["Beavers.","Nature trails -- Wyoming -- Muddy Mountain.","Muddy Mountain (Wyo.)"]},{"first_publish_year":1984,"key":"/works/OL14918027M","title":"Beaver Trail","subject":["Beavers","Nature trails -- Wyoming -- Muddy Mountain","Muddy Mountain (Wyo.)"]},{"author_name":["Ben Adkison"],"first_publish_year":2012,"key":"/works/OL19745445W","lcc":["GV-0199.42000000.W82W5617","GV-0199.42000000.W82 W5617 2018"],"title":"Hiking Wyoming's Wind River Range","subject":["Walking","Guidebooks","Backpacking","Hiking","Trails","Outdoor recreation","Mountaineering","Rock climbing","Wyoming, guidebooks"]},{"author_name":["United States. National Park Service. Rocky Mountain Regional Office"],"first_publish_year":1981,"key":"/works/OL36989895W","title":"Mormon Pioneer National Historic Trail, Illinois-Iowa-Nebraska-Wyoming-Utah","subject":["Mormon Church"]},{"author_name":["Smith"],"first_publish_year":2017,"key":"/works/OL38965745W","title":"Hiking Wyoming's Medicine Bow National Forest"},{"first_publish_year":1981,"key":"/works/OL14089607M","title":"Mormon Pioneer National Historic Trail","subject":["Mormons -- West (U.S.) -- History.","Mormon Trail."]},{"first_publish_year":1983,"key":"/works/OL14918025M","title":"Forest ecology/plant identification trail","subject":["Forest ecology -- Wyoming -- Muddy Mountain","Nature trails -- Wyoming -- Muddy Mountain"]},{"author_name":["Bill Moeller","Jan Moeller"],"first_publish_year":1985,"key":"/works/OL30468W","lcc":["F--0597.00000000.M73 2001","F--0597.00000000 M73 2001","F--0597.00000000.M73 1985b","F--0597.00000000.M73 1985"],"title":"The Oregon Trail","subject":["Overland journeys to the Pacific","Frontier and pioneer life","Pictorial works","History","West (U.S.)","General","United States - 19th Century/Old West","Oregon National Historic Trail","Photo Techniques","Photography"]},{"author_name":["Cheryl Harness"],"first_publish_year":2006,"key":"/works/OL15964798W","lcc":["E--0444.00000000.T82 A73 2006","F--0880.00000000.H275 2006","E--0444.00000000.T82A73 2006"],"title":"The tragic tale of Narcissa Whitman and a faithful history of the Oregon Trail","subject":["Women missionaries","Frontier and pioneer life","Women pioneers","Overland journeys to the Pacific","Juvenile literature","Biography","History","African American women","Slaves","Underground railroad","Underground Railroad","African americans, juvenile literature","African americans","Tubman, harriet, 1822-1913","Tubman, harriet, 1822-1913, juvenile literature","Whitman, narcissa (prentiss), 1808-1847","Missionaries","Missionaries, juvenile literature","Frontier and pioneer life, juvenile literature","Overland journeys to the pacific","Overland journeys to the pacific, juvenile literature","Oregon national historic trail","Oregon national historic trail, juvenile literature","Pioneers","Oregon, history"]},{"author_name":["Earle Crowe"],"first_publish_year":1960,"key":"/works/OL7524672W","title":"General Beale's sheep odessey [sic]","subject":["History","Sheep","Transportation"]},{"author_name":["L. C. Bishop"],"first_publish_year":1978,"key":"/works/OL38855306W","title":"LaBonte, Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":0,"start":0,"numFoundExact":true,"num_found":0,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"xyzzy plugh quux","offset":null,"docs":[]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":0,"start":0,"numFoundExact":true,"num_found":0,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"xyzzy plugh","offset":null,"docs":[]}
|
||||
@@ -17,6 +17,8 @@ export interface Loc {
|
||||
byIsbn(isbn: string): Promise<MarcFields[]>;
|
||||
byLccn(lccn: string): Promise<MarcFields[]>;
|
||||
byTitle(title: string, author: string): Promise<MarcFields[]>;
|
||||
/** Records whose title, subjects or notes mention every keyword (the `bath.any` index). */
|
||||
byKeywords(keywords: string[]): Promise<MarcFields[]>;
|
||||
}
|
||||
|
||||
export function createLoc(deps: {
|
||||
@@ -99,5 +101,11 @@ export function createLoc(deps: {
|
||||
const query = surname ? `bath.title="${t}" and bath.author="${surname}"` : `bath.title="${t}"`;
|
||||
return sru(`loc-title:${title}|${author}`, query, 5);
|
||||
},
|
||||
byKeywords(keywords) {
|
||||
const words = keywords.map((k) => k.replace(/[^\p{L}\p{N}]/gu, '')).filter(Boolean);
|
||||
if (words.length === 0) return Promise.resolve([]);
|
||||
const query = words.map((w) => `bath.any=${w}`).join(' and ');
|
||||
return sru(`similar-loc:${words.join(' ')}`, query, 20);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,8 @@ export interface MarcFields {
|
||||
meta: Partial<BookMeta>;
|
||||
/** Every 100/700 $a, cleaned but still in "Surname, Forename" form; used to verify title/author matches. */
|
||||
names: string[];
|
||||
/** Subject headings with their subdivisions and place names (650, 651), for judging what a book is about. */
|
||||
topics: string[];
|
||||
}
|
||||
|
||||
type Node = Record<string, unknown>;
|
||||
@@ -114,6 +116,8 @@ export function parseMarcRecord(rec: Node): MarcFields {
|
||||
const ym = pub ? /\b(1[0-9]\d\d|20\d\d)\b/.exec(sub(pub, 'c')) : null;
|
||||
|
||||
const subjects = uniq(all('650').map((f) => trimPunct(sub(f, 'a'))).filter(Boolean));
|
||||
const topics = uniq([...all('650'), ...all('651')].flatMap((f) =>
|
||||
f.subs.filter((s) => 'avxyz'.includes(s.code) && s.value).map((s) => trimPunct(s.value))));
|
||||
const f010 = all('010')[0];
|
||||
const lccn = f010 && sub(f010, 'a') ? sub(f010, 'a').replace(/\s+/g, '') : null;
|
||||
|
||||
@@ -123,7 +127,7 @@ export function parseMarcRecord(rec: Node): MarcFields {
|
||||
if (publisher) meta.publisher = publisher;
|
||||
if (ym) meta.year = Number(ym[1]);
|
||||
if (lccn) meta.lccn = lccn;
|
||||
return { lccn, lcc, dewey, meta, names };
|
||||
return { lccn, lcc, dewey, meta, names, topics };
|
||||
}
|
||||
|
||||
/** Parse every MARC record in an SRU response or a bare LCCN permalink record. */
|
||||
|
||||
@@ -95,7 +95,24 @@ export function parseSearch(body: string): SearchResult[] {
|
||||
});
|
||||
}
|
||||
|
||||
/** One result of a keyword search: enough to judge what a book is about and where it is shelved. */
|
||||
export interface SimilarDoc { title: string; subtitle?: string; authors: string[]; subjects: string[]; lcc: string[]; year?: number }
|
||||
|
||||
const SIMILAR_FIELDS = 'key,title,subtitle,author_name,subject,lcc,first_publish_year';
|
||||
|
||||
export function parseSimilar(body: string): SimilarDoc[] {
|
||||
return docs(body).flatMap((d) => {
|
||||
if (typeof d['title'] !== 'string' || !d['title'].trim()) return [];
|
||||
const r: SimilarDoc = { title: d['title'].trim(), authors: uniq(strs(d['author_name'])), subjects: uniq(strs(d['subject'])), lcc: strs(d['lcc']) };
|
||||
if (typeof d['subtitle'] === 'string' && d['subtitle'].trim()) r.subtitle = d['subtitle'].trim();
|
||||
if (typeof d['first_publish_year'] === 'number') r.year = d['first_publish_year'];
|
||||
return [r];
|
||||
});
|
||||
}
|
||||
|
||||
export interface OpenLibrary {
|
||||
/** Keyword relevance search (all words must match); results carry their LC classification when Open Library has one. */
|
||||
similar(keywords: string[]): Promise<SimilarDoc[]>;
|
||||
edition(isbn: string): Promise<OlInfo | null>;
|
||||
work(isbn: string): Promise<OlInfo | null>;
|
||||
search(title: string, author: string): Promise<SearchResult[]>;
|
||||
@@ -116,6 +133,11 @@ export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCach
|
||||
return text;
|
||||
}
|
||||
return {
|
||||
async similar(keywords) {
|
||||
const q = keywords.join(' ');
|
||||
const url = `https://openlibrary.org/search.json?${new URLSearchParams({ q, fields: SIMILAR_FIELDS, limit: '25' })}`;
|
||||
return parseSimilar(await body(`similar-ol:${q}`, url, (t) => parseSimilar(t).length > 0));
|
||||
},
|
||||
async edition(isbn) {
|
||||
const url = `https://openlibrary.org/api/books?bibkeys=ISBN:${isbn}&jscmd=data&format=json`;
|
||||
return parseEdition(await body(`ol-data:${isbn}`, url, (t) => parseEdition(t, isbn) !== null), isbn);
|
||||
|
||||
+1
-1
@@ -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' | 'manual';
|
||||
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[];
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { Book, SearchResult } from '../shared/types.ts';
|
||||
import { api } from './api.ts';
|
||||
import { setLastScan, upsertBook } from './live.ts';
|
||||
import { beepLow } from './sound.ts';
|
||||
import { showError } from './toast-store.ts';
|
||||
|
||||
/** ISBNs with a request in flight: one ISBN is never sent twice at the same time. */
|
||||
const inflight = new Map<string, Promise<void>>();
|
||||
|
||||
/** Add a book by ISBN (from the camera or the entry box). The Last scan card shows what happened. */
|
||||
export function addByIsbn(isbn: string): Promise<void> {
|
||||
let p = inflight.get(isbn);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
try {
|
||||
const r = await api.scan(isbn);
|
||||
upsertBook(r.book);
|
||||
setLastScan(r.book.id, r.duplicate);
|
||||
} catch (e) {
|
||||
beepLow();
|
||||
showError(`Could not add ${isbn}: ${(e as Error).message}`);
|
||||
}
|
||||
})();
|
||||
inflight.set(isbn, p);
|
||||
void p.finally(() => inflight.delete(isbn));
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
function added(book: Book): void {
|
||||
upsertBook(book);
|
||||
setLastScan(book.id, false);
|
||||
}
|
||||
|
||||
export async function addByLccn(lccn: string): Promise<boolean> {
|
||||
try { added(await api.addLccn(lccn)); return true; }
|
||||
catch (e) { beepLow(); showError(`Could not add ${lccn}: ${(e as Error).message}`); return false; }
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
@@ -43,8 +43,17 @@ export const api = {
|
||||
request<Book[]>('GET', `/api/books?filter=${filter}&q=${encodeURIComponent(q)}`),
|
||||
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. */
|
||||
deleteBookOnUnload(id: number): void {
|
||||
try { void fetch(`/api/books/${id}`, { method: 'DELETE', keepalive: true }).catch(() => {}); } catch { /* page is going away */ }
|
||||
},
|
||||
queueBook: async (id: number) => toBook(await request('POST', `/api/books/${id}/queue`)),
|
||||
retryBook: async (id: number) => toBook(await request('POST', `/api/books/${id}/retry`)),
|
||||
confirmPrintOnUnload(ids: number[]): void {
|
||||
try {
|
||||
void fetch('/api/print/confirm', { method: 'POST', keepalive: true, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids }) }).catch(() => {});
|
||||
} catch { /* page is going away */ }
|
||||
},
|
||||
confirmPrint: (ids: number[]) => request<unknown>('POST', '/api/print/confirm', { ids }),
|
||||
getSettings: () => request<Settings>('GET', '/api/settings'),
|
||||
putSettings: (s: Settings) => request<Settings>('PUT', '/api/settings', s),
|
||||
|
||||
+19
-25
@@ -1,19 +1,19 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { elapsedText, pdfLabel, queueHeader, queueSplit, queueTabLabel, rowState, sessionSummary } from './bookstate.ts';
|
||||
import { elapsedText, printStatus, queueOrder, rowState } from './bookstate.ts';
|
||||
|
||||
function book(id: number, over: Partial<Book>): Book {
|
||||
return {
|
||||
id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey: null, confidence: null, source: null, dewey: null,
|
||||
status: 'pending', attentionReason: null, manualOverride: false, inQueue: true,
|
||||
printedAt: null, createdAt: '', updatedAt: '', ...over,
|
||||
printedAt: null, createdAt: `2026-01-01T00:00:0${id}Z`, updatedAt: '', ...over,
|
||||
};
|
||||
}
|
||||
const ready = (id: number) => book(id, { status: 'resolved', callNumber: 'QA76.73 .R87 K53 2018', sortKey: 'k' + id });
|
||||
const ready = (id: number, over: Partial<Book> = {}) => book(id, { status: 'resolved', callNumber: 'QA76.73 .R87 K53 2018', sortKey: 'k' + id, ...over });
|
||||
const looking = (id: number) => book(id, {});
|
||||
const attention = (id: number) => book(id, { status: 'needs_attention', attentionReason: 'No match' });
|
||||
const attention = (id: number, over: Partial<Book> = {}) => book(id, { status: 'needs_attention', attentionReason: 'No match', ...over });
|
||||
|
||||
test('a pending book is "looking", never "no call number"', () => {
|
||||
assert.deepEqual(rowState(looking(1)), { kind: 'looking', note: null });
|
||||
@@ -27,34 +27,28 @@ test('ready and attention states', () => {
|
||||
assert.equal(rowState(book(1, { status: 'resolved' })).kind, 'attention');
|
||||
});
|
||||
|
||||
test('session summary', () => {
|
||||
assert.equal(sessionSummary([ready(1), ready(2), ready(3), looking(4)]), '4 scanned · 3 ready · 1 looking up');
|
||||
assert.equal(sessionSummary([ready(1)]), '1 scanned · 1 ready');
|
||||
assert.equal(sessionSummary([attention(1), attention(2), looking(3)]), '3 scanned · 1 looking up · 2 need attention');
|
||||
assert.equal(sessionSummary([]), '0 scanned');
|
||||
test('queue order: attention first, then newest first', () => {
|
||||
const order = queueOrder([ready(1), attention(2), looking(3), ready(4), attention(0)]).map(b => b.id);
|
||||
assert.deepEqual(order, [2, 0, 4, 3, 1]);
|
||||
});
|
||||
|
||||
test('queue split ignores books that are not queued or need attention', () => {
|
||||
const printed = { ...ready(9), inQueue: false };
|
||||
const q = queueSplit([ready(1), looking(2), attention(3), printed, ready(4)]);
|
||||
assert.deepEqual(q.ready.map(b => b.id), [1, 4]);
|
||||
assert.deepEqual(q.looking.map(b => b.id), [2]);
|
||||
test('queue order leaves out books that are not queued, and ties go to the higher id', () => {
|
||||
const same = '2026-02-02T00:00:00Z';
|
||||
const order = queueOrder([ready(1, { createdAt: same }), ready(2, { createdAt: same }), ready(3, { inQueue: false })]).map(b => b.id);
|
||||
assert.deepEqual(order, [2, 1]);
|
||||
});
|
||||
|
||||
test('queue labels', () => {
|
||||
assert.equal(queueHeader(3, 1), '3 cards ready · 1 still looking up');
|
||||
assert.equal(queueHeader(1, 0), '1 card ready');
|
||||
assert.equal(queueHeader(0, 1), '0 cards ready · 1 still looking up');
|
||||
assert.equal(pdfLabel(3), 'Make PDF (3 cards)');
|
||||
assert.equal(pdfLabel(1), 'Make PDF (1 card)');
|
||||
assert.equal(pdfLabel(0), 'Make PDF');
|
||||
assert.equal(queueTabLabel(3, 1), 'Print queue (4)');
|
||||
assert.equal(queueTabLabel(0, 0), 'Print queue');
|
||||
test('print status counts ready cards and explains a disabled button', () => {
|
||||
assert.deepEqual(printStatus([]), { ready: 0, looking: 0, label: 'Print cards', reason: 'Nothing to print yet' });
|
||||
assert.deepEqual(printStatus([looking(1), looking(2)]), { ready: 0, looking: 2, label: 'Print cards', reason: '2 still looking up' });
|
||||
assert.deepEqual(printStatus([ready(1)]), { ready: 1, looking: 0, label: 'Print 1 card', reason: null });
|
||||
const mixed = printStatus([ready(1), ready(2), looking(3), attention(4)]);
|
||||
assert.equal(mixed.label, 'Print 2 cards');
|
||||
assert.equal(mixed.reason, '1 still looking up');
|
||||
});
|
||||
|
||||
test('elapsed text', () => {
|
||||
assert.equal(elapsedText(0), '0 s');
|
||||
assert.equal(elapsedText(59_900), '59 s');
|
||||
assert.equal(elapsedText(12_400), '12 s');
|
||||
assert.equal(elapsedText(65_000), '1 min 05 s');
|
||||
assert.equal(elapsedText(-5), '0 s');
|
||||
});
|
||||
+22
-38
@@ -13,46 +13,30 @@ export function rowState(book: Book): RowState {
|
||||
return { kind: 'attention', reason: book.attentionReason ?? 'This book needs a look.' };
|
||||
}
|
||||
|
||||
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
|
||||
/** Queued books: the ones needing attention first, then newest first. */
|
||||
export function queueOrder(books: Book[]): Book[] {
|
||||
const rank = (b: Book) => (rowState(b).kind === 'attention' ? 0 : 1);
|
||||
return books
|
||||
.filter(b => b.inQueue)
|
||||
.sort((a, b) => {
|
||||
if (rank(a) !== rank(b)) return rank(a) - rank(b);
|
||||
if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;
|
||||
return b.id - a.id;
|
||||
});
|
||||
}
|
||||
|
||||
export function sessionSummary(books: Book[]): string {
|
||||
let ready = 0, looking = 0, attention = 0;
|
||||
for (const b of books) {
|
||||
const s = rowState(b).kind;
|
||||
if (s === 'ready') ready++; else if (s === 'looking') looking++; else attention++;
|
||||
export interface PrintStatus { ready: number; looking: number; label: string; reason: string | null }
|
||||
|
||||
/** What the print button says, and why it is disabled when it is. */
|
||||
export function printStatus(queue: Book[]): PrintStatus {
|
||||
let ready = 0, looking = 0;
|
||||
for (const b of queue) {
|
||||
const k = rowState(b).kind;
|
||||
if (k === 'ready') ready++; else if (k === 'looking') looking++;
|
||||
}
|
||||
const parts = [`${books.length} scanned`];
|
||||
if (ready) parts.push(`${ready} ready`);
|
||||
if (looking) parts.push(`${looking} looking up`);
|
||||
if (attention) parts.push(`${attention} ${attention === 1 ? 'needs' : 'need'} attention`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
export interface QueueSplit { ready: Book[]; looking: Book[] }
|
||||
|
||||
/** Queued books, split into the ones that can be printed now and the ones still being looked up. */
|
||||
export function queueSplit(books: Book[]): QueueSplit {
|
||||
const ready: Book[] = [], looking: Book[] = [];
|
||||
for (const b of books) {
|
||||
if (!b.inQueue) continue;
|
||||
const s = rowState(b).kind;
|
||||
if (s === 'ready') ready.push(b); else if (s === 'looking') looking.push(b);
|
||||
}
|
||||
return { ready, looking };
|
||||
}
|
||||
|
||||
export function queueHeader(ready: number, looking: number): string {
|
||||
const head = plural(ready, 'card', 'cards') + ' ready';
|
||||
return looking ? `${head} · ${looking} still looking up` : head;
|
||||
}
|
||||
|
||||
export function pdfLabel(ready: number): string {
|
||||
return ready ? `Make PDF (${plural(ready, 'card', 'cards')})` : 'Make PDF';
|
||||
}
|
||||
|
||||
export function queueTabLabel(ready: number, looking: number): string {
|
||||
const n = ready + looking;
|
||||
return n ? `Print queue (${n})` : 'Print queue';
|
||||
const label = ready === 0 ? 'Print cards' : `Print ${ready} ${ready === 1 ? 'card' : 'cards'}`;
|
||||
const reason = looking ? `${looking} still looking up` : ready === 0 ? 'Nothing to print yet' : null;
|
||||
return { ready, looking, label, reason };
|
||||
}
|
||||
|
||||
/** "12 s", "1 min 05 s" */
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useEffect, useState } from 'preact/hooks';
|
||||
|
||||
/** What the Scan screen's camera tells the settings panel: which cameras exist, which is chosen, the stream size. */
|
||||
export interface CameraInfo { devices: { id: string; label: string }[]; deviceId: string; resolution: string }
|
||||
|
||||
const CAMERA_KEY = 'camera';
|
||||
const readFlag = (k: string) => { try { return localStorage.getItem(k); } catch { return null; } };
|
||||
export const writeFlag = (k: string, v: string | null) => {
|
||||
try { if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* ignore */ }
|
||||
};
|
||||
export { readFlag };
|
||||
|
||||
let info: CameraInfo = { devices: [], deviceId: readFlag(CAMERA_KEY) ?? '', resolution: '' };
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export const getCamera = () => info;
|
||||
export function updateCamera(patch: Partial<CameraInfo>): void {
|
||||
info = { ...info, ...patch };
|
||||
listeners.forEach(l => l());
|
||||
}
|
||||
export function chooseCamera(deviceId: string): void {
|
||||
writeFlag(CAMERA_KEY, deviceId || null);
|
||||
updateCamera({ deviceId });
|
||||
}
|
||||
|
||||
export function useCamera(): CameraInfo {
|
||||
const [, force] = useState(0);
|
||||
useEffect(() => {
|
||||
const l = () => force(n => n + 1);
|
||||
listeners.add(l);
|
||||
return () => { listeners.delete(l); };
|
||||
}, []);
|
||||
return info;
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { useState } from 'preact/hooks';
|
||||
import type { Book } from '../../shared/types.ts';
|
||||
import { api } from '../api.ts';
|
||||
import { upsertBook, dispatch } from '../live.ts';
|
||||
import { parseYear } from '../year.ts';
|
||||
|
||||
export function BookEditor({ book, onClose }: { book: Book; onClose: () => void }) {
|
||||
const [title, setTitle] = useState(book.title);
|
||||
const [authors, setAuthors] = useState(book.authors.join('; '));
|
||||
const [publisher, setPublisher] = useState(book.publisher ?? '');
|
||||
const [year, setYear] = useState(book.year?.toString() ?? '');
|
||||
const [callNumber, setCallNumber] = useState(book.callNumber ?? '');
|
||||
const [msg, setMsg] = useState('');
|
||||
const [yearError, setYearError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function run(fn: () => Promise<void>) {
|
||||
setBusy(true); setMsg('');
|
||||
try { await fn(); } catch (e) { setMsg((e as Error).message); }
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
const save = (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
const y = parseYear(year);
|
||||
if (!y.ok) { setYearError('Enter the year as digits, for example 2018, or leave it empty.'); return; }
|
||||
setYearError('');
|
||||
void run(async () => {
|
||||
const patch: Record<string, unknown> = {
|
||||
title: title.trim(),
|
||||
authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean),
|
||||
publisher: publisher.trim() || null,
|
||||
year: y.value,
|
||||
};
|
||||
if (callNumber.trim() !== (book.callNumber ?? '')) patch.callNumber = callNumber.trim();
|
||||
upsertBook(await api.patchBook(book.id, patch));
|
||||
onClose();
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form class="card editor" onSubmit={save}>
|
||||
<label>Title<input value={title} onInput={e => setTitle(e.currentTarget.value)} required /></label>
|
||||
<label>Authors (separate with ;)<input value={authors} onInput={e => setAuthors(e.currentTarget.value)} /></label>
|
||||
<div class="row">
|
||||
<label class="grow">Publisher<input value={publisher} onInput={e => setPublisher(e.currentTarget.value)} /></label>
|
||||
<label class="year">Year<input inputMode="numeric" value={year} aria-invalid={yearError ? 'true' : undefined} onInput={e => { setYear(e.currentTarget.value); setYearError(''); }} /></label>
|
||||
</div>
|
||||
{yearError ? <p class="error" role="alert">{yearError}</p> : null}
|
||||
<label>Call number
|
||||
<input class="mono" value={callNumber} onInput={e => setCallNumber(e.currentTarget.value)} />
|
||||
<small>Changing this locks the number</small>
|
||||
</label>
|
||||
{book.attentionReason ? <p class="warn">{book.attentionReason}</p> : null}
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
<div class="row wrap">
|
||||
<button type="submit" class="primary" disabled={busy}>Save</button>
|
||||
<button type="button" disabled={busy} onClick={() => run(async () => { upsertBook(await api.queueBook(book.id)); })}>Queue reprint</button>
|
||||
<button type="button" disabled={busy || book.manualOverride}
|
||||
title={book.manualOverride ? 'This number was set by hand' : undefined}
|
||||
onClick={() => run(async () => { upsertBook(await api.retryBook(book.id)); })}>Look up again</button>
|
||||
<button type="button" class="danger" disabled={busy} onClick={() => {
|
||||
if (!confirm(`Delete "${book.title}"?`)) return;
|
||||
void run(async () => { await api.deleteBook(book.id); dispatch({ type: 'delete', id: book.id }); onClose(); });
|
||||
}}>Delete</button>
|
||||
<button type="button" class="quiet" onClick={onClose}>Close</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Book } from '../../shared/types.ts';
|
||||
import { rowState } from '../bookstate.ts';
|
||||
import { CallNo } from './CallNo.tsx';
|
||||
import { StateMark, StateText } from './StateMark.tsx';
|
||||
|
||||
function Main({ book, showYear }: { book: Book; showYear: boolean }) {
|
||||
const byline = [book.authors.join(', '), showYear ? book.year : null].filter(Boolean).join(' · ');
|
||||
return (
|
||||
<span class="row-main">
|
||||
<span class="row-title">{book.title}</span>
|
||||
{byline ? <span class="row-sub">{byline}</span> : null}
|
||||
<StateText book={book} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** A queued book on the Scan screen: state, call number, title, and the actions that apply. */
|
||||
export function QueueRow({ book, onFix, onRemove }: { book: Book; onFix: () => void; onRemove: () => void }) {
|
||||
const kind = rowState(book).kind;
|
||||
return (
|
||||
<li class={'row row-queue row-' + kind} data-book-id={book.id}>
|
||||
<StateMark book={book} />
|
||||
<CallNo value={kind === 'looking' ? null : book.callNumber} approximate={book.confidence === 'approximate'} source={book.source} />
|
||||
<Main book={book} showYear={false} />
|
||||
<span class="row-actions">
|
||||
{kind === 'attention' ? <button type="button" class="btn" onClick={onFix}>Fix</button> : null}
|
||||
<button type="button" class="btn-icon" onClick={onRemove} aria-label={`Remove "${book.title}"`} title="Remove">×</button>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** A book in the Library: the whole row opens the editor. */
|
||||
export function LibraryRow({ book, onOpen }: { book: Book; onOpen: () => void }) {
|
||||
const kind = rowState(book).kind;
|
||||
return (
|
||||
<li data-book-id={book.id}>
|
||||
<button type="button" class={'row row-library row-' + kind} onClick={onOpen}>
|
||||
<StateMark book={book} />
|
||||
<CallNo value={kind === 'looking' ? null : book.callNumber} approximate={book.confidence === 'approximate'} source={book.source} />
|
||||
<Main book={book} showYear />
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import type { Book } from '../../shared/types.ts';
|
||||
import { elapsedText, rowState } from '../bookstate.ts';
|
||||
import { lookupStartedAt, useNow } from '../live.ts';
|
||||
|
||||
const CheckIcon = () => (
|
||||
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3.2 3.2L13 4.8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /></svg>
|
||||
);
|
||||
const AlertIcon = () => (
|
||||
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 2.2L14.6 13.5H1.4L8 2.2z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" /><path d="M8 6.6v3.2M8 11.6v.1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
|
||||
);
|
||||
|
||||
function Looking({ book }: { book: Book }) {
|
||||
const now = useNow(true);
|
||||
return <span class="state-label"><span class="spinner" aria-hidden="true" />Looking up… <span class="elapsed">{elapsedText(now - lookupStartedAt(book))}</span></span>;
|
||||
}
|
||||
|
||||
/** The one label a book shows: Looking up… (spinner, seconds), Ready, or Needs attention. */
|
||||
export function StateLabel({ book }: { book: Book }) {
|
||||
const s = rowState(book);
|
||||
if (s.kind === 'looking') return <Looking book={book} />;
|
||||
if (s.kind === 'ready') return <span class="state-label"><CheckIcon />Ready</span>;
|
||||
return <span class="state-label"><AlertIcon />Needs attention</span>;
|
||||
}
|
||||
@@ -1,13 +1,23 @@
|
||||
import { cardLines, parseCallNumber } from '../../shared/callnumber.ts';
|
||||
|
||||
export function CallNo({ value, approximate }: { value: string | null; approximate?: boolean }) {
|
||||
if (!value) return <span class="callno muted">No call number</span>;
|
||||
export const APPROX_TIP = 'Number borrowed from another edition';
|
||||
export const SIMILAR_TIP = 'Number borrowed from similar books';
|
||||
|
||||
/** A call number in two monospaced lines, the way it is printed on the card. `~` marks an approximate one. */
|
||||
export function CallNo({ value, approximate, source, large }: { value: string | null; approximate?: boolean; source?: string | null; large?: boolean }) {
|
||||
const similar = source === 'similar';
|
||||
const tip = similar ? SIMILAR_TIP : APPROX_TIP;
|
||||
const cls = 'callno' + (large ? ' callno-large' : '');
|
||||
if (!value) return <span class={cls + ' callno-none'} aria-label="No call number yet">–</span>;
|
||||
const cn = parseCallNumber(value);
|
||||
const lines = cn ? cardLines(cn) : [value, ''];
|
||||
return (
|
||||
<span class="callno">
|
||||
<span class="callno-line">{lines[0]}{approximate ? <span class="approx" title="Approximate number"> ~</span> : null}</span>
|
||||
<span class="callno-line">{lines[1] || ' '}</span>
|
||||
<span class={cls}>
|
||||
<span class="callno-line">{lines[0]}</span>
|
||||
<span class="callno-line">
|
||||
{lines[1]}
|
||||
{approximate || similar ? <span class="approx" title={tip} aria-label={tip}> ~</span> : null}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import { useEffect, useState } from 'preact/hooks';
|
||||
import type { Book, SearchResult } from '../../shared/types.ts';
|
||||
import { api } from '../api.ts';
|
||||
import type { BookPatch } from '../api.ts';
|
||||
import { getBook, setLastScan, upsertBook, dispatch, useBooks } from '../live.ts';
|
||||
import { showToast } from '../toast-store.ts';
|
||||
import { splitTitleAuthor } from '../entry.ts';
|
||||
import { parseYear } from '../year.ts';
|
||||
import { rowState } from '../bookstate.ts';
|
||||
import { Panel } from './Panel.tsx';
|
||||
import { moveActive, ResultList } from './Results.tsx';
|
||||
import { Spinner } from './StateMark.tsx';
|
||||
import { composeNumber, findNeighbours } from '../shelve.ts';
|
||||
|
||||
/** `new` may carry what was typed in the entry box. */
|
||||
export type EditorTarget = { kind: 'edit'; id: number } | { kind: 'new'; title?: string; authors?: string };
|
||||
|
||||
const yearValue = (text: string) => { const y = parseYear(text); return y.ok ? y.value : null; };
|
||||
const splitAuthors = (text: string) => text.split(/[;\n]/).map(a => a.trim()).filter(Boolean);
|
||||
/** A book that has not been found yet is titled with its ISBN or LCCN; that is not worth searching for. */
|
||||
const knownTitle = (b: Book) => (/^[\d\s-]+$/.test(b.title) ? '' : b.title);
|
||||
|
||||
export function Editor({ target, onClose }: { target: EditorTarget; onClose: () => void }) {
|
||||
useBooks(); // re-render when the book changes underneath
|
||||
const book = target.kind === 'edit' ? getBook(target.id) : undefined;
|
||||
const missing = target.kind === 'edit' && !book;
|
||||
useEffect(() => { if (missing) onClose(); }, [missing]);
|
||||
if (target.kind === 'edit' && !book) return null;
|
||||
const fixing = !!book && rowState(book).kind === 'attention';
|
||||
return (
|
||||
<Panel title={!book ? 'Add a book' : fixing ? 'Fix this book' : 'Edit book'} onClose={onClose}>
|
||||
<EditorForm book={book} fixing={fixing} initial={target.kind === 'new' ? target : undefined} onClose={onClose} />
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function EditorForm({ book, fixing, initial, onClose }: {
|
||||
book: Book | undefined; fixing: boolean; initial?: { title?: string; authors?: string }; onClose: () => void;
|
||||
}) {
|
||||
const [title, setTitle] = useState(book ? knownTitle(book) || book.title : initial?.title ?? '');
|
||||
const [authors, setAuthors] = useState(book?.authors.join('; ') ?? initial?.authors ?? '');
|
||||
const [publisher, setPublisher] = useState(book?.publisher ?? '');
|
||||
const [year, setYear] = useState(book?.year?.toString() ?? '');
|
||||
const [callNumber, setCallNumber] = useState(book?.callNumber ?? '');
|
||||
const [picked, setPicked] = useState<SearchResult | null>(null);
|
||||
const [yearError, setYearError] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
|
||||
async function run(fn: () => Promise<void>) {
|
||||
setBusy(true); setError('');
|
||||
try { await fn(); } catch (e) { setError((e as Error).message); }
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
function save(ev: Event) {
|
||||
ev.preventDefault();
|
||||
const y = parseYear(year);
|
||||
if (!y.ok) { setYearError('Enter the year as digits, for example 2018, or leave it empty.'); return; }
|
||||
setYearError('');
|
||||
void run(async () => {
|
||||
const names = splitAuthors(authors);
|
||||
if (!book) {
|
||||
const created = await api.addManual({
|
||||
title: title.trim(), authors: names,
|
||||
...(y.value !== null ? { year: y.value } : {}),
|
||||
...(publisher.trim() ? { publisher: publisher.trim() } : {}),
|
||||
...(callNumber.trim() ? { callNumber: callNumber.trim() } : {}),
|
||||
});
|
||||
upsertBook(created); setLastScan(created.id, false);
|
||||
showToast(`Added "${created.title}"`);
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
const patch: BookPatch = { title: title.trim(), authors: names, publisher: publisher.trim() || null, year: y.value };
|
||||
const numberChanged = callNumber.trim() !== (book.callNumber ?? '');
|
||||
if (numberChanged) patch.callNumber = callNumber.trim();
|
||||
let saved = await api.patchBook(book.id, patch);
|
||||
// A result without a call number of its own: ask the sources again with the better details.
|
||||
if (picked && picked.lcc.length === 0 && !numberChanged && !book.manualOverride) saved = await api.retryBook(book.id);
|
||||
upsertBook(saved);
|
||||
showToast(saved.status === 'pending' ? `Saved "${saved.title}". Looking up the call number.` : `Saved "${saved.title}"`);
|
||||
onClose();
|
||||
});
|
||||
}
|
||||
|
||||
function pick(r: SearchResult) {
|
||||
setPicked(r);
|
||||
setTitle(r.title);
|
||||
setAuthors(r.authors.join('; '));
|
||||
setPublisher(r.publisher ?? '');
|
||||
setYear(r.year ? String(r.year) : '');
|
||||
if (r.lcc[0]) setCallNumber(r.lcc[0]);
|
||||
}
|
||||
|
||||
return (
|
||||
<form class="editor" onSubmit={save}>
|
||||
{fixing && book ? (
|
||||
<>
|
||||
<p class="state-text state-attention">{book.attentionReason ?? 'This book needs a look.'}</p>
|
||||
<FixSearch initial={knownTitle(book)} onPick={pick} />
|
||||
</>
|
||||
) : null}
|
||||
<label class="field">Title
|
||||
<input value={title} onInput={e => setTitle(e.currentTarget.value)} required data-autofocus={!fixing ? '' : undefined} />
|
||||
</label>
|
||||
<label class="field">Authors
|
||||
<input value={authors} onInput={e => setAuthors(e.currentTarget.value)} />
|
||||
<span class="help">Separate several with ;</span>
|
||||
</label>
|
||||
<div class="field-pair">
|
||||
<label class="field">Publisher
|
||||
<input value={publisher} onInput={e => setPublisher(e.currentTarget.value)} />
|
||||
</label>
|
||||
<label class="field">Year
|
||||
<input inputMode="numeric" value={year} aria-invalid={yearError ? 'true' : undefined}
|
||||
onInput={e => { setYear(e.currentTarget.value); setYearError(''); }} />
|
||||
</label>
|
||||
</div>
|
||||
{yearError ? <p class="error" role="alert">{yearError}</p> : null}
|
||||
<label class="field">Call number
|
||||
<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>
|
||||
<ShelveWith exclude={book?.id} compose={neighbour => composeNumber(neighbour, splitAuthors(authors), title, yearValue(year))}
|
||||
onChoose={setCallNumber} />
|
||||
{error ? <p class="error" role="alert">{error}</p> : null}
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit" class="btn btn-primary" disabled={busy || !title.trim()}>Save</button>
|
||||
{book ? (
|
||||
<>
|
||||
<button type="button" class="btn" disabled={busy || book.inQueue} title={book.inQueue ? 'Already in Cards to print' : undefined}
|
||||
onClick={() => run(async () => {
|
||||
upsertBook(await api.queueBook(book.id));
|
||||
showToast(`Queued a card for "${book.title}"`);
|
||||
onClose();
|
||||
})}>Print another card</button>
|
||||
<button type="button" class="btn" disabled={busy || book.manualOverride}
|
||||
title={book.manualOverride ? 'This number was set by hand, so there is nothing to look up' : undefined}
|
||||
onClick={() => run(async () => {
|
||||
upsertBook(await api.retryBook(book.id));
|
||||
showToast(`Looking up "${book.title}" again`);
|
||||
onClose();
|
||||
})}>Look up again</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{book ? (
|
||||
<div class="danger-zone">
|
||||
{confirming ? (
|
||||
<div class="confirm" role="group" aria-label="Delete this book?">
|
||||
<span class="confirm-text">Delete this book?</span>
|
||||
<button type="button" class="btn btn-danger" disabled={busy} ref={el => { el?.focus(); }}
|
||||
onClick={() => run(async () => {
|
||||
await api.deleteBook(book.id);
|
||||
dispatch({ type: 'delete', id: book.id });
|
||||
showToast(`Deleted "${book.title}"`);
|
||||
onClose();
|
||||
})}>Delete</button>
|
||||
<button type="button" class="btn" onClick={() => setConfirming(false)}>Keep</button>
|
||||
</div>
|
||||
) : (
|
||||
<button type="button" class="btn btn-text btn-danger" disabled={busy} onClick={() => setConfirming(true)}>Delete</button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Search for it": looks the book up by title (and author) so its details can be copied into the fields. */
|
||||
function FixSearch({ initial, onPick }: { initial: string; onPick: (r: SearchResult) => void }) {
|
||||
const [text, setText] = useState(initial);
|
||||
const [results, setResults] = useState<SearchResult[] | null>(null);
|
||||
const [active, setActive] = useState(-1);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
|
||||
async function search() {
|
||||
const { title, author } = splitTitleAuthor(text);
|
||||
if (!title) return;
|
||||
setBusy(true); setMessage(''); setResults(null); setActive(-1);
|
||||
try {
|
||||
const found = await api.search(title, author);
|
||||
setResults(found);
|
||||
if (found.length === 0) setMessage('No matches. Edit the details by hand below.');
|
||||
} catch (e) {
|
||||
setMessage(`The search failed: ${(e as Error).message}`);
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
useEffect(() => { if (initial) void search(); }, []);
|
||||
|
||||
const choose = (r: SearchResult) => { onPick(r); setResults(null); setMessage('Details copied below. Check them, then save.'); };
|
||||
const open = !!results && results.length > 0;
|
||||
|
||||
return (
|
||||
<div class="fix-search">
|
||||
<label class="field">Search for it
|
||||
<span class="search-row">
|
||||
<input type="text" role="combobox" aria-expanded={open} aria-controls="fix-results" aria-autocomplete="list"
|
||||
aria-activedescendant={open && active >= 0 ? `fix-results-${active}` : undefined}
|
||||
value={text} data-autofocus="" autocomplete="off"
|
||||
onInput={e => { setText(e.currentTarget.value); setActive(-1); }}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (open && active >= 0) choose(results![active]!); else void search();
|
||||
} else if (open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
|
||||
e.preventDefault(); setActive(moveActive(e.key, active, results!.length));
|
||||
} else if (e.key === 'Escape' && open) {
|
||||
e.preventDefault(); e.stopPropagation(); setResults(null);
|
||||
}
|
||||
}} />
|
||||
<button type="button" class="btn" disabled={busy || !text.trim()} onClick={() => void search()}>Search</button>
|
||||
</span>
|
||||
</label>
|
||||
{busy ? <p class="help"><Spinner /> Searching…</p> : null}
|
||||
{message ? <p class="help" role="status">{message}</p> : null}
|
||||
{open ? <ResultList id="fix-results" label="Search results" results={results!} active={active} onPick={choose} onHover={setActive} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Shelve it with…": search the library for a book this one belongs next to, and borrow its class for the call number. */
|
||||
function ShelveWith({ exclude, compose, onChoose }: { exclude: number | undefined; compose: (neighbour: string) => string | null; onChoose: (n: string) => void }) {
|
||||
const books = useBooks();
|
||||
const [text, setText] = useState('');
|
||||
const [active, setActive] = useState(-1);
|
||||
const matches = findNeighbours(books.filter(b => b.id !== exclude), text);
|
||||
const open = matches.length > 0;
|
||||
const choose = (b: Book) => {
|
||||
const n = b.callNumber ? compose(b.callNumber) : null;
|
||||
if (!n) { showToast('Could not make a call number from that book'); return; }
|
||||
onChoose(n); setText(''); setActive(-1);
|
||||
showToast(`Call number set to ${n}. Check it, then save.`);
|
||||
};
|
||||
return (
|
||||
<div class="field">
|
||||
<label for="shelve-with">Shelve it with…</label>
|
||||
<input id="shelve-with" type="text" role="combobox" autocomplete="off" aria-expanded={open} aria-controls="shelve-results" aria-autocomplete="list"
|
||||
aria-activedescendant={open && active >= 0 ? `shelve-results-${active}` : undefined}
|
||||
value={text} onInput={e => { setText(e.currentTarget.value); setActive(-1); }}
|
||||
onKeyDown={e => {
|
||||
if (open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) { e.preventDefault(); setActive(moveActive(e.key, active, matches.length)); }
|
||||
else if (e.key === 'Enter') { e.preventDefault(); if (open && active >= 0) choose(matches[active]!); }
|
||||
else if (e.key === 'Escape' && open) { e.preventDefault(); e.stopPropagation(); setText(''); }
|
||||
}} />
|
||||
<span class="help">Pick a book this one belongs next to</span>
|
||||
{open ? (
|
||||
<ul class="results" role="listbox" id="shelve-results" aria-label="Books in your library">
|
||||
{matches.map((b, i) => (
|
||||
<li role="option" id={`shelve-results-${i}`} aria-selected={i === active} class={'result' + (i === active ? ' active' : '')}
|
||||
onMouseDown={e => e.preventDefault()} onMouseMove={() => setActive(i)} onClick={() => choose(b)}>
|
||||
<span class="result-title">{b.title}</span>
|
||||
<span class="result-sub mono">{b.callNumber}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useRef } from 'preact/hooks';
|
||||
import type { ComponentChildren } from 'preact';
|
||||
import { useDialog } from '../dialog.ts';
|
||||
|
||||
/** A side panel on wide windows and a full-width sheet on narrow ones, over a dimmed page. */
|
||||
export function Panel({ title, onClose, children }: { title: string; onClose: () => void; children: ComponentChildren }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useDialog(ref, onClose, true);
|
||||
return (
|
||||
<div class="backdrop" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div class="panel" role="dialog" aria-modal="true" aria-label={title} ref={ref} tabIndex={-1}>
|
||||
<div class="panel-head">
|
||||
<h2>{title}</h2>
|
||||
<button type="button" class="btn-icon" onClick={onClose} aria-label="Close" title="Close">×</button>
|
||||
</div>
|
||||
<div class="panel-body">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { SearchResult } from '../../shared/types.ts';
|
||||
|
||||
/** Next highlighted index for an arrow key; -1 means nothing is highlighted. */
|
||||
export function moveActive(key: string, active: number, count: number): number {
|
||||
if (count === 0) return -1;
|
||||
if (key === 'ArrowDown') return active < count - 1 ? active + 1 : 0;
|
||||
if (key === 'ArrowUp') return active > 0 ? active - 1 : count - 1;
|
||||
return active;
|
||||
}
|
||||
|
||||
export interface Footer { label: string; onPick: () => void }
|
||||
|
||||
/** Search results as a listbox. The input that owns it keeps focus and points at the highlighted option. */
|
||||
export function ResultList({ id, label, results, active, onPick, onHover, footer }: {
|
||||
id: string; label: string; results: SearchResult[]; active: number;
|
||||
onPick: (r: SearchResult) => void; onHover: (i: number) => void; footer?: Footer;
|
||||
}) {
|
||||
const keep = (e: Event) => e.preventDefault(); // a click must not take focus from the input
|
||||
return (
|
||||
<ul class="results" role="listbox" id={id} aria-label={label}>
|
||||
{results.map((r, i) => (
|
||||
<li role="option" id={`${id}-${i}`} class={'result' + (i === active ? ' active' : '')} aria-selected={i === active}
|
||||
onMouseDown={keep} onMouseMove={() => onHover(i)} onClick={() => onPick(r)}>
|
||||
<span class="result-title">{r.title}</span>
|
||||
<span class="result-sub">{[r.authors.join(', '), r.year, r.publisher].filter(Boolean).join(' · ')}</span>
|
||||
</li>
|
||||
))}
|
||||
{footer ? (
|
||||
<li role="option" id={`${id}-${results.length}`} class={'result result-footer' + (active === results.length ? ' active' : '')}
|
||||
aria-selected={active === results.length} onMouseDown={keep} onMouseMove={() => onHover(results.length)} onClick={footer.onPick}>
|
||||
<span class="result-title">{footer.label}</span>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useEffect, useState } from 'preact/hooks';
|
||||
import { api } from '../api.ts';
|
||||
import { chooseCamera, useCamera } from '../camera.ts';
|
||||
import { showError, showToast } from '../toast-store.ts';
|
||||
import { Panel } from './Panel.tsx';
|
||||
|
||||
export function Settings({ onClose }: { onClose: () => void }) {
|
||||
const cam = useCamera();
|
||||
const [x, setX] = useState('0');
|
||||
const [y, setY] = useState('0');
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api.getSettings()
|
||||
.then(s => { setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); setLoaded(true); })
|
||||
.catch(e => showError(`Could not load the printer settings: ${(e as Error).message}`));
|
||||
}, []);
|
||||
|
||||
async function save(ev: Event) {
|
||||
ev.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
const s = await api.putSettings({ offsetXmm: Number(x) || 0, offsetYmm: Number(y) || 0 });
|
||||
setX(String(s.offsetXmm)); setY(String(s.offsetYmm));
|
||||
showToast('Printer alignment saved');
|
||||
} catch (e) { showError(`Could not save the alignment: ${(e as Error).message}`); }
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Panel title="Settings" onClose={onClose}>
|
||||
<section class="settings-block" aria-labelledby="set-camera">
|
||||
<h3 id="set-camera">Camera</h3>
|
||||
{cam.devices.length > 1 ? (
|
||||
<label class="field">Camera
|
||||
<select value={cam.deviceId} onChange={e => chooseCamera(e.currentTarget.value)}>
|
||||
<option value="">Default camera</option>
|
||||
{cam.devices.map((d, i) => <option value={d.id}>{d.label || `Camera ${i + 1}`}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
) : null}
|
||||
<p class="help">{cam.resolution ? `Stream resolution: ${cam.resolution}` : 'Stream resolution: shown while the camera is on.'}</p>
|
||||
</section>
|
||||
|
||||
<form class="settings-block" aria-labelledby="set-print" onSubmit={save}>
|
||||
<h3 id="set-print">Printer alignment</h3>
|
||||
<div class="field-pair">
|
||||
<label class="field">Offset X (mm)
|
||||
<input type="number" step="0.25" min="-10" max="10" value={x} onInput={e => setX(e.currentTarget.value)} />
|
||||
</label>
|
||||
<label class="field">Offset Y (mm)
|
||||
<input type="number" step="0.25" min="-10" max="10" value={y} onInput={e => setY(e.currentTarget.value)} />
|
||||
</label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="submit" class="btn" disabled={busy || !loaded}>Save</button>
|
||||
<a class="btn" href="/api/calibration.pdf" target="_blank" rel="noopener">Print calibration page</a>
|
||||
</div>
|
||||
<p class="help">Print the calibration page on plain paper, hold it over a real sheet up to a light, and enter how far the lines are off, up to 10 mm.</p>
|
||||
</form>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Book } from '../../shared/types.ts';
|
||||
import { elapsedText, rowState } from '../bookstate.ts';
|
||||
import { lookupStartedAt, useNow } from '../live.ts';
|
||||
|
||||
export const LABEL = { looking: 'Looking up…', ready: 'Ready', attention: 'Needs attention' } as const;
|
||||
|
||||
export const CheckIcon = () => (
|
||||
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3.2 3.2L13 4.8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /></svg>
|
||||
);
|
||||
export const WarnIcon = () => (
|
||||
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 2.2L14.6 13.5H1.4L8 2.2z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" /><path d="M8 6.6v3.2M8 11.6v.1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
|
||||
);
|
||||
export const Spinner = () => <span class="spinner" aria-hidden="true" />;
|
||||
|
||||
/** The small mark at the left of a row: spinner, nothing much when ready, amber warning. */
|
||||
export function StateMark({ book }: { book: Book }) {
|
||||
const s = rowState(book);
|
||||
if (s.kind === 'looking') return <span class="mark mark-looking" aria-hidden="true"><Spinner /></span>;
|
||||
if (s.kind === 'attention') return <span class="mark mark-attention" aria-hidden="true"><WarnIcon /></span>;
|
||||
return <span class="mark mark-ready" role="img" aria-label={LABEL.ready} title={LABEL.ready}><CheckIcon /></span>;
|
||||
}
|
||||
|
||||
function LookingText({ book, note }: { book: Book; note: string | null }) {
|
||||
const now = useNow(true);
|
||||
return (
|
||||
<span class="state-text state-looking">
|
||||
{LABEL.looking} <span class="elapsed">{elapsedText(now - lookupStartedAt(book))}</span>
|
||||
{note ? <span class="note"> · {note}</span> : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The worded state under a title: "Looking up… 12 s", or "Needs attention · reason". Nothing when ready. */
|
||||
export function StateText({ book }: { book: Book }) {
|
||||
const s = rowState(book);
|
||||
if (s.kind === 'looking') return <LookingText book={book} note={s.note} />;
|
||||
if (s.kind === 'attention') return <span class="state-text state-attention">{LABEL.attention} · {s.reason}</span>;
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useEffect } from 'preact/hooks';
|
||||
import { dismissToast, useToasts } from '../toast-store.ts';
|
||||
import type { Toast } from '../toasts.ts';
|
||||
|
||||
function ToastItem({ toast }: { toast: Toast }) {
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => dismissToast(toast.id), toast.ms);
|
||||
return () => clearTimeout(t);
|
||||
}, [toast.id]);
|
||||
return (
|
||||
<div class={'toast toast-' + toast.tone} role={toast.tone === 'error' ? 'alert' : 'status'}>
|
||||
<span class="toast-text">{toast.text}</span>
|
||||
{toast.action ? (
|
||||
<button type="button" class="toast-action" onClick={() => { toast.action!.run(); dismissToast(toast.id); }}>{toast.action.label}</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Toasts() {
|
||||
const toasts = useToasts();
|
||||
return <div class="toasts">{toasts.map(t => <ToastItem key={t.id} toast={t} />)}</div>;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useRef } from 'preact/hooks';
|
||||
import type { RefObject } from 'preact';
|
||||
|
||||
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
||||
|
||||
/** True while any dialog is open; the Scan screen then leaves keyboard focus alone. */
|
||||
export function dialogOpen(): boolean {
|
||||
return document.querySelector('[role="dialog"]') !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Behaviour every panel shares: focus moves in when it opens and returns to where it was when it closes,
|
||||
* Escape closes it, and (for a modal one) Tab stays inside. A non-modal panel also closes on a click outside it.
|
||||
*/
|
||||
export function useDialog(ref: RefObject<HTMLElement | null>, onClose: () => void, modal: boolean): void {
|
||||
const close = useRef(onClose);
|
||||
close.current = onClose;
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
const opener = document.activeElement as HTMLElement | null;
|
||||
if (root) {
|
||||
const first = root.querySelector<HTMLElement>('[data-autofocus]') ?? root.querySelector<HTMLElement>(FOCUSABLE);
|
||||
(first ?? root).focus();
|
||||
}
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') { e.preventDefault(); close.current(); return; }
|
||||
if (e.key !== 'Tab' || !modal || !root) return;
|
||||
const items = [...root.querySelectorAll<HTMLElement>(FOCUSABLE)];
|
||||
if (items.length === 0) { e.preventDefault(); return; }
|
||||
const first = items[0]!, last = items[items.length - 1]!;
|
||||
const a = document.activeElement;
|
||||
if (e.shiftKey && (a === first || !root.contains(a))) { e.preventDefault(); last.focus(); }
|
||||
else if (!e.shiftKey && (a === last || !root.contains(a))) { e.preventDefault(); first.focus(); }
|
||||
};
|
||||
const onPointer = (e: PointerEvent) => {
|
||||
if (!root || root.contains(e.target as Node)) return;
|
||||
// Pressing the button that opened the panel is handled by that button.
|
||||
if (opener && opener.contains(e.target as Node)) return;
|
||||
close.current();
|
||||
};
|
||||
document.addEventListener('keydown', onKey);
|
||||
if (!modal) document.addEventListener('pointerdown', onPointer);
|
||||
return () => {
|
||||
document.removeEventListener('keydown', onKey);
|
||||
document.removeEventListener('pointerdown', onPointer);
|
||||
if (opener && opener.isConnected) opener.focus();
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { classifyEntry, splitTitleAuthor } from './entry.ts';
|
||||
|
||||
test('a valid ISBN-13 or ISBN-10, with or without hyphens, is an ISBN', () => {
|
||||
assert.deepEqual(classifyEntry('9781593278281'), { kind: 'isbn', isbn: '9781593278281' });
|
||||
assert.deepEqual(classifyEntry(' 978-1-59327-828-1 '), { kind: 'isbn', isbn: '9781593278281' });
|
||||
assert.deepEqual(classifyEntry('0201835959'), { kind: 'isbn', isbn: '9780201835953' });
|
||||
});
|
||||
|
||||
test('8 to 12 digits with an optional hyphen is an LCCN', () => {
|
||||
assert.deepEqual(classifyEntry('88005934'), { kind: 'lccn', lccn: '88005934' });
|
||||
assert.deepEqual(classifyEntry('2001-012345'), { kind: 'lccn', lccn: '2001-012345' });
|
||||
});
|
||||
|
||||
test('other digit strings are rejected, not searched', () => {
|
||||
assert.deepEqual(classifyEntry('9781593278282'), { kind: 'bad-digits' }); // wrong check digit
|
||||
assert.deepEqual(classifyEntry('1234567'), { kind: 'bad-digits' });
|
||||
assert.deepEqual(classifyEntry('1234567890123456'), { kind: 'bad-digits' });
|
||||
assert.deepEqual(classifyEntry('12-34'), { kind: 'bad-digits' });
|
||||
});
|
||||
|
||||
test('text is a title search', () => {
|
||||
assert.deepEqual(classifyEntry(' The Pragmatic Programmer '), { kind: 'title', title: 'The Pragmatic Programmer', author: '' });
|
||||
assert.deepEqual(classifyEntry('1984'), { kind: 'bad-digits' });
|
||||
assert.deepEqual(classifyEntry('Catch-22'), { kind: 'title', title: 'Catch-22', author: '' });
|
||||
});
|
||||
|
||||
test('empty input does nothing', () => {
|
||||
assert.deepEqual(classifyEntry(' '), { kind: 'empty' });
|
||||
});
|
||||
|
||||
test('" by " and a comma split the title from the author', () => {
|
||||
assert.deepEqual(splitTitleAuthor('Dune by Frank Herbert'), { title: 'Dune', author: 'Frank Herbert' });
|
||||
assert.deepEqual(splitTitleAuthor('Dune BY Frank Herbert'), { title: 'Dune', author: 'Frank Herbert' });
|
||||
assert.deepEqual(splitTitleAuthor('Dune, Frank Herbert'), { title: 'Dune', author: 'Frank Herbert' });
|
||||
assert.deepEqual(classifyEntry('Stand by Me by Stephen King'), { kind: 'title', title: 'Stand by Me', author: 'Stephen King' });
|
||||
});
|
||||
|
||||
test('"by" inside a word or at an edge does not split', () => {
|
||||
assert.deepEqual(splitTitleAuthor('Standby'), { title: 'Standby', author: '' });
|
||||
assert.deepEqual(splitTitleAuthor('Goodbye'), { title: 'Goodbye', author: '' });
|
||||
assert.deepEqual(splitTitleAuthor('Dune,'), { title: 'Dune,', author: '' });
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { normalizeIsbn } from '../shared/isbn.ts';
|
||||
|
||||
/** What the one entry box should do with what was typed. */
|
||||
export type EntryAction =
|
||||
| { kind: 'empty' }
|
||||
| { kind: 'isbn'; isbn: string }
|
||||
| { kind: 'lccn'; lccn: string }
|
||||
| { kind: 'bad-digits' }
|
||||
| { kind: 'title'; title: string; author: string };
|
||||
|
||||
const LCCN = /^\d+(?:-\d+)?$/;
|
||||
const DIGITS_ONLY = /^[\d\s-]+$/;
|
||||
|
||||
/** "Dune by Frank Herbert" or "Dune, Frank Herbert" become a title and an author; anything else is all title. */
|
||||
export function splitTitleAuthor(text: string): { title: string; author: string } {
|
||||
const t = text.trim().replace(/\s+/g, ' ');
|
||||
const by = t.toLowerCase().lastIndexOf(' by ');
|
||||
if (by > 0 && by + 4 < t.length) return { title: t.slice(0, by).trim(), author: t.slice(by + 4).trim() };
|
||||
const comma = t.indexOf(',');
|
||||
if (comma > 0 && comma < t.length - 1) return { title: t.slice(0, comma).trim(), author: t.slice(comma + 1).trim() };
|
||||
return { title: t, author: '' };
|
||||
}
|
||||
|
||||
export function classifyEntry(raw: string): EntryAction {
|
||||
const text = raw.trim();
|
||||
if (!text) return { kind: 'empty' };
|
||||
const isbn = normalizeIsbn(text);
|
||||
if (isbn) return { kind: 'isbn', isbn };
|
||||
const compact = text.replace(/\s+/g, '');
|
||||
if (compact.length >= 8 && compact.length <= 12 && LCCN.test(compact)) return { kind: 'lccn', lccn: compact };
|
||||
if (DIGITS_ONLY.test(text)) return { kind: 'bad-digits' };
|
||||
return { kind: 'title', ...splitTitleAuthor(text) };
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { groupLibrary, mainClass, matchesQuery } from './library.ts';
|
||||
|
||||
function book(id: number, over: Partial<Book>): Book {
|
||||
return {
|
||||
id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey: null, confidence: null, source: null, dewey: null,
|
||||
status: 'resolved', attentionReason: null, manualOverride: false, inQueue: false,
|
||||
printedAt: null, createdAt: '', updatedAt: '', ...over,
|
||||
};
|
||||
}
|
||||
const qa = (id: number, key: string) => book(id, { callNumber: 'QA76.73 .R87', sortKey: key });
|
||||
const ps = (id: number, key: string) => book(id, { callNumber: 'PS3558.E63 Z46', sortKey: key });
|
||||
|
||||
test('main class comes from the call number letters', () => {
|
||||
assert.equal(mainClass(qa(1, 'a')), 'Q');
|
||||
assert.equal(mainClass(ps(1, 'a')), 'P');
|
||||
assert.equal(mainClass(book(1, {})), null);
|
||||
assert.equal(mainClass(book(1, { callNumber: 'not a number' })), null);
|
||||
});
|
||||
|
||||
test('books are grouped by main class in shelf order, with names and an Unsorted group last', () => {
|
||||
const groups = groupLibrary([
|
||||
book(9, { title: 'Unknown', status: 'pending' }), qa(2, 'QA 0076'), ps(3, 'PS 3558'), qa(1, 'QA 0001'),
|
||||
book(8, { callNumber: 'garbage', status: 'needs_attention', sortKey: '~GARBAGE' }),
|
||||
]);
|
||||
assert.deepEqual(groups.map(g => g.key), ['P', 'Q', 'Unsorted']);
|
||||
assert.equal(groups[0]!.heading, 'P · Language and literature');
|
||||
assert.equal(groups[1]!.heading, 'Q · Science');
|
||||
assert.deepEqual(groups[1]!.books.map(b => b.id), [1, 2]);
|
||||
assert.deepEqual(groups[2]!.books.map(b => b.id).sort(), [8, 9]);
|
||||
assert.equal(groups[2]!.heading, 'Unsorted');
|
||||
});
|
||||
|
||||
test('search matches title, author, ISBN and call number', () => {
|
||||
const b = book(1, { title: 'Dune', authors: ['Frank Herbert'], isbn13: '9780441172719', callNumber: 'PS3558.E63' });
|
||||
for (const q of ['dune', 'herbert', '97804411', 'ps3558', ' ']) assert.ok(matchesQuery(b, q), q);
|
||||
assert.ok(!matchesQuery(b, 'emma'));
|
||||
});
|
||||
|
||||
test('filters apply before grouping, and an empty result has no groups', () => {
|
||||
const books = [qa(1, 'QA 1'), book(2, { status: 'needs_attention', callNumber: null }), ps(3, 'PS 1')];
|
||||
assert.deepEqual(groupLibrary(books, { attentionOnly: true }).map(g => g.key), ['Unsorted']);
|
||||
assert.deepEqual(groupLibrary(books, { query: 'T3' }).map(g => g.key), ['P']);
|
||||
assert.deepEqual(groupLibrary(books, { query: 'zzz' }), []);
|
||||
assert.deepEqual(groupLibrary([]), []);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { parseCallNumber } from '../shared/callnumber.ts';
|
||||
import { classNames } from '../shared/lcc-outline.ts';
|
||||
import { compareShelf } from './store.ts';
|
||||
|
||||
export interface LibraryGroup { key: string; heading: string; books: Book[] }
|
||||
|
||||
export const UNSORTED = 'Unsorted';
|
||||
|
||||
/** The main class letter of a book's call number, or null when it has none or cannot be read. */
|
||||
export function mainClass(book: Book): string | null {
|
||||
if (!book.callNumber) return null;
|
||||
const cn = parseCallNumber(book.callNumber);
|
||||
return cn ? cn.letters[0]! : null;
|
||||
}
|
||||
|
||||
export function matchesQuery(book: Book, query: string): boolean {
|
||||
const needle = query.trim().toLowerCase();
|
||||
if (!needle) return true;
|
||||
return [book.title, book.authors.join(' '), book.isbn13 ?? '', book.callNumber ?? ''].some(s => s.toLowerCase().includes(needle));
|
||||
}
|
||||
|
||||
export const needsAttention = (book: Book) => book.status === 'needs_attention';
|
||||
|
||||
/** Books in shelf order, grouped under their main class ("Q · Science"). Books without a readable number come last. */
|
||||
export function groupLibrary(books: Book[], opts: { query?: string; attentionOnly?: boolean } = {}): LibraryGroup[] {
|
||||
const groups = new Map<string, Book[]>();
|
||||
const unsorted: Book[] = [];
|
||||
for (const b of [...books].sort(compareShelf)) {
|
||||
if (opts.attentionOnly && !needsAttention(b)) continue;
|
||||
if (!matchesQuery(b, opts.query ?? '')) continue;
|
||||
const letter = mainClass(b);
|
||||
if (!letter) { unsorted.push(b); continue; }
|
||||
const list = groups.get(letter);
|
||||
if (list) list.push(b); else groups.set(letter, [b]);
|
||||
}
|
||||
const out: LibraryGroup[] = [...groups.keys()].sort().map(letter => {
|
||||
const name = classNames(letter).className;
|
||||
return { key: letter, heading: name ? `${letter} · ${name}` : letter, books: groups.get(letter)! };
|
||||
});
|
||||
if (unsorted.length) out.push({ key: UNSORTED, heading: UNSORTED, books: unsorted });
|
||||
return out;
|
||||
}
|
||||
+27
-2
@@ -3,8 +3,16 @@ import type { Book } from '../shared/types.ts';
|
||||
import { api } from './api.ts';
|
||||
import { emptyState, reduce, shelfOrder } from './store.ts';
|
||||
import type { BookAction, BookState } from './store.ts';
|
||||
import { emptyPending, queueVisible, visible } from './pending.ts';
|
||||
import { queueOrder } from './bookstate.ts';
|
||||
import type { PendingState } from './pending.ts';
|
||||
|
||||
let state: BookState = emptyState;
|
||||
/** Books removed from view whose real delete has not been sent yet (see removal.ts). */
|
||||
let pending: PendingState = emptyPending;
|
||||
/** The book most recently scanned or added, for the Last scan card. `existed` means it was in the library already. */
|
||||
export interface LastScan { id: number; existed: boolean }
|
||||
let lastScan: LastScan | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
/** When each book was first seen waiting for its lookup, for the elapsed-seconds display. */
|
||||
@@ -34,11 +42,22 @@ export function useNow(active: boolean): number {
|
||||
return now;
|
||||
}
|
||||
|
||||
function notify(): void { listeners.forEach(l => l()); }
|
||||
|
||||
export function dispatch(action: BookAction): void {
|
||||
trackPending(action);
|
||||
state = reduce(state, action);
|
||||
listeners.forEach(l => l());
|
||||
if (action.type === 'delete' && action.id in pending.items) { // the real delete is done
|
||||
const items = { ...pending.items };
|
||||
delete items[action.id];
|
||||
pending = { items };
|
||||
}
|
||||
notify();
|
||||
}
|
||||
export const getPending = () => pending;
|
||||
export function setPending(next: PendingState): void { pending = next; notify(); }
|
||||
export function setLastScan(id: number, existed: boolean): void { lastScan = { id, existed }; notify(); }
|
||||
export function useLastScan(): LastScan | null { useBooks(); return lastScan; }
|
||||
export const upsertBook = (book: Book) => dispatch({ type: 'upsert', book });
|
||||
|
||||
export function useBooks(): Book[] {
|
||||
@@ -48,7 +67,13 @@ export function useBooks(): Book[] {
|
||||
listeners.add(l);
|
||||
return () => { listeners.delete(l); };
|
||||
}, []);
|
||||
return shelfOrder(state);
|
||||
return visible(shelfOrder(state), pending);
|
||||
}
|
||||
|
||||
/** The queued books for "Cards to print": attention first, then newest first. */
|
||||
export function useQueue(): Book[] {
|
||||
const books = useBooks();
|
||||
return queueOrder(queueVisible(books, pending));
|
||||
}
|
||||
|
||||
export function getBook(id: number): Book | undefined { return state.byId[id]; }
|
||||
|
||||
+36
-15
@@ -1,34 +1,55 @@
|
||||
import { render } from 'preact';
|
||||
import { useState } from 'preact/hooks';
|
||||
import { startLive, useBooks } from './live.ts';
|
||||
import { queueSplit, queueTabLabel } from './bookstate.ts';
|
||||
import { flushRemovals } from './removal.ts';
|
||||
import { Editor } from './components/Editor.tsx';
|
||||
import type { EditorTarget } from './components/Editor.tsx';
|
||||
import { Settings } from './components/Settings.tsx';
|
||||
import { Toasts } from './components/Toasts.tsx';
|
||||
import { Library } from './views/Library.tsx';
|
||||
import { Scan } from './views/Scan.tsx';
|
||||
import { Queue } from './views/Queue.tsx';
|
||||
import { Catalog } from './views/Catalog.tsx';
|
||||
|
||||
type Tab = 'scan' | 'queue' | 'catalog';
|
||||
type View = 'scan' | 'library';
|
||||
/** At most one panel is open at a time. */
|
||||
type PanelState = { kind: 'settings' } | { kind: 'editor'; target: EditorTarget } | null;
|
||||
|
||||
const GearIcon = () => (
|
||||
<svg class="icon icon-lg" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor">
|
||||
<circle cx="12" cy="12" r="9" stroke-width="3" stroke-dasharray="3.53 3.53" />
|
||||
<circle cx="12" cy="12" r="6.5" stroke-width="2" />
|
||||
<circle cx="12" cy="12" r="2.5" stroke-width="2" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
function App() {
|
||||
const [tab, setTab] = useState<Tab>('scan');
|
||||
const [view, setView] = useState<View>('scan');
|
||||
const [panel, setPanel] = useState<PanelState>(null);
|
||||
const books = useBooks();
|
||||
const { ready, looking } = queueSplit(books);
|
||||
const tabs: [Tab, string][] = [['scan', 'Scan'], ['queue', queueTabLabel(ready.length, looking.length)], ['catalog', 'Catalog']];
|
||||
const close = () => setPanel(null);
|
||||
const edit = (target: EditorTarget) => setPanel({ kind: 'editor', target });
|
||||
return (
|
||||
<>
|
||||
<header>
|
||||
<h1>Booksorter</h1>
|
||||
<nav role="tablist">
|
||||
{tabs.map(([id, label]) => (
|
||||
<button role="tab" aria-selected={tab === id} class={tab === id ? 'on' : ''} onClick={() => setTab(id)}>{label}</button>
|
||||
))}
|
||||
</nav>
|
||||
<header class="top">
|
||||
<div class="top-inner">
|
||||
<h1>Booksorter</h1>
|
||||
<nav aria-label="Screens">
|
||||
<button type="button" class={'tab' + (view === 'scan' ? ' on' : '')} aria-current={view === 'scan' ? 'page' : undefined} onClick={() => setView('scan')}>Scan</button>
|
||||
<button type="button" class={'tab' + (view === 'library' ? ' on' : '')} aria-current={view === 'library' ? 'page' : undefined} onClick={() => setView('library')}>Library ({books.length})</button>
|
||||
</nav>
|
||||
<button type="button" class="btn-icon top-gear" aria-label="Settings" title="Settings" aria-haspopup="dialog"
|
||||
onClick={() => setPanel({ kind: 'settings' })}><GearIcon /></button>
|
||||
</div>
|
||||
</header>
|
||||
<main>
|
||||
{tab === 'scan' ? <Scan /> : tab === 'queue' ? <Queue /> : <Catalog />}
|
||||
{view === 'scan' ? <Scan onEdit={edit} /> : <Library onEdit={edit} />}
|
||||
</main>
|
||||
{panel?.kind === 'settings' ? <Settings onClose={close} /> : null}
|
||||
{panel?.kind === 'editor' ? <Editor target={panel.target} onClose={close} /> : null}
|
||||
<Toasts />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
startLive();
|
||||
window.addEventListener('pagehide', flushRemovals);
|
||||
render(<App />, document.getElementById('app')!);
|
||||
@@ -0,0 +1,43 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { emptyPending, isPending, pendingIds, queueVisible, removeLater, restore, visible } from './pending.ts';
|
||||
|
||||
const book = (id: number, printedAt: string | null = null) => ({ id, title: 'T' + id, printedAt } as Book);
|
||||
const ids = (bs: Book[]) => bs.map(b => b.id);
|
||||
|
||||
test('a removed book is hidden at once but remembered', () => {
|
||||
const s = removeLater(emptyPending, book(1));
|
||||
assert.ok(isPending(s, 1));
|
||||
assert.deepEqual(ids(visible([book(1), book(2)], s)), [2]);
|
||||
assert.deepEqual(ids(queueVisible([book(1), book(2)], s)), [2]);
|
||||
assert.deepEqual(pendingIds(s), [1]);
|
||||
});
|
||||
|
||||
test('a book that was printed before is only taken off the print list, never hidden from the library', () => {
|
||||
const s = removeLater(emptyPending, book(1, '2026-01-01'));
|
||||
assert.equal(s.items[1]!.kind, 'dequeue');
|
||||
assert.deepEqual(ids(visible([book(1)], s)), [1]);
|
||||
assert.deepEqual(ids(queueVisible([book(1)], s)), []);
|
||||
});
|
||||
|
||||
test('undo brings the book back and forgets it', () => {
|
||||
const s = removeLater(removeLater(emptyPending, book(1)), book(2));
|
||||
const r = restore(s, 1);
|
||||
assert.equal(r.removal?.book.id, 1);
|
||||
assert.deepEqual(pendingIds(r.state), [2]);
|
||||
assert.deepEqual(ids(visible([book(1), book(2)], r.state)), [1]);
|
||||
});
|
||||
|
||||
test('restoring something that is not pending changes nothing', () => {
|
||||
const r = restore(emptyPending, 5);
|
||||
assert.equal(r.removal, null);
|
||||
assert.equal(r.state, emptyPending);
|
||||
});
|
||||
|
||||
test('removing does not touch the earlier state', () => {
|
||||
const a = removeLater(emptyPending, book(1));
|
||||
removeLater(a, book(2));
|
||||
assert.deepEqual(pendingIds(a), [1]);
|
||||
assert.deepEqual(pendingIds(emptyPending), []);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Book } from '../shared/types.ts';
|
||||
|
||||
/**
|
||||
* Rows the person removed from "Cards to print". They are hidden at once; the real request waits so Undo can
|
||||
* bring them back. A book never printed is deleted; one already in the library is only taken off the queue.
|
||||
*/
|
||||
export type RemovalKind = 'delete' | 'dequeue';
|
||||
export interface Removal { book: Book; kind: RemovalKind }
|
||||
export interface PendingState { items: Record<number, Removal> }
|
||||
|
||||
export const emptyPending: PendingState = { items: {} };
|
||||
|
||||
export function removeKind(book: Book): RemovalKind {
|
||||
return book.printedAt ? 'dequeue' : 'delete';
|
||||
}
|
||||
|
||||
export function removeLater(s: PendingState, book: Book): PendingState {
|
||||
return { items: { ...s.items, [book.id]: { book, kind: removeKind(book) } } };
|
||||
}
|
||||
|
||||
/** Undo (or a failed request): the book is shown again. `removal` is null when nothing was pending. */
|
||||
export function restore(s: PendingState, id: number): { state: PendingState; removal: Removal | null } {
|
||||
const removal = s.items[id] ?? null;
|
||||
if (!removal) return { state: s, removal: null };
|
||||
const items = { ...s.items };
|
||||
delete items[id];
|
||||
return { state: { items }, removal };
|
||||
}
|
||||
|
||||
export function isPending(s: PendingState, id: number): boolean { return id in s.items; }
|
||||
export function pendingIds(s: PendingState): number[] { return Object.keys(s.items).map(Number); }
|
||||
|
||||
/** For the library: only books waiting to be deleted are hidden. */
|
||||
export function visible(books: Book[], s: PendingState): Book[] {
|
||||
return books.filter(b => s.items[b.id]?.kind !== 'delete');
|
||||
}
|
||||
/** For the print list: every removed row is hidden. */
|
||||
export function queueVisible(books: Book[], s: PendingState): Book[] {
|
||||
return books.filter(b => !isPending(s, b.id));
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { api } from './api.ts';
|
||||
import { dispatch, getPending, setPending, upsertBook } from './live.ts';
|
||||
import { pendingIds, removeLater, restore } from './pending.ts';
|
||||
import { dismissToast, showError, showToast } from './toast-store.ts';
|
||||
|
||||
export const UNDO_MS = 6000;
|
||||
|
||||
const timers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
const toastIds = new Map<number, number>();
|
||||
|
||||
function finish(id: number): void {
|
||||
clearTimeout(timers.get(id)); timers.delete(id);
|
||||
const t = toastIds.get(id);
|
||||
if (t !== undefined) dismissToast(t);
|
||||
toastIds.delete(id);
|
||||
}
|
||||
|
||||
export function undoRemove(id: number): void {
|
||||
finish(id);
|
||||
setPending(restore(getPending(), id).state);
|
||||
}
|
||||
|
||||
/** The real request, sent when the undo window is over. A failure puts the row back and says so. */
|
||||
async function commit(id: number): Promise<void> {
|
||||
finish(id);
|
||||
const removal = getPending().items[id];
|
||||
if (!removal) return;
|
||||
const { book, kind } = removal;
|
||||
try { // the row stays hidden while the request is out
|
||||
if (kind === 'delete') {
|
||||
await api.deleteBook(id);
|
||||
dispatch({ type: 'delete', id });
|
||||
} else {
|
||||
// The API has no "take off the queue" route; confirming a print does exactly that and keeps the book.
|
||||
await api.confirmPrint([id]);
|
||||
upsertBook({ ...book, inQueue: false });
|
||||
setPending(restore(getPending(), id).state);
|
||||
}
|
||||
} catch (e) {
|
||||
if (kind === 'delete' && (e as Error).message === 'Book not found') { dispatch({ type: 'delete', id }); return; }
|
||||
setPending(restore(getPending(), id).state);
|
||||
showError(`Could not remove "${book.title}": ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Take a book out of view now; the real request goes out after 6 seconds unless Undo is pressed. */
|
||||
export function removeWithUndo(book: Book): void {
|
||||
setPending(removeLater(getPending(), book));
|
||||
const id = book.id;
|
||||
toastIds.set(id, showToast(`Removed "${book.title}"`, {
|
||||
ms: UNDO_MS, action: { label: 'Undo', run: () => undoRemove(id) },
|
||||
}));
|
||||
timers.set(id, setTimeout(() => { void commit(id); }, UNDO_MS));
|
||||
}
|
||||
|
||||
/** On page unload every waiting removal is sent at once. */
|
||||
export function flushRemovals(): void {
|
||||
const items = getPending().items;
|
||||
for (const id of pendingIds(getPending())) {
|
||||
if (items[id]!.kind === 'delete') api.deleteBookOnUnload(id);
|
||||
else api.confirmPrintOnUnload([id]);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { emptySession, forget, touch } from './session.ts';
|
||||
|
||||
test('a book listed twice stays one row and moves to the top', () => {
|
||||
let s = touch(emptySession, 1, false);
|
||||
s = touch(s, 2, false);
|
||||
s = touch(s, 1, true);
|
||||
assert.deepEqual(s.order, [1, 2]);
|
||||
assert.equal(s.touched[1], 2);
|
||||
assert.equal(s.touched[2], 1);
|
||||
});
|
||||
|
||||
test('"earlier" is decided when the book is first listed, not by later scans', () => {
|
||||
let s = touch(emptySession, 1, false);
|
||||
s = touch(s, 1, true);
|
||||
assert.equal(s.earlier[1], undefined);
|
||||
s = touch(s, 2, true);
|
||||
s = touch(s, 2, false);
|
||||
assert.equal(s.earlier[2], true);
|
||||
});
|
||||
|
||||
test('forget removes a book everywhere', () => {
|
||||
let s = touch(touch(emptySession, 1, true), 2, false);
|
||||
s = forget(s, 1);
|
||||
assert.deepEqual(s.order, [2]);
|
||||
assert.equal(s.earlier[1], undefined);
|
||||
assert.equal(s.touched[1], undefined);
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
/** The books touched in this browsing session, one row per book id, newest activity first. */
|
||||
export interface SessionState {
|
||||
order: number[];
|
||||
/** Books that were already in the catalog when first added to this session. */
|
||||
earlier: Record<number, true>;
|
||||
/** How many times each book was added or scanned; above 1 means "seen again", so its row flashes. */
|
||||
touched: Record<number, number>;
|
||||
}
|
||||
|
||||
export const emptySession: SessionState = { order: [], earlier: {}, touched: {} };
|
||||
|
||||
/** Add a book, or move it to the top if it is listed already. Never creates a second row. */
|
||||
export function touch(s: SessionState, bookId: number, alreadyInCatalog: boolean): SessionState {
|
||||
const known = s.order.includes(bookId);
|
||||
return {
|
||||
order: [bookId, ...s.order.filter(i => i !== bookId)],
|
||||
earlier: !known && alreadyInCatalog ? { ...s.earlier, [bookId]: true } : s.earlier,
|
||||
touched: { ...s.touched, [bookId]: (s.touched[bookId] ?? 0) + 1 },
|
||||
};
|
||||
}
|
||||
|
||||
export function forget(s: SessionState, bookId: number): SessionState {
|
||||
const { [bookId]: _a, ...earlier } = s.earlier;
|
||||
const { [bookId]: _b, ...touched } = s.touched;
|
||||
return { ...s, order: s.order.filter(i => i !== bookId), earlier, touched };
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { composeNumber, findNeighbours } from './shelve.ts';
|
||||
|
||||
test('a number is composed from the neighbour class, a new cutter and the year', () => {
|
||||
assert.equal(composeNumber('GV199.42.U8 T74 2016', ['Nancy Pallister'], 'Hiking', 2025), 'GV199.42.U8 P35 2025');
|
||||
assert.equal(composeNumber('TX719.C454 2001', ['Samin Nosrat'], 'Salt fat acid heat', 2017), 'TX719.N67 2017');
|
||||
});
|
||||
|
||||
test('no year given leaves it off; an unreadable neighbour gives nothing', () => {
|
||||
assert.equal(composeNumber('TX719.C454 2001', ['Samin Nosrat'], 'x', null), 'TX719.N67');
|
||||
assert.equal(composeNumber('garbage', ['A'], 'x', 2000), null);
|
||||
});
|
||||
|
||||
test('neighbours: matches by title or author, only books with a readable number, capped', () => {
|
||||
const mk = (id: number, title: string, callNumber: string | null) =>
|
||||
({ id, title, authors: ['Ann Author'], callNumber } as Book);
|
||||
const books = [mk(1, 'Hiking', 'GV199.42 .U8'), mk(2, 'Hiking notes', null), mk(3, 'Other', 'QA76 .X')];
|
||||
assert.deepEqual(findNeighbours(books, 'hik').map(b => b.id), [1]);
|
||||
assert.deepEqual(findNeighbours(books, 'author').map(b => b.id), [1, 3]);
|
||||
assert.deepEqual(findNeighbours(books, 'author', 1).length, 1);
|
||||
assert.deepEqual(findNeighbours(books, ' '), []);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { cardLines, formatCallNumber, parseCallNumber, withYear } from '../shared/callnumber.ts';
|
||||
import { cutterFor, mainEntry } from '../shared/cutter.ts';
|
||||
|
||||
/** A call number for `authors`/`title` that shelves next to `neighbour`: its class part, a new cutter, then the year. */
|
||||
export function composeNumber(neighbour: string, authors: string[], title: string, year: number | null): string | null {
|
||||
const cn = parseCallNumber(neighbour);
|
||||
if (!cn) return null;
|
||||
const classPart = parseCallNumber(cardLines(cn)[0]);
|
||||
const cutter = parseCallNumber(`A1 ${cutterFor(mainEntry(authors, title))}`)?.cutters[0];
|
||||
if (!classPart || !cutter) return null;
|
||||
const next = { ...classPart, cutters: [...classPart.cutters] };
|
||||
if (next.cutters.length < 3) next.cutters.push(cutter);
|
||||
return formatCallNumber(year ? withYear(next, year) : next);
|
||||
}
|
||||
|
||||
/** Up to `limit` of the library's books with a readable call number whose title or author matches. */
|
||||
export function findNeighbours(books: Book[], text: string, limit = 8): Book[] {
|
||||
const needle = text.trim().toLowerCase();
|
||||
if (!needle) return [];
|
||||
const out: Book[] = [];
|
||||
for (const b of books) {
|
||||
if (!b.callNumber || !parseCallNumber(b.callNumber)) continue;
|
||||
if ([b.title, b.authors.join(' ')].some(s => s.toLowerCase().includes(needle))) out.push(b);
|
||||
if (out.length >= limit) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
+288
-108
@@ -1,119 +1,299 @@
|
||||
/* Booksorter: one visual system. Everything below uses these tokens. */
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #f7f6f3; --panel: #fff; --text: #1d1d1b; --muted: #6a6a64; --line: #dcdad3;
|
||||
--accent: #1f5fbf; --accent-text: #fff; --ok: #1d7a46; --warn: #a15c00; --bad: #b3261e; --flash: #2fa35d;
|
||||
|
||||
/* spacing: a 4px scale */
|
||||
--space-1: 4px; --space-2: 8px; --space-3: 12px; --space-4: 16px; --space-5: 20px;
|
||||
--space-6: 24px; --space-8: 32px; --space-10: 40px;
|
||||
|
||||
/* type */
|
||||
--text-sm: 13px; --text-md: 15px; --text-lg: 18px; --text-xl: 24px;
|
||||
--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
--font-mono: ui-monospace, "SF Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace;
|
||||
--leading: 1.4;
|
||||
|
||||
/* shape and size */
|
||||
--radius: 8px; --radius-lg: 12px; --radius-pill: 999px;
|
||||
--control: 36px; --icon-btn: 32px; --row-h: 56px;
|
||||
--icon: 16px; --icon-lg: 20px;
|
||||
--page-max: 1200px; --gutter: 24px; --left-col: 440px; --panel-w: 440px;
|
||||
--callno-col: 96px; --mark-col: 20px;
|
||||
|
||||
/* colour (light) */
|
||||
--bg: #f6f5f2;
|
||||
--surface: #ffffff;
|
||||
--border: #dcd9d1;
|
||||
--border-strong: #8c887e;
|
||||
--text: #1c1b19;
|
||||
--muted: #5c5a54;
|
||||
--accent: #1a56b0;
|
||||
--on-accent: #ffffff;
|
||||
--success: #16703f;
|
||||
--warning: #8a4b00;
|
||||
--danger: #b3261e;
|
||||
--on-danger: #ffffff;
|
||||
--accent-soft: #e3ecf9;
|
||||
--warning-soft: #fbefd9;
|
||||
--hover: color-mix(in srgb, var(--text) 6%, transparent);
|
||||
--scrim: rgba(0, 0, 0, .45);
|
||||
--shadow: 0 8px 24px rgba(0, 0, 0, .18);
|
||||
|
||||
/* on top of the video */
|
||||
--video-bg: #000000;
|
||||
--overlay: rgba(0, 0, 0, .72);
|
||||
--on-overlay: #ffffff;
|
||||
--on-overlay-line: rgba(255, 255, 255, .6);
|
||||
--on-overlay-hover: rgba(255, 255, 255, .18);
|
||||
--overlay-ok: #86efac;
|
||||
--overlay-warn: #fcd34d;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root { --bg: #16171a; --panel: #1f2125; --text: #ecebe6; --muted: #9a9a94; --line: #33363b;
|
||||
--accent: #6ea3f2; --accent-text: #0b1b33; --ok: #52c586; --warn: #e0a24a; --bad: #f08a82; --flash: #52c586; }
|
||||
:root {
|
||||
--bg: #141518;
|
||||
--surface: #1e2024;
|
||||
--border: #32353b;
|
||||
--border-strong: #70747c;
|
||||
--text: #ecebe6;
|
||||
--muted: #a3a29b;
|
||||
--accent: #7eb0f5;
|
||||
--on-accent: #08182e;
|
||||
--success: #58c98a;
|
||||
--warning: #e8ab55;
|
||||
--danger: #f4948c;
|
||||
--on-danger: #2a0a07;
|
||||
--accent-soft: #1f2d44;
|
||||
--warning-soft: #33291a;
|
||||
--scrim: rgba(0, 0, 0, .6);
|
||||
--shadow: 0 8px 24px rgba(0, 0, 0, .5);
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: var(--bg); color: var(--text); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
|
||||
header { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 24px; padding: 14px 20px; border-bottom: 1px solid var(--line); background: var(--panel); }
|
||||
h1 { font-size: 1.15rem; margin: 0; }
|
||||
h2 { font-size: 1.05rem; margin: 0 0 8px; }
|
||||
nav { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
nav button { border: 0; background: none; padding: 6px 12px; border-radius: 8px; color: var(--muted); }
|
||||
nav button.on { background: var(--bg); color: var(--text); font-weight: 600; }
|
||||
main { max-width: 1100px; margin: 0 auto; padding: 20px; }
|
||||
button, .button, select, input { font: inherit; color: inherit; }
|
||||
button, .button { display: inline-block; padding: 8px 14px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); cursor: pointer; text-decoration: none; }
|
||||
button:hover:not(:disabled), .button:hover { border-color: var(--muted); }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
|
||||
button.danger { color: var(--bad); }
|
||||
button.quiet { border-color: transparent; background: none; color: var(--muted); }
|
||||
body { margin: 0; background: var(--bg); color: var(--text); font: var(--text-md) / var(--leading) var(--font-sans); }
|
||||
h1, h2, h3, p { margin: 0; }
|
||||
button, input, select { font: inherit; color: inherit; }
|
||||
button { background: none; border: 0; padding: 0; cursor: pointer; text-align: inherit; }
|
||||
a { color: var(--accent); }
|
||||
ul { list-style: none; margin: 0; padding: 0; }
|
||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
input, select { padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); width: 100%; }
|
||||
input[type=checkbox] { width: auto; }
|
||||
label { display: block; font-size: .9rem; color: var(--muted); }
|
||||
label > input, label > select { margin-top: 4px; color: var(--text); }
|
||||
label small { display: block; margin-top: 4px; }
|
||||
.row { display: flex; gap: 10px; align-items: flex-end; margin: 10px 0; }
|
||||
.row.wrap { flex-wrap: wrap; align-items: center; }
|
||||
.grow { flex: 1 1 200px; } .year { width: 110px; }
|
||||
.stack { display: grid; gap: 10px; margin: 10px 0; }
|
||||
.muted { color: var(--muted); } .mono { font-family: ui-monospace, "SF Mono", Menlo, monospace; }
|
||||
.error { color: var(--bad); } .warn, .warn-text { color: var(--warn); }
|
||||
.check { display: flex; gap: 6px; align-items: center; }
|
||||
.mono { font-family: var(--font-mono); }
|
||||
.error { color: var(--danger); }
|
||||
|
||||
.scan { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 24px; }
|
||||
.scan .forms { grid-column: 1 / -1; }
|
||||
@media (max-width: 760px) { .scan { grid-template-columns: 1fr; } main { padding: 14px 12px; } }
|
||||
.video-wrap { position: relative; width: 100%; background: #0b0c0e; border-radius: 12px; overflow: hidden; border: 3px solid var(--line); transition: border-color .15s; }
|
||||
.video-wrap.flash { border-color: var(--flash); transition: none; }
|
||||
video { width: 100%; height: 100%; object-fit: cover; display: block; transform-origin: center; }
|
||||
.res { margin: -6px 0 8px; }
|
||||
.video-empty { position: absolute; inset: 0; display: grid; place-items: center; }
|
||||
button.big { font-size: 1.1rem; padding: 12px 26px; }
|
||||
.target { position: absolute; border: 2px solid rgba(255,255,255,.92); border-radius: 10px; box-shadow: 0 0 0 100vmax rgba(0,0,0,.38); pointer-events: none; transition: border-color .15s; }
|
||||
.video-wrap.flash .target { border-color: var(--flash); box-shadow: 0 0 0 100vmax rgba(0,0,0,.38), 0 0 0 3px var(--flash); }
|
||||
.hint { position: absolute; left: 50%; bottom: 5%; transform: translateX(-50%); max-width: 92%; padding: 4px 12px; border-radius: 14px; background: rgba(0,0,0,.72); color: #fff; font-size: .9rem; text-align: center; width: max-content; pointer-events: none; }
|
||||
.scanning { position: absolute; top: 10px; right: 10px; display: flex; align-items: center; gap: 7px; padding: 3px 11px 3px 9px; border-radius: 999px; background: rgba(0,0,0,.72); color: #fff; font-size: .82rem; pointer-events: none; }
|
||||
.pulse { width: 9px; height: 9px; border-radius: 50%; background: #52c586; animation: pulse 1.2s ease-in-out infinite; }
|
||||
@keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .35; transform: scale(.7); } }
|
||||
/* Buttons: one filled primary per screen; everything else is quiet (border) or text. */
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2);
|
||||
min-height: var(--control); padding: 0 var(--space-4);
|
||||
border: 1px solid var(--border-strong); border-radius: var(--radius); background: var(--surface);
|
||||
color: var(--text); text-align: center; text-decoration: none; white-space: nowrap;
|
||||
}
|
||||
.btn:hover:not(:disabled) { background: var(--hover); }
|
||||
.btn:disabled { opacity: .55; cursor: default; }
|
||||
.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
|
||||
.btn-primary:hover:not(:disabled) { background: var(--accent); filter: brightness(1.1); }
|
||||
.btn-primary:disabled { opacity: 1; background: var(--bg); border-color: var(--border); color: var(--muted); }
|
||||
.btn-text { border-color: transparent; background: none; }
|
||||
.btn-danger { color: var(--danger); }
|
||||
.btn-icon {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
min-width: var(--icon-btn); min-height: var(--icon-btn); border: 1px solid transparent; border-radius: var(--radius);
|
||||
color: var(--muted); font-size: var(--text-lg); line-height: 1;
|
||||
}
|
||||
.btn-icon:hover { background: var(--hover); border-color: var(--border-strong); color: var(--text); }
|
||||
.icon { width: var(--icon); height: var(--icon); flex: none; }
|
||||
.icon-lg { width: var(--icon-lg); height: var(--icon-lg); }
|
||||
|
||||
/* Fields */
|
||||
input, select {
|
||||
width: 100%; min-height: var(--control); padding: 0 var(--space-3);
|
||||
border: 1px solid var(--border-strong); border-radius: var(--radius); background: var(--surface); color: var(--text);
|
||||
}
|
||||
input[aria-invalid="true"] { border-color: var(--danger); }
|
||||
.field { display: grid; gap: var(--space-1); font-size: var(--text-sm); color: var(--muted); }
|
||||
.field input, .field select { font-size: var(--text-md); }
|
||||
.field-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: var(--space-3); }
|
||||
.help { margin: 0; font-size: var(--text-sm); color: var(--muted); }
|
||||
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); }
|
||||
|
||||
/* Header */
|
||||
.top { background: var(--surface); border-bottom: 1px solid var(--border); }
|
||||
.top-inner { display: flex; align-items: center; gap: var(--space-6); max-width: var(--page-max); margin: 0 auto; padding: var(--space-2) var(--gutter); }
|
||||
.top h1 { font-size: var(--text-lg); font-weight: 700; }
|
||||
.top nav { display: flex; gap: var(--space-1); }
|
||||
.tab { min-height: var(--control); padding: 0 var(--space-3); border-bottom: 2px solid transparent; color: var(--muted); }
|
||||
.tab:hover { color: var(--text); }
|
||||
.tab.on { color: var(--text); font-weight: 600; border-bottom-color: var(--accent); }
|
||||
.top-gear { margin-left: auto; min-width: var(--control); min-height: var(--control); }
|
||||
|
||||
main { max-width: var(--page-max); margin: 0 auto; padding: var(--space-6) var(--gutter); }
|
||||
|
||||
/* Scan: camera, last scan and entry on the left; cards to print on the right */
|
||||
.scan { display: grid; grid-template-columns: var(--left-col) minmax(0, 1fr); gap: var(--space-6); align-items: start; }
|
||||
.scan-left { position: sticky; top: var(--space-4); display: grid; gap: var(--space-4); min-width: 0; }
|
||||
.cards { min-width: 0; }
|
||||
|
||||
.video-frame {
|
||||
position: relative; aspect-ratio: 16 / 10; overflow: hidden;
|
||||
background: var(--video-bg); border: 3px solid var(--border); border-radius: var(--radius-lg);
|
||||
transition: border-color .15s;
|
||||
}
|
||||
.video-frame.flash { border-color: var(--success); transition: none; }
|
||||
.video-frame video { display: block; width: 100%; height: 100%; object-fit: cover; transform-origin: center; }
|
||||
.target {
|
||||
position: absolute; border: 2px solid var(--on-overlay); border-radius: var(--radius);
|
||||
box-shadow: 0 0 0 100vmax var(--scrim); pointer-events: none;
|
||||
}
|
||||
.video-frame.flash .target { border-color: var(--overlay-ok); }
|
||||
.video-bar {
|
||||
position: absolute; left: 0; right: 0; bottom: 0;
|
||||
display: flex; align-items: center; gap: var(--space-2); padding: var(--space-2) var(--space-3);
|
||||
background: var(--overlay); color: var(--on-overlay);
|
||||
}
|
||||
.video-status {
|
||||
flex: 1 1 auto; min-width: 0; font-size: var(--text-sm);
|
||||
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere;
|
||||
}
|
||||
.tone-ok { color: var(--overlay-ok); }
|
||||
.tone-warn { color: var(--overlay-warn); }
|
||||
.btn-video { border-color: var(--on-overlay-line); background: transparent; color: var(--on-overlay); }
|
||||
.btn-video:hover:not(:disabled) { background: var(--on-overlay-hover); }
|
||||
.btn-video:focus-visible { outline-color: var(--on-overlay); }
|
||||
.btn-video-icon { flex: none; padding: 0; width: var(--control); }
|
||||
.video-empty {
|
||||
position: absolute; top: 0; right: 0; bottom: 0; left: 0;
|
||||
display: grid; place-content: center; justify-items: center; gap: var(--space-3); padding: var(--space-4);
|
||||
color: var(--on-overlay); text-align: center;
|
||||
}
|
||||
.video-problem { max-width: 28ch; font-size: var(--text-sm); color: var(--overlay-warn); }
|
||||
|
||||
/* Last scan */
|
||||
.last { padding: var(--space-4); background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-lg); min-height: 120px; }
|
||||
.last-empty { display: grid; place-items: center; color: var(--muted); text-align: center; }
|
||||
.last-title { font-size: var(--text-lg); font-weight: 600; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
|
||||
.last-author { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.last-state { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-3); margin-top: var(--space-3); min-width: 0; }
|
||||
.last-mark { display: inline-flex; flex: none; }
|
||||
.last-mark .icon { width: var(--text-xl); height: var(--text-xl); }
|
||||
.last-ready { color: var(--success); }
|
||||
.last-attention { color: var(--warning); }
|
||||
.last-already { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--space-3); margin-top: var(--space-3); padding-top: var(--space-3); border-top: 1px solid var(--border); color: var(--muted); }
|
||||
|
||||
/* Entry box and its results */
|
||||
.entry { display: grid; gap: var(--space-1); }
|
||||
.entry-input { min-height: 44px; font-size: var(--text-lg); }
|
||||
.entry-help { min-height: calc(var(--text-sm) * var(--leading)); font-size: var(--text-sm); color: var(--muted); }
|
||||
.entry-help.error { color: var(--danger); }
|
||||
.entry-pop { display: grid; gap: var(--space-2); }
|
||||
.entry-none { font-size: var(--text-sm); color: var(--muted); }
|
||||
.results { max-height: 40vh; overflow: auto; background: var(--surface); border: 1px solid var(--border-strong); border-radius: var(--radius); }
|
||||
.result { display: grid; gap: 2px; min-height: var(--control); padding: var(--space-2) var(--space-3); border-top: 1px solid var(--border); cursor: pointer; }
|
||||
.result:first-child { border-top: 0; }
|
||||
.result.active { background: var(--accent-soft); }
|
||||
.result-title { font-weight: 600; overflow-wrap: anywhere; }
|
||||
.result-sub { font-size: var(--text-sm); color: var(--muted); overflow-wrap: anywhere; }
|
||||
.result-footer .result-title { color: var(--accent); }
|
||||
|
||||
/* Cards to print */
|
||||
.cards-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--space-3); margin-bottom: var(--space-3); }
|
||||
.cards-head h2, .group-head { font-size: var(--text-lg); font-weight: 600; }
|
||||
.count { margin-left: var(--space-1); font-size: var(--text-md); font-weight: 400; color: var(--muted); }
|
||||
.cards-print { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-3); }
|
||||
.cards-reason { font-size: var(--text-sm); color: var(--muted); }
|
||||
.print-anchor { position: relative; }
|
||||
.print-panel {
|
||||
position: absolute; top: calc(100% + var(--space-2)); right: 0; z-index: 20;
|
||||
display: grid; gap: var(--space-3); width: min(20rem, calc(100vw - 2 * var(--gutter))); padding: var(--space-4);
|
||||
background: var(--surface); border: 1px solid var(--border-strong); border-radius: var(--radius-lg); box-shadow: var(--shadow);
|
||||
}
|
||||
.print-panel:focus { outline: none; }
|
||||
.print-question { font-weight: 600; }
|
||||
.print-note { font-size: var(--text-sm); }
|
||||
.slots-wrap { display: grid; gap: var(--space-2); justify-items: start; }
|
||||
.slots-label { font-size: var(--text-sm); color: var(--muted); }
|
||||
.sheet { display: grid; gap: var(--space-1); width: 100%; padding: var(--space-2); background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius); }
|
||||
.slot { min-height: var(--control); text-align: center; background: var(--surface); border: 1px solid var(--border-strong); border-radius: var(--radius); }
|
||||
.slot:hover { background: var(--hover); }
|
||||
.slot.on { background: var(--accent-soft); border: 2px solid var(--accent); font-weight: 700; }
|
||||
.slot.used { border-style: dashed; color: var(--muted); }
|
||||
|
||||
/* Rows: state mark, call number, title and author, actions. Shared by both screens. */
|
||||
.rows { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-lg); overflow: hidden; }
|
||||
.row {
|
||||
display: grid; grid-template-columns: var(--mark-col) var(--callno-col) minmax(0, 1fr) auto; align-items: center;
|
||||
gap: var(--space-3); min-height: var(--row-h); padding: var(--space-2) var(--space-3);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.rows > li:last-child > .row, .rows > .row:last-child { border-bottom: 0; }
|
||||
.row-library { width: 100%; grid-template-columns: var(--mark-col) var(--callno-col) minmax(0, 1fr); color: var(--text); text-align: left; }
|
||||
.row-library:hover { background: var(--hover); }
|
||||
.row:focus-visible { outline-offset: -2px; }
|
||||
.row-attention { background: var(--warning-soft); }
|
||||
.mark { display: flex; justify-content: center; }
|
||||
.mark-ready { color: var(--success); }
|
||||
.mark-attention { color: var(--warning); }
|
||||
.row-main { display: grid; gap: 2px; min-width: 0; }
|
||||
.row-title { font-weight: 600; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
|
||||
.row-sub { font-size: var(--text-sm); color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.state-text { font-size: var(--text-sm); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
|
||||
.state-looking { color: var(--muted); }
|
||||
.state-attention { color: var(--warning); font-weight: 600; }
|
||||
.elapsed { font-variant-numeric: tabular-nums; }
|
||||
.row-actions { display: flex; align-items: center; gap: var(--space-1); }
|
||||
|
||||
/* Call number: two monospaced lines in a fixed-width column */
|
||||
.callno { display: block; width: var(--callno-col); min-width: 0; font-family: var(--font-mono); font-size: var(--text-sm); line-height: 1.3; font-variant-numeric: tabular-nums; }
|
||||
.callno-line { display: block; min-height: 1.3em; overflow-wrap: anywhere; }
|
||||
.callno-none { color: var(--muted); }
|
||||
.callno-large { width: auto; font-size: var(--text-xl); line-height: 1.2; }
|
||||
.callno-large .callno-line { min-height: 1.2em; }
|
||||
.approx { color: var(--warning); cursor: help; }
|
||||
|
||||
/* Spinner (still, not spinning, when motion is reduced) */
|
||||
.spinner { display: inline-block; flex: none; width: 14px; height: 14px; vertical-align: -2px; border: 2px solid var(--border-strong); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@keyframes rowflash { from { opacity: .35; } to { opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) { .pulse { animation: none; } .spinner { animation-duration: 3s; } .flashbar { animation-duration: .01s; } }
|
||||
.status { margin: 10px 0; padding: 8px 12px; border-radius: 8px; border-left: 4px solid var(--line); background: var(--panel); font-weight: 500; min-height: 2.6em; }
|
||||
.status.ok { border-left-color: var(--ok); color: var(--ok); }
|
||||
.status.warn { border-left-color: var(--warn); color: var(--warn); }
|
||||
.small { font-size: .85rem; }
|
||||
.summary { font-weight: 600; margin: 0 0 6px; }
|
||||
.isbn-form input { font-size: 1.1rem; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.spinner { animation: none; }
|
||||
.video-frame, .video-frame.flash { transition: none; }
|
||||
}
|
||||
|
||||
.list { list-style: none; margin: 0; padding: 0; }
|
||||
.item { display: flex; gap: 14px; justify-content: space-between; align-items: flex-start; padding: 12px 0; border-bottom: 1px solid var(--line); }
|
||||
.item.column { flex-direction: column; align-items: stretch; gap: 8px; }
|
||||
.item-btn { display: flex; gap: 14px; align-items: flex-start; width: 100%; text-align: left; border: 0; padding: 0; background: none; }
|
||||
.item-main { display: flex; flex-direction: column; min-width: 0; flex: 1; }
|
||||
.item-main .chip { align-self: flex-start; margin-top: 4px; }
|
||||
.item-side { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; }
|
||||
.title { overflow-wrap: anywhere; }
|
||||
.callno { display: inline-flex; flex-direction: column; font-family: ui-monospace, "SF Mono", Menlo, monospace; font-variant-numeric: tabular-nums; white-space: pre; min-width: 9.5em; font-size: .92rem; line-height: 1.35; }
|
||||
.item-main .callno { margin-top: 4px; }
|
||||
.approx { color: var(--warn); }
|
||||
.chip { display: inline-block; padding: 2px 10px; border-radius: 999px; font-size: .8rem; border: 1px solid var(--line); white-space: nowrap; }
|
||||
.chip.ok { color: var(--ok); border-color: var(--ok); } .chip.warn { color: var(--warn); border-color: var(--warn); }
|
||||
.chip.dup { color: var(--accent); border-color: var(--accent); } .chip.pending { color: var(--muted); }
|
||||
.error-item { color: var(--bad); }
|
||||
details { border: 1px solid var(--line); border-radius: 10px; background: var(--panel); padding: 10px 14px; margin: 8px 0; }
|
||||
summary { cursor: pointer; font-weight: 600; }
|
||||
.results .result { width: 100%; text-align: left; display: flex; flex-direction: column; border: 0; border-bottom: 1px solid var(--line); border-radius: 0; background: none; }
|
||||
.card { border: 1px solid var(--line); border-radius: 10px; background: var(--panel); padding: 14px; margin: 10px 0; }
|
||||
.editor { display: grid; gap: 10px; }
|
||||
.editor .row { margin: 0; }
|
||||
.queue section { margin-bottom: 28px; }
|
||||
fieldset.start { border: 0; padding: 0; margin: 16px 0 8px; }
|
||||
legend { color: var(--muted); font-size: .9rem; padding: 0; margin-bottom: 6px; }
|
||||
.sheet { display: inline-flex; flex-direction: column; gap: 4px; padding: 8px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); }
|
||||
.slot { width: 150px; height: 40px; padding: 0; border-radius: 4px; }
|
||||
.slot.on { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
|
||||
.slot.used { opacity: .45; }
|
||||
.confirm { border-color: var(--accent); }
|
||||
.empty { padding: var(--space-6) var(--space-4); text-align: center; color: var(--muted); border: 1px dashed var(--border-strong); border-radius: var(--radius-lg); }
|
||||
.empty-page { margin-top: var(--space-10); }
|
||||
|
||||
/* Books: one row each, one state each. */
|
||||
.book { position: relative; display: grid; gap: 8px; padding: 12px 12px 12px 14px; border-bottom: 1px solid var(--line); border-left: 4px solid var(--line); overflow: hidden; }
|
||||
.book.looking { border-left-color: var(--accent); }
|
||||
.book.ready { border-left-color: var(--ok); }
|
||||
.book.attention { border-left-color: var(--warn); background: color-mix(in srgb, var(--warn) 8%, transparent); }
|
||||
.book-head { display: flex; gap: 12px; justify-content: space-between; align-items: flex-start; }
|
||||
.book-head .item-main { flex: 1; }
|
||||
.earlier { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; }
|
||||
.book-state { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; }
|
||||
.state-label { display: inline-flex; align-items: center; gap: 7px; font-weight: 600; white-space: nowrap; }
|
||||
.book.looking .state-label, .item[data-state=looking] .state-label { color: var(--accent); }
|
||||
.book.ready .state-label, .item .state-label { color: var(--ok); }
|
||||
.book.attention .state-label { color: var(--warn); }
|
||||
.item[data-state=looking] .state-label { color: var(--accent); }
|
||||
.elapsed { font-weight: 400; font-variant-numeric: tabular-nums; color: var(--muted); }
|
||||
.icon { width: 16px; height: 16px; flex: none; }
|
||||
.spinner { width: 14px; height: 14px; border-radius: 50%; border: 2px solid color-mix(in srgb, var(--accent) 30%, transparent); border-top-color: var(--accent); animation: spin .8s linear infinite; flex: none; }
|
||||
.reason { color: var(--text); overflow-wrap: anywhere; }
|
||||
.note { overflow-wrap: anywhere; }
|
||||
.flashbar { position: absolute; inset: 0; background: var(--flash); opacity: 0; animation: rowflash 1.4s ease-out; pointer-events: none; }
|
||||
.item { align-items: center; }
|
||||
.item > .state-label { margin-left: auto; }
|
||||
.item.dim .title { color: var(--muted); }
|
||||
.callno-slot { min-width: 9.5em; }
|
||||
.queue-head { font-weight: 600; }
|
||||
/* Library */
|
||||
.library-tools { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-3); margin-bottom: var(--space-4); }
|
||||
.library-search { flex: 1 1 20rem; }
|
||||
.chip { display: inline-flex; align-items: center; min-height: var(--control); padding: 0 var(--space-3); border: 1px solid var(--border-strong); border-radius: var(--radius-pill); background: var(--surface); }
|
||||
.chip:hover { background: var(--hover); }
|
||||
.chip.on { background: var(--accent-soft); border-color: var(--accent); font-weight: 600; }
|
||||
.group { margin-bottom: var(--space-6); }
|
||||
.group-head { margin-bottom: var(--space-2); }
|
||||
|
||||
/* Panels: a side panel on wide windows, a full-width sheet on narrow ones */
|
||||
.backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 30; display: flex; justify-content: flex-end; background: var(--scrim); }
|
||||
.panel { display: flex; flex-direction: column; width: min(var(--panel-w), 100%); height: 100%; background: var(--surface); box-shadow: var(--shadow); }
|
||||
.panel:focus { outline: none; }
|
||||
.panel-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); padding: var(--space-3) var(--space-6); border-bottom: 1px solid var(--border); }
|
||||
.panel-head h2 { font-size: var(--text-lg); font-weight: 600; }
|
||||
.panel-body { display: grid; gap: var(--space-6); align-content: start; padding: var(--space-6); overflow: auto; }
|
||||
.editor { display: grid; gap: var(--space-4); }
|
||||
.fix-search { display: grid; gap: var(--space-2); padding-bottom: var(--space-4); border-bottom: 1px solid var(--border); }
|
||||
.search-row { display: flex; gap: var(--space-2); }
|
||||
.danger-zone { padding-top: var(--space-4); border-top: 1px solid var(--border); }
|
||||
.confirm { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); }
|
||||
.confirm-text { margin-right: var(--space-2); font-weight: 600; }
|
||||
.settings-block { display: grid; gap: var(--space-3); }
|
||||
.settings-block h3 { font-size: var(--text-md); font-weight: 600; }
|
||||
|
||||
/* Toasts */
|
||||
.toasts { position: fixed; left: 50%; bottom: var(--space-6); z-index: 50; display: grid; gap: var(--space-2); width: min(32rem, calc(100vw - 2 * var(--gutter))); transform: translateX(-50%); pointer-events: none; }
|
||||
.toast { pointer-events: auto; display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); min-height: var(--control); padding: var(--space-2) var(--space-3) var(--space-2) var(--space-4); background: var(--text); color: var(--bg); border-radius: var(--radius); box-shadow: var(--shadow); }
|
||||
.toast-error { background: var(--danger); color: var(--on-danger); }
|
||||
.toast-text { min-width: 0; overflow-wrap: anywhere; }
|
||||
.toast-action { flex: none; min-height: var(--icon-btn); padding: 0 var(--space-2); border-radius: var(--radius); font-weight: 700; text-decoration: underline; color: inherit; }
|
||||
.toast-action:focus-visible { outline-color: currentColor; }
|
||||
|
||||
@media (max-width: 820px) {
|
||||
.scan { grid-template-columns: minmax(0, 1fr); }
|
||||
.scan-left { position: static; }
|
||||
.panel { width: 100%; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from 'preact/hooks';
|
||||
import { dropToast, pushToast } from './toasts.ts';
|
||||
import type { Toast, ToastAction } from './toasts.ts';
|
||||
|
||||
let list: Toast[] = [];
|
||||
let nextId = 1;
|
||||
const listeners = new Set<() => void>();
|
||||
const publish = (next: Toast[]) => { list = next; listeners.forEach(l => l()); };
|
||||
|
||||
export interface ToastOptions { tone?: 'info' | 'error'; action?: ToastAction; ms?: number }
|
||||
|
||||
/** One toast component for the whole app: saving, queuing, removing and every error go through here. */
|
||||
export function showToast(text: string, opts: ToastOptions = {}): number {
|
||||
const tone = opts.tone ?? 'info';
|
||||
const id = nextId++;
|
||||
publish(pushToast(list, { id, text, tone, action: opts.action, ms: opts.ms ?? (tone === 'error' ? 8000 : 4000) }));
|
||||
return id;
|
||||
}
|
||||
export const showError = (text: string) => showToast(text, { tone: 'error' });
|
||||
export function dismissToast(id: number): void { publish(dropToast(list, id)); }
|
||||
|
||||
export function useToasts(): Toast[] {
|
||||
const [, force] = useState(0);
|
||||
useEffect(() => {
|
||||
const l = () => force(n => n + 1);
|
||||
listeners.add(l);
|
||||
return () => { listeners.delete(l); };
|
||||
}, []);
|
||||
return list;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { dropToast, MAX_TOASTS, pushToast } from './toasts.ts';
|
||||
import type { Toast } from './toasts.ts';
|
||||
|
||||
const toast = (id: number): Toast => ({ id, text: 't' + id, tone: 'info', ms: 5000 });
|
||||
|
||||
test('toasts stack in order and the oldest drop when too many pile up', () => {
|
||||
let list: Toast[] = [];
|
||||
for (let i = 1; i <= MAX_TOASTS + 2; i++) list = pushToast(list, toast(i));
|
||||
assert.equal(list.length, MAX_TOASTS);
|
||||
assert.equal(list[0]!.id, 3);
|
||||
assert.equal(list.at(-1)!.id, MAX_TOASTS + 2);
|
||||
});
|
||||
|
||||
test('a toast can be dismissed by id', () => {
|
||||
const list = dropToast([toast(1), toast(2)], 1);
|
||||
assert.deepEqual(list.map(t => t.id), [2]);
|
||||
assert.equal(dropToast(list, 9).length, 1);
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
export interface ToastAction { label: string; run: () => void }
|
||||
export interface Toast { id: number; text: string; tone: 'info' | 'error'; action?: ToastAction; ms: number }
|
||||
|
||||
export const MAX_TOASTS = 4;
|
||||
|
||||
export function pushToast(list: Toast[], toast: Toast): Toast[] {
|
||||
return [...list, toast].slice(-MAX_TOASTS);
|
||||
}
|
||||
|
||||
export function dropToast(list: Toast[], id: number): Toast[] {
|
||||
return list.filter(t => t.id !== id);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useEffect, useRef, useState } from 'preact/hooks';
|
||||
import { startScanner } from '../scanner.ts';
|
||||
import type { Scanner } from '../scanner.ts';
|
||||
import { targetBox, ZOOM } from '../frame.ts';
|
||||
import { beepAccept, beepLow, unlockAudio } from '../sound.ts';
|
||||
import { getCamera, readFlag, updateCamera, useCamera, writeFlag } from '../camera.ts';
|
||||
import { showError } from '../toast-store.ts';
|
||||
|
||||
const CAMERA_FLAG = 'cameraOn';
|
||||
/** The video box is always 16:10; the picture fills it and the middle is shown, magnified. */
|
||||
const BOX = targetBox(16 / 10);
|
||||
const BOX_STYLE = { left: `${BOX.left}%`, top: `${BOX.top}%`, width: `${BOX.width}%`, height: `${BOX.height}%` };
|
||||
|
||||
function cameraMessage(e: unknown): string {
|
||||
const name = (e as { name?: string })?.name;
|
||||
if (name === 'NotAllowedError' || name === 'SecurityError') return 'Camera access was blocked. Allow it in the browser, or type below.';
|
||||
if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'No camera was found. You can still type below.';
|
||||
if (name === 'NotReadableError') return 'The camera is busy in another program.';
|
||||
return 'The camera could not be started. You can still type below.';
|
||||
}
|
||||
|
||||
type Cam = 'off' | 'starting' | 'on';
|
||||
type Tone = 'info' | 'ok' | 'warn';
|
||||
interface Status { text: string; tone: Tone; hold: boolean }
|
||||
|
||||
const NOT_FOUND = 'No barcode found. Try again.';
|
||||
const NOT_FOUND_SAVED = 'No barcode found. Picture saved.';
|
||||
|
||||
const CameraIcon = () => (
|
||||
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true">
|
||||
<path d="M1.5 4.5h2.8l1-1.6h5.4l1 1.6h2.8v8h-13z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" />
|
||||
<circle cx="8" cy="8.5" r="2.4" fill="none" stroke="currentColor" stroke-width="1.5" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
/**
|
||||
* The live camera with its controls on a bar along the bottom edge. `onIsbn` gets every ISBN it reads.
|
||||
* `captureRef.current` is set to a function that takes one careful picture (it returns false when the camera is off).
|
||||
*/
|
||||
export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void; captureRef: { current: (() => boolean) | null } }) {
|
||||
const cam = useCamera();
|
||||
const video = useRef<HTMLVideoElement>(null);
|
||||
const scanner = useRef<Scanner | null>(null);
|
||||
const opening = useRef<AbortController | null>(null);
|
||||
const statusTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
const flashTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
const [state, setState] = useState<Cam>('off');
|
||||
const [problem, setProblem] = useState('');
|
||||
const [flash, setFlash] = useState(false);
|
||||
const [status, setStatus] = useState<Status | null>(null);
|
||||
const [capturing, setCapturing] = useState(false);
|
||||
|
||||
/** Show a message on the bar. Unless `hold`, it falls back to "Looking for a barcode…" after a few seconds. */
|
||||
const say = (text: string, tone: Tone, hold = false) => {
|
||||
clearTimeout(statusTimer.current);
|
||||
setStatus({ text, tone, hold });
|
||||
if (!hold) statusTimer.current = setTimeout(() => setStatus(null), 4000);
|
||||
};
|
||||
|
||||
const gotIsbn = (isbn: string) => {
|
||||
beepAccept();
|
||||
setFlash(true);
|
||||
clearTimeout(flashTimer.current);
|
||||
flashTimer.current = setTimeout(() => setFlash(false), 600);
|
||||
say(`Read ${isbn}`, 'ok');
|
||||
onIsbn(isbn);
|
||||
};
|
||||
const handlers = useRef({ onIsbn: gotIsbn, onOther: () => {}, onEnded: () => {} });
|
||||
handlers.current = {
|
||||
onIsbn: gotIsbn,
|
||||
onOther: () => { beepLow(); say('That barcode is not an ISBN', 'warn'); },
|
||||
onEnded: () => {
|
||||
scanner.current = null; setState('off'); setStatus(null); updateCamera({ resolution: '' });
|
||||
setProblem('The camera stopped. Turn it on again to keep scanning.');
|
||||
},
|
||||
};
|
||||
|
||||
/** `user` is true when the person turned it off: only then is the camera forgotten for the next visit. */
|
||||
function stopCamera(user: boolean) {
|
||||
opening.current?.abort(); opening.current = null;
|
||||
scanner.current?.stop(); scanner.current = null;
|
||||
setState('off'); setStatus(null); setCapturing(false); updateCamera({ resolution: '' });
|
||||
if (user) writeFlag(CAMERA_FLAG, null);
|
||||
}
|
||||
|
||||
async function startCamera() {
|
||||
if (opening.current || scanner.current || !video.current) return; // a second click does nothing
|
||||
unlockAudio(); // needs the user gesture (a no-op for an automatic start)
|
||||
const ac = new AbortController();
|
||||
opening.current = ac;
|
||||
setState('starting'); setProblem('');
|
||||
try {
|
||||
const sc = await startScanner(video.current, getCamera().deviceId || undefined, {
|
||||
onIsbn: i => handlers.current.onIsbn(i), onOther: c => handlers.current.onOther(), onEnded: () => handlers.current.onEnded(),
|
||||
}, ac.signal);
|
||||
if (!sc) return; // turned off or left the screen while the permission prompt was open
|
||||
if (ac.signal.aborted) { sc.stop(); return; }
|
||||
scanner.current = sc;
|
||||
setState('on');
|
||||
writeFlag(CAMERA_FLAG, '1');
|
||||
const v = video.current;
|
||||
if (v?.videoWidth) updateCamera({ resolution: `${v.videoWidth}×${v.videoHeight}` });
|
||||
const all = (await navigator.mediaDevices.enumerateDevices()).filter(d => d.kind === 'videoinput');
|
||||
updateCamera({ devices: all.map(d => ({ id: d.deviceId, label: d.label })) });
|
||||
} catch (e) {
|
||||
if (ac.signal.aborted) return;
|
||||
setState('off');
|
||||
const msg = cameraMessage(e);
|
||||
setProblem(msg); showError(msg);
|
||||
if ((e as { name?: string })?.name === 'NotAllowedError') writeFlag(CAMERA_FLAG, null);
|
||||
} finally {
|
||||
if (opening.current === ac) opening.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function capture() {
|
||||
const sc = scanner.current;
|
||||
if (!sc || capturing) return;
|
||||
setCapturing(true);
|
||||
say('Trying… 0 frames', 'info', true);
|
||||
try {
|
||||
const r = await sc.capture(n => say(`Trying… ${n} frames`, 'info', true));
|
||||
if (scanner.current !== sc) return;
|
||||
if (r.isbn) gotIsbn(r.isbn);
|
||||
else if (r.other) { beepLow(); say('That barcode is not an ISBN', 'warn', true); }
|
||||
else { beepLow(); say(r.saved ? NOT_FOUND_SAVED : NOT_FOUND, 'warn', true); }
|
||||
} catch {
|
||||
say(NOT_FOUND, 'warn', true);
|
||||
}
|
||||
setCapturing(false);
|
||||
}
|
||||
captureRef.current = () => {
|
||||
if (!scanner.current) return false;
|
||||
void capture();
|
||||
return true;
|
||||
};
|
||||
|
||||
// Turn the camera off when leaving the screen, and back on when it was on last time and the browser
|
||||
// already allows it (no prompt).
|
||||
useEffect(() => {
|
||||
if (readFlag(CAMERA_FLAG) === '1') {
|
||||
navigator.permissions?.query({ name: 'camera' as PermissionName })
|
||||
.then(p => { if (p.state === 'granted') void startCamera(); }, () => {});
|
||||
}
|
||||
return () => { stopCamera(false); clearTimeout(statusTimer.current); clearTimeout(flashTimer.current); captureRef.current = null; };
|
||||
}, []);
|
||||
|
||||
// Choosing another camera in the settings restarts a running one.
|
||||
const lastDevice = useRef(cam.deviceId);
|
||||
useEffect(() => {
|
||||
if (lastDevice.current === cam.deviceId) return;
|
||||
lastDevice.current = cam.deviceId;
|
||||
if (scanner.current || opening.current) { stopCamera(false); void startCamera(); }
|
||||
}, [cam.deviceId]);
|
||||
|
||||
const shown: Status = status ?? { text: 'Looking for a barcode…', tone: 'info', hold: true };
|
||||
|
||||
return (
|
||||
<div class={'video-frame' + (flash ? ' flash' : '')}>
|
||||
<video ref={video} playsInline muted aria-label="Camera view" style={{ transform: `scale(${-ZOOM}, ${ZOOM})` }}
|
||||
onLoadedMetadata={e => { const v = e.currentTarget; if (v.videoWidth) updateCamera({ resolution: `${v.videoWidth}×${v.videoHeight}` }); }} />
|
||||
{state === 'on' ? (
|
||||
<>
|
||||
<div class="target" aria-hidden="true" style={BOX_STYLE} />
|
||||
<div class="video-bar">
|
||||
<p class={'video-status tone-' + shown.tone} role="status" aria-live="polite" title={shown.text}>{shown.text}</p>
|
||||
<button type="button" class="btn btn-video" disabled={capturing} onClick={() => void capture()}
|
||||
title="Take one careful picture now (Space)">{capturing ? 'Reading…' : 'Capture'}</button>
|
||||
<button type="button" class="btn btn-video btn-video-icon" onClick={() => stopCamera(true)}
|
||||
aria-label="Turn camera off" title="Turn camera off"><CameraIcon /></button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div class="video-empty">
|
||||
<button type="button" class="btn btn-video" disabled={state === 'starting'} onClick={() => void startCamera()}>
|
||||
{state === 'starting' ? 'Starting camera…' : 'Turn on camera'}
|
||||
</button>
|
||||
{problem ? <p class="video-problem" role="alert">{problem}</p> : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useEffect, useRef, useState } from 'preact/hooks';
|
||||
import { api } from '../api.ts';
|
||||
import { printStatus } from '../bookstate.ts';
|
||||
import { useDialog } from '../dialog.ts';
|
||||
import { useQueue } from '../live.ts';
|
||||
import { removeWithUndo } from '../removal.ts';
|
||||
import { sheetCount } from '../sheets.ts';
|
||||
import { showError, showToast } from '../toast-store.ts';
|
||||
import { QueueRow } from '../components/BookRow.tsx';
|
||||
|
||||
interface MadePdf { ids: number[]; url: string }
|
||||
|
||||
export function CardsToPrint({ onFix }: { onFix: (id: number) => void }) {
|
||||
const queue = useQueue();
|
||||
const status = printStatus(queue);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [made, setMade] = useState<MadePdf | null>(null);
|
||||
const pdfUrl = useRef<string | null>(null);
|
||||
useEffect(() => () => { if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); }, []);
|
||||
|
||||
// Nothing left to print while the panel is open (for example the last card was removed): close it.
|
||||
useEffect(() => { if (open && status.ready === 0 && !made) setOpen(false); }, [open, status.ready, made]);
|
||||
|
||||
function forget() {
|
||||
if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current);
|
||||
pdfUrl.current = null; setMade(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<section class="cards" aria-labelledby="cards-heading">
|
||||
<div class="cards-head">
|
||||
<h2 id="cards-heading">Cards to print <span class="count">{queue.length}</span></h2>
|
||||
<div class="cards-print">
|
||||
{status.reason ? <span class="cards-reason" role="status">{status.reason}</span> : null}
|
||||
<div class="print-anchor">
|
||||
<button type="button" class={'btn ' + (open ? '' : 'btn-primary')} disabled={status.ready === 0 && !made}
|
||||
aria-haspopup="dialog" aria-expanded={open} onClick={() => setOpen(o => !o)}>{status.label}</button>
|
||||
{open ? <PrintPanel ready={status.ready} made={made} setMade={setMade} pdfUrl={pdfUrl} forget={forget} onClose={() => setOpen(false)} /> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{queue.length === 0 ? (
|
||||
<p class="empty">No cards waiting. Scan a book to start.</p>
|
||||
) : (
|
||||
<ul class="rows">
|
||||
{queue.map(b => <QueueRow key={b.id} book={b} onFix={() => onFix(b.id)} onRemove={() => removeWithUndo(b)} />)}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Where the first card goes, then the PDF, then "did it print?". Anchored under the print button. */
|
||||
function PrintPanel({ ready, made, setMade, pdfUrl, forget, onClose }: {
|
||||
ready: number; made: MadePdf | null; setMade: (m: MadePdf | null) => void;
|
||||
pdfUrl: { current: string | null }; forget: () => void; onClose: () => void;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useDialog(ref, onClose, false);
|
||||
const [start, setStart] = useState(1);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const sheets = sheetCount(ready, start);
|
||||
|
||||
// Keep keyboard focus inside when the panel changes from the question to the confirmation.
|
||||
const first = useRef(true);
|
||||
useEffect(() => {
|
||||
if (first.current) { first.current = false; return; }
|
||||
ref.current?.querySelector<HTMLElement>('.btn-primary')?.focus();
|
||||
}, [made === null]);
|
||||
|
||||
async function makePdf() {
|
||||
setBusy(true);
|
||||
// Open the tab inside the click so the popup blocker allows it, then point it at the PDF.
|
||||
const tab = window.open('', '_blank');
|
||||
try {
|
||||
const { blob, ids } = await api.fetchPdf(start);
|
||||
if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); // the previous PDF is no longer needed
|
||||
const url = URL.createObjectURL(new Blob([blob], { type: 'application/pdf' }));
|
||||
pdfUrl.current = url;
|
||||
if (tab) tab.location.href = url;
|
||||
setMade({ ids, url });
|
||||
} catch (e) {
|
||||
tab?.close();
|
||||
showError(`Could not make the PDF: ${(e as Error).message}`);
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
if (!made) return;
|
||||
try {
|
||||
await api.confirmPrint(made.ids);
|
||||
showToast(`Cleared ${made.ids.length} ${made.ids.length === 1 ? 'card' : 'cards'} from the list`);
|
||||
forget(); onClose();
|
||||
} catch (e) { showError(`Could not clear the cards: ${(e as Error).message}`); }
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="print-panel" role="dialog" aria-label="Print cards" ref={ref} tabIndex={-1}>
|
||||
{made ? (
|
||||
<>
|
||||
<p class="print-question">Did the cards print correctly?</p>
|
||||
<p class="help"><a href={made.url} target="_blank" rel="noopener">Open the PDF again</a> if the tab did not open.</p>
|
||||
<div class="actions">
|
||||
<button type="button" class="btn btn-primary" onClick={() => void confirm()}>Yes, clear them</button>
|
||||
<button type="button" class="btn" onClick={() => { forget(); onClose(); }}>Not yet</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div class="slots-wrap">
|
||||
<span class="slots-label" id="slots-label">First card goes in</span>
|
||||
<div class="sheet" role="radiogroup" aria-labelledby="slots-label">
|
||||
{[1, 2, 3].map(n => (
|
||||
<button type="button" role="radio" aria-checked={start === n} aria-label={`Slot ${n} of 3`}
|
||||
class={'slot' + (start === n ? ' on' : '') + (n < start ? ' used' : '')} onClick={() => setStart(n)}>{n}</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<p class="print-note">Print at actual size (100%), single-sided, from the manual feed slot</p>
|
||||
<p class="help">{ready} {ready === 1 ? 'card' : 'cards'} on {sheets} {sheets === 1 ? 'sheet' : 'sheets'}</p>
|
||||
<div class="actions">
|
||||
<button type="button" class="btn btn-primary" disabled={busy || ready === 0} onClick={() => void makePdf()}>{busy ? 'Making PDF…' : 'Make PDF'}</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { useState } from 'preact/hooks';
|
||||
import { useBooks } from '../live.ts';
|
||||
import { CallNo } from '../components/CallNo.tsx';
|
||||
import { BookEditor } from '../components/BookEditor.tsx';
|
||||
|
||||
export function Catalog() {
|
||||
const books = useBooks();
|
||||
const [q, setQ] = useState('');
|
||||
const [attentionOnly, setAttentionOnly] = useState(false);
|
||||
const [openId, setOpenId] = useState<number | null>(null);
|
||||
const needle = q.trim().toLowerCase();
|
||||
const shown = books.filter(b => {
|
||||
if (attentionOnly && b.status !== 'needs_attention') return false;
|
||||
if (!needle) return true;
|
||||
return [b.title, b.authors.join(' '), b.isbn13 ?? '', b.callNumber ?? ''].some(s => s.toLowerCase().includes(needle));
|
||||
});
|
||||
return (
|
||||
<div class="catalog">
|
||||
<div class="row wrap">
|
||||
<input class="grow" type="search" placeholder="Search title, author, ISBN or call number" aria-label="Search" value={q} onInput={e => setQ(e.currentTarget.value)} />
|
||||
<label class="check"><input type="checkbox" checked={attentionOnly} onChange={e => setAttentionOnly(e.currentTarget.checked)} /> Needs attention only</label>
|
||||
</div>
|
||||
<p class="muted">{shown.length} of {books.length} books</p>
|
||||
{shown.length === 0 ? <p class="muted">Nothing to show.</p> : null}
|
||||
<ul class="list">
|
||||
{shown.map(b => (
|
||||
<li class="item column" key={b.id}>
|
||||
<button class="item-btn" onClick={() => setOpenId(openId === b.id ? null : b.id)} aria-expanded={openId === b.id}>
|
||||
{b.status === 'pending' ? <span class="callno muted">Looking up…</span> : <CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />}
|
||||
<span class="item-main">
|
||||
<strong class="title">{b.title}</strong>
|
||||
<span class="muted">{[b.authors.join(', '), b.year].filter(Boolean).join(' · ')}</span>
|
||||
{b.status === 'needs_attention' ? <span class="chip warn">Needs attention</span> : null}
|
||||
{b.status === 'pending' ? <span class="chip pending">Looking up…</span> : null}
|
||||
</span>
|
||||
</button>
|
||||
{openId === b.id ? <BookEditor book={b} onClose={() => setOpenId(null)} /> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useRef, useState } from 'preact/hooks';
|
||||
import type { RefObject } from 'preact';
|
||||
import type { SearchResult } from '../../shared/types.ts';
|
||||
import { api } from '../api.ts';
|
||||
import { addByIsbn, addByLccn, addFromResult } from '../actions.ts';
|
||||
import { classifyEntry } from '../entry.ts';
|
||||
import { beepAccept, beepLow } from '../sound.ts';
|
||||
import { showError } from '../toast-store.ts';
|
||||
import { moveActive, ResultList } from '../components/Results.tsx';
|
||||
import { Spinner } from '../components/StateMark.tsx';
|
||||
import type { EditorTarget } from '../components/Editor.tsx';
|
||||
|
||||
/** The one entry box: an ISBN, an LCCN, or a title to search for. */
|
||||
export function Entry({ inputRef, onEdit }: { inputRef: RefObject<HTMLInputElement | null>; onEdit: (t: EditorTarget) => void }) {
|
||||
const [text, setText] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [results, setResults] = useState<SearchResult[] | null>(null);
|
||||
const [active, setActive] = useState(-1);
|
||||
const seq = useRef(0);
|
||||
const query = useRef({ title: '', author: '' });
|
||||
|
||||
const open = results !== null;
|
||||
const count = open ? results.length + 1 : 0; // the last option is always "Not listed?"
|
||||
|
||||
const close = () => { seq.current++; setResults(null); setActive(-1); setSearching(false); };
|
||||
|
||||
async function search(title: string, author: string) {
|
||||
const mine = ++seq.current;
|
||||
query.current = { title, author };
|
||||
setSearching(true); setResults(null); setActive(-1);
|
||||
try {
|
||||
const found = await api.search(title, author);
|
||||
if (mine !== seq.current) return;
|
||||
setResults(found);
|
||||
} catch (e) {
|
||||
if (mine !== seq.current) return;
|
||||
showError(`The search failed: ${(e as Error).message}`);
|
||||
}
|
||||
setSearching(false);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const action = classifyEntry(text);
|
||||
setMessage('');
|
||||
switch (action.kind) {
|
||||
case 'empty': return;
|
||||
case 'bad-digits': beepLow(); setMessage('That is not a valid ISBN'); return;
|
||||
case 'isbn': beepAccept(); setText(''); close(); await addByIsbn(action.isbn); return;
|
||||
case 'lccn': if (await addByLccn(action.lccn)) { beepAccept(); setText(''); close(); } return;
|
||||
case 'title': await search(action.title, action.author); return;
|
||||
}
|
||||
}
|
||||
|
||||
async function pick(r: SearchResult) {
|
||||
if (await addFromResult(r)) { beepAccept(); setText(''); close(); }
|
||||
}
|
||||
function manual() {
|
||||
const t = query.current;
|
||||
close(); setText('');
|
||||
onEdit({ kind: 'new', title: t.title, authors: t.author });
|
||||
}
|
||||
const choose = (i: number) => { if (!results) return; if (i < results.length) void pick(results[i]!); else manual(); };
|
||||
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (open && active >= 0) choose(active); else void submit();
|
||||
} else if (open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
|
||||
e.preventDefault(); setActive(moveActive(e.key, active, count));
|
||||
} else if (e.key === 'Escape' && (open || searching)) {
|
||||
e.preventDefault(); close();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="entry">
|
||||
<input ref={inputRef} class="entry-input" type="text" inputMode="text" autocomplete="off" spellcheck={false}
|
||||
placeholder="Type an ISBN, or a title to search" aria-label="ISBN or title"
|
||||
role="combobox" aria-expanded={open} aria-controls="entry-results" aria-autocomplete="list"
|
||||
aria-activedescendant={open && active >= 0 ? `entry-results-${active}` : undefined}
|
||||
aria-describedby="entry-help" aria-invalid={message ? 'true' : undefined}
|
||||
value={text} onKeyDown={onKeyDown}
|
||||
onInput={e => { setText(e.currentTarget.value); setMessage(''); if (open || searching) close(); }} />
|
||||
<p class={'entry-help' + (message ? ' error' : '')} id="entry-help" role={message ? 'alert' : undefined}>
|
||||
{message || (searching ? <><Spinner /> Searching…</> : 'Also takes an LCCN, such as 88005934.')}
|
||||
</p>
|
||||
{open ? (
|
||||
<div class="entry-pop">
|
||||
{results.length === 0 ? <p class="entry-none" role="status">No matches for “{query.current.title}”.</p> : null}
|
||||
<ResultList id="entry-results" label="Search results" results={results} active={active} onPick={r => void pick(r)} onHover={setActive}
|
||||
footer={{ label: 'Not listed? Enter it by hand', onPick: manual }} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useState } from 'preact/hooks';
|
||||
import { api } from '../api.ts';
|
||||
import { rowState } from '../bookstate.ts';
|
||||
import { upsertBook, useBooks, useLastScan } from '../live.ts';
|
||||
import { showError, showToast } from '../toast-store.ts';
|
||||
import { CallNo } from '../components/CallNo.tsx';
|
||||
import { CheckIcon, LABEL, Spinner, StateText, WarnIcon } from '../components/StateMark.tsx';
|
||||
|
||||
/** The book handled last, big enough to read at a glance while looking at the camera. */
|
||||
export function LastScan({ onFix }: { onFix: (id: number) => void }) {
|
||||
const last = useLastScan();
|
||||
const books = useBooks();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const book = last ? books.find(b => b.id === last.id) : undefined;
|
||||
|
||||
if (!last || !book) {
|
||||
return <section class="last last-empty" aria-label="Last scan"><p>Hold a barcode up to the camera, or type below.</p></section>;
|
||||
}
|
||||
const s = rowState(book);
|
||||
const already = last.existed && !book.inQueue;
|
||||
|
||||
async function printAnother() {
|
||||
if (!book) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
upsertBook(await api.queueBook(book.id));
|
||||
showToast(`Queued a card for "${book.title}"`);
|
||||
} catch (e) { showError(`Could not queue "${book.title}": ${(e as Error).message}`); }
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<section class="last" aria-label="Last scan" aria-live="polite">
|
||||
<h2 class="last-title">{book.title}</h2>
|
||||
{book.authors.length ? <p class="last-author">{book.authors.join(', ')}</p> : null}
|
||||
<div class="last-state">
|
||||
{s.kind === 'looking' ? <><span class="last-mark"><Spinner /></span><StateText book={book} /></> : null}
|
||||
{s.kind === 'ready' ? (
|
||||
<>
|
||||
<span class="last-mark last-ready" role="img" aria-label={LABEL.ready}><CheckIcon /></span>
|
||||
<CallNo value={book.callNumber} approximate={book.confidence === 'approximate'} source={book.source} large />
|
||||
</>
|
||||
) : null}
|
||||
{s.kind === 'attention' ? (
|
||||
<>
|
||||
<span class="last-mark last-attention" aria-hidden="true"><WarnIcon /></span>
|
||||
<StateText book={book} />
|
||||
<button type="button" class="btn" onClick={() => onFix(book.id)}>Fix</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
{already && s.kind !== 'looking' ? (
|
||||
<div class="last-already">
|
||||
<span>Already in your library</span>
|
||||
<button type="button" class="btn" disabled={busy} onClick={() => void printAnother()}>Print another card</button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useState } from 'preact/hooks';
|
||||
import { groupLibrary, needsAttention } from '../library.ts';
|
||||
import { useBooks } from '../live.ts';
|
||||
import { LibraryRow } from '../components/BookRow.tsx';
|
||||
import type { EditorTarget } from '../components/Editor.tsx';
|
||||
|
||||
export function Library({ onEdit }: { onEdit: (t: EditorTarget) => void }) {
|
||||
const books = useBooks();
|
||||
const [query, setQuery] = useState('');
|
||||
const [attentionFlag, setAttentionFlag] = useState(false);
|
||||
const attention = books.filter(needsAttention).length;
|
||||
const attentionOnly = attentionFlag && attention > 0;
|
||||
const groups = groupLibrary(books, { query, attentionOnly });
|
||||
|
||||
if (books.length === 0) return <p class="empty empty-page">Your library is empty. Books appear here once scanned.</p>;
|
||||
|
||||
return (
|
||||
<div class="library">
|
||||
<div class="library-tools">
|
||||
<input type="search" class="library-search" placeholder="Search title, author, ISBN or call number" aria-label="Search the library"
|
||||
value={query} onInput={e => setQuery(e.currentTarget.value)} />
|
||||
{attention > 0 ? (
|
||||
<button type="button" class={'chip' + (attentionOnly ? ' on' : '')} aria-pressed={attentionOnly}
|
||||
onClick={() => setAttentionFlag(!attentionOnly)}>Needs attention ({attention})</button>
|
||||
) : null}
|
||||
</div>
|
||||
{groups.length === 0 ? <p class="empty">Nothing matches. Try fewer words.</p> : null}
|
||||
{groups.map(g => (
|
||||
<section class="group" key={g.key} aria-labelledby={`group-${g.key}`}>
|
||||
<h2 class="group-head" id={`group-${g.key}`}>{g.heading} <span class="count">{g.books.length}</span></h2>
|
||||
<ul class="rows">
|
||||
{g.books.map(b => <LibraryRow key={b.id} book={b} onOpen={() => onEdit({ kind: 'edit', id: b.id })} />)}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'preact/hooks';
|
||||
import { api } from '../api.ts';
|
||||
import { dispatch, upsertBook, useBooks } from '../live.ts';
|
||||
import { sheetCount } from '../sheets.ts';
|
||||
import { pdfLabel, queueHeader, queueSplit } from '../bookstate.ts';
|
||||
import { StateLabel } from '../components/BookState.tsx';
|
||||
import { CallNo } from '../components/CallNo.tsx';
|
||||
import { BookEditor } from '../components/BookEditor.tsx';
|
||||
|
||||
export function Queue() {
|
||||
const books = useBooks();
|
||||
const { ready: queued, looking } = queueSplit(books);
|
||||
const attention = books.filter(b => b.status === 'needs_attention');
|
||||
const [start, setStart] = useState(1);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [pending, setPending] = useState<{ ids: number[]; url: string } | null>(null);
|
||||
const [editId, setEditId] = useState<number | null>(null);
|
||||
const sheets = sheetCount(queued.length, start);
|
||||
const pdfUrl = useRef<string | null>(null);
|
||||
useEffect(() => () => { if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); }, []);
|
||||
|
||||
async function makePdf() {
|
||||
setMsg(''); setBusy(true);
|
||||
// Open the tab inside the click so the popup blocker allows it, then point it at the PDF.
|
||||
const tab = window.open('', '_blank');
|
||||
try {
|
||||
const { blob, ids } = await api.fetchPdf(start);
|
||||
if (pdfUrl.current) URL.revokeObjectURL(pdfUrl.current); // the previous PDF is no longer needed
|
||||
const url = URL.createObjectURL(new Blob([blob], { type: 'application/pdf' }));
|
||||
pdfUrl.current = url;
|
||||
if (tab) tab.location.href = url;
|
||||
setPending({ ids, url });
|
||||
} catch (e) {
|
||||
tab?.close();
|
||||
setMsg((e as Error).message);
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
async function confirmPrinted() {
|
||||
if (!pending) return;
|
||||
try {
|
||||
await api.confirmPrint(pending.ids);
|
||||
URL.revokeObjectURL(pending.url); pdfUrl.current = null;
|
||||
setPending(null);
|
||||
setMsg('');
|
||||
// Live events will update the books; refresh the local copies too.
|
||||
for (const b of await api.listBooks('all')) upsertBook(b);
|
||||
} catch (e) { setMsg((e as Error).message); }
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="queue">
|
||||
<section>
|
||||
<h2>Print queue</h2>
|
||||
<p class="summary" aria-live="polite">{queueHeader(queued.length, looking.length)}</p>
|
||||
{queued.length ? <p class="muted small">{sheets} {sheets === 1 ? 'sheet' : 'sheets'} of 3 cards</p> : null}
|
||||
{queued.length === 0 && looking.length === 0 ? <p class="muted">Nothing is waiting to print.</p> : null}
|
||||
<ul class="list">
|
||||
{queued.map(b => (
|
||||
<li class="item" key={b.id}>
|
||||
<CallNo value={b.callNumber} approximate={b.confidence === 'approximate'} />
|
||||
<span class="item-main"><strong class="title">{b.title}</strong><span class="muted">{b.authors.join(', ')}</span></span>
|
||||
<StateLabel book={b} />
|
||||
</li>
|
||||
))}
|
||||
{looking.map(b => (
|
||||
<li class="item dim" key={b.id} data-state="looking">
|
||||
<span class="callno-slot" aria-hidden="true" />
|
||||
<span class="item-main">
|
||||
<strong class="title">{b.title}</strong><span class="muted">{b.authors.join(', ')}</span>
|
||||
{b.attentionReason ? <span class="muted small note">{b.attentionReason}</span> : null}
|
||||
</span>
|
||||
<StateLabel book={b} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<fieldset class="start">
|
||||
<legend>First card goes in position</legend>
|
||||
<div class="sheet" role="radiogroup" aria-label="Start position">
|
||||
{[1, 2, 3].map(n => (
|
||||
<button type="button" role="radio" aria-checked={start === n} class={'slot' + (start === n ? ' on' : '') + (n < start ? ' used' : '')}
|
||||
onClick={() => setStart(n)}>{n}</button>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<p class="muted">Print at actual size (100%), single-sided, from the manual feed slot.</p>
|
||||
<button class="primary" disabled={busy || queued.length === 0} aria-describedby={queued.length === 0 ? 'pdf-why' : undefined} onClick={makePdf}>{busy ? 'Making PDF' : pdfLabel(queued.length)}</button>
|
||||
{queued.length === 0 ? (
|
||||
<p class="muted small" id="pdf-why">{looking.length
|
||||
? 'No card is ready yet. Books still being looked up are added to the PDF once they have a call number.'
|
||||
: 'There are no cards to print. Scan a book first.'}</p>
|
||||
) : looking.length ? <p class="muted small">The PDF holds the ready cards only. The {looking.length === 1 ? 'book' : 'books'} still looking up will be in the next one.</p> : null}
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
{pending ? (
|
||||
<div class="card confirm" role="alert">
|
||||
<p><strong>Did the cards print correctly?</strong></p>
|
||||
<p class="muted"><a href={pending.url} target="_blank" rel="noopener">Open the PDF again</a> if the tab did not open.</p>
|
||||
<div class="row wrap">
|
||||
<button class="primary" onClick={confirmPrinted}>Yes, clear these from the queue</button>
|
||||
<button onClick={() => { URL.revokeObjectURL(pending.url); pdfUrl.current = null; setPending(null); }}>Not yet</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Needs attention</h2>
|
||||
{attention.length === 0 ? <p class="muted">No book needs attention.</p> : null}
|
||||
<ul class="list">
|
||||
{attention.map(b => (
|
||||
<li class="item column" key={b.id}>
|
||||
<div class="item-main">
|
||||
<strong class="title">{b.title}</strong>
|
||||
<span class="muted">{b.authors.join(', ')}</span>
|
||||
<span class="warn-text">{b.attentionReason}</span>
|
||||
</div>
|
||||
<div class="row wrap">
|
||||
<button disabled={b.manualOverride} onClick={async () => { try { upsertBook(await api.retryBook(b.id)); } catch (e) { setMsg((e as Error).message); } }}>Retry</button>
|
||||
<button onClick={() => setEditId(editId === b.id ? null : b.id)}>Edit</button>
|
||||
<button class="danger" onClick={async () => {
|
||||
if (!confirm(`Delete "${b.title}"?`)) return;
|
||||
try { await api.deleteBook(b.id); dispatch({ type: 'delete', id: b.id }); } catch (e) { setMsg((e as Error).message); }
|
||||
}}>Delete</button>
|
||||
</div>
|
||||
{editId === b.id ? <BookEditor book={b} onClose={() => setEditId(null)} /> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<Alignment />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Alignment() {
|
||||
const [x, setX] = useState('0'); const [y, setY] = useState('0');
|
||||
const [msg, setMsg] = useState('');
|
||||
const loaded = useRef(false);
|
||||
useEffect(() => {
|
||||
api.getSettings().then(s => { setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); loaded.current = true; }).catch(() => {});
|
||||
}, []);
|
||||
const save = async () => {
|
||||
setMsg('');
|
||||
try {
|
||||
const s = await api.putSettings({ offsetXmm: Number(x) || 0, offsetYmm: Number(y) || 0 });
|
||||
setX(String(s.offsetXmm)); setY(String(s.offsetYmm)); setMsg('Saved');
|
||||
} catch (e) { setMsg((e as Error).message); }
|
||||
};
|
||||
return (
|
||||
<section>
|
||||
<h2>Printer alignment</h2>
|
||||
<div class="row wrap">
|
||||
<label>Offset X (mm)<input type="number" step="0.25" min="-10" max="10" value={x} onInput={e => setX(e.currentTarget.value)} /></label>
|
||||
<label>Offset Y (mm)<input type="number" step="0.25" min="-10" max="10" value={y} onInput={e => setY(e.currentTarget.value)} /></label>
|
||||
</div>
|
||||
<div class="row wrap">
|
||||
<button onClick={save}>Save offsets</button>
|
||||
<a class="button" href="/api/calibration.pdf" target="_blank" rel="noopener">Print calibration page</a>
|
||||
</div>
|
||||
{msg ? <p class="muted" role="status">{msg}</p> : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+39
-383
@@ -1,407 +1,63 @@
|
||||
import { useEffect, useRef, useState } from 'preact/hooks';
|
||||
import type { Book, SearchResult } from '../../shared/types.ts';
|
||||
import { normalizeIsbn } from '../../shared/isbn.ts';
|
||||
import { api } from '../api.ts';
|
||||
import { getBook, upsertBook, useBooks } from '../live.ts';
|
||||
import { startScanner } from '../scanner.ts';
|
||||
import type { Scanner } from '../scanner.ts';
|
||||
import { targetBox, ZOOM } from '../frame.ts';
|
||||
import { beepAccept, beepLow, unlockAudio } from '../sound.ts';
|
||||
import { emptySession, touch } from '../session.ts';
|
||||
import type { SessionState } from '../session.ts';
|
||||
import { rowState, sessionSummary } from '../bookstate.ts';
|
||||
import { parseYear } from '../year.ts';
|
||||
import { CallNo } from '../components/CallNo.tsx';
|
||||
import { BookEditor } from '../components/BookEditor.tsx';
|
||||
import { StateLabel } from '../components/BookState.tsx';
|
||||
import { useEffect, useRef } from 'preact/hooks';
|
||||
import { addByIsbn } from '../actions.ts';
|
||||
import { dialogOpen } from '../dialog.ts';
|
||||
import { unlockAudio } from '../sound.ts';
|
||||
import type { EditorTarget } from '../components/Editor.tsx';
|
||||
import { Camera } from './Camera.tsx';
|
||||
import { CardsToPrint } from './CardsToPrint.tsx';
|
||||
import { Entry } from './Entry.tsx';
|
||||
import { LastScan } from './LastScan.tsx';
|
||||
|
||||
// Kept at module level so the list survives switching tabs.
|
||||
let session: SessionState = emptySession;
|
||||
/** ISBNs with a request in flight: one ISBN is never sent twice at the same time. */
|
||||
const inflight = new Map<string, Promise<void>>();
|
||||
|
||||
const CAMERA_FLAG = 'cameraOn';
|
||||
const readFlag = (k: string) => { try { return localStorage.getItem(k); } catch { return null; } };
|
||||
const writeFlag = (k: string, v: string | null) => {
|
||||
try { if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* ignore */ }
|
||||
};
|
||||
|
||||
function cameraMessage(e: unknown): string {
|
||||
const name = (e as { name?: string })?.name;
|
||||
if (name === 'NotAllowedError' || name === 'SecurityError') return 'Camera access was blocked. Allow it in the browser, or type the ISBN below.';
|
||||
if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'No camera was found. You can still type or scan the ISBN below.';
|
||||
if (name === 'NotReadableError') return 'The camera is busy in another program.';
|
||||
return 'The camera could not be started. You can still type the ISBN below.';
|
||||
/** Space reaches the camera unless focus is in a text field other than an empty entry box (titles contain spaces). */
|
||||
function spaceIsForCamera(active: HTMLElement | null, entry: HTMLInputElement | null): boolean {
|
||||
if (!active || active === document.body) return true;
|
||||
if (active === entry) return entry.value === '';
|
||||
return !(active.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'SUMMARY', 'A'].includes(active.tagName));
|
||||
}
|
||||
|
||||
type Cam = 'off' | 'starting' | 'on';
|
||||
type Tone = 'info' | 'ok' | 'warn';
|
||||
interface Status { text: string; tone: Tone; hold: boolean }
|
||||
export function Scan({ onEdit }: { onEdit: (t: EditorTarget) => void }) {
|
||||
const entry = useRef<HTMLInputElement>(null);
|
||||
const capture = useRef<(() => boolean) | null>(null);
|
||||
|
||||
const NOT_FOUND = 'No barcode found. Try again, or type the ISBN below.';
|
||||
const NOT_FOUND_SAVED = 'No barcode found. Saved the picture to data/captures so the reader can be tuned.';
|
||||
|
||||
export function Scan() {
|
||||
useBooks(); // re-render on live updates
|
||||
const [, bump] = useState(0);
|
||||
const refresh = () => bump(n => n + 1);
|
||||
const video = useRef<HTMLVideoElement>(null);
|
||||
const isbnBox = useRef<HTMLInputElement>(null);
|
||||
const scanner = useRef<Scanner | null>(null);
|
||||
const opening = useRef<AbortController | null>(null);
|
||||
const statusTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
const [cam, setCam] = useState<Cam>('off');
|
||||
const [camError, setCamError] = useState('');
|
||||
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
|
||||
const [deviceId, setDeviceId] = useState(() => readFlag('camera') ?? '');
|
||||
const [aspect, setAspect] = useState('16 / 9');
|
||||
const [res, setRes] = useState('');
|
||||
const [flash, setFlash] = useState(false);
|
||||
const [status, setStatus] = useState<Status | null>(null);
|
||||
const [capturing, setCapturing] = useState(false);
|
||||
const [typed, setTyped] = useState('');
|
||||
const [typedError, setTypedError] = useState('');
|
||||
const [sendError, setSendError] = useState('');
|
||||
const [editId, setEditId] = useState<number | null>(null);
|
||||
|
||||
/** Show a message under the video. Unless `hold`, it falls back to "Looking for a barcode…" after a few seconds. */
|
||||
const say = (text: string, tone: Tone, hold = false) => {
|
||||
clearTimeout(statusTimer.current);
|
||||
setStatus({ text, tone, hold });
|
||||
if (!hold) statusTimer.current = setTimeout(() => setStatus(null), 4000);
|
||||
};
|
||||
|
||||
async function submitIsbn(isbn: string) {
|
||||
setSendError('');
|
||||
let p = inflight.get(isbn);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
try {
|
||||
const r = await api.scan(isbn);
|
||||
upsertBook(r.book);
|
||||
session = touch(session, r.book.id, r.duplicate);
|
||||
} catch (e) {
|
||||
beepLow();
|
||||
setSendError(`${isbn}: ${(e as Error).message}`);
|
||||
}
|
||||
})();
|
||||
inflight.set(isbn, p);
|
||||
void p.finally(() => inflight.delete(isbn));
|
||||
}
|
||||
await p;
|
||||
refresh();
|
||||
}
|
||||
const addBook = (b: Book) => { session = touch(session, b.id, false); refresh(); };
|
||||
|
||||
const gotIsbn = (isbn: string) => {
|
||||
beepAccept();
|
||||
setFlash(true); setTimeout(() => setFlash(false), 600);
|
||||
say(`Read ${isbn}`, 'ok');
|
||||
void submitIsbn(isbn);
|
||||
};
|
||||
const handlers = useRef({ onIsbn: gotIsbn, onOther: (_c: string) => {}, onEnded: () => {} });
|
||||
handlers.current = {
|
||||
onIsbn: gotIsbn,
|
||||
onOther: () => { beepLow(); say('That barcode is not an ISBN', 'warn'); },
|
||||
onEnded: () => { scanner.current = null; setCam('off'); say('The camera stopped. Press Start camera to turn it on again.', 'warn', true); },
|
||||
};
|
||||
|
||||
/** `user` is true when the person pressed Stop: only then is the camera forgotten for the next visit. */
|
||||
function stopCamera(user: boolean) {
|
||||
opening.current?.abort(); opening.current = null;
|
||||
scanner.current?.stop(); scanner.current = null;
|
||||
setCam('off'); setStatus(null); setCapturing(false); setAspect('16 / 9'); setRes('');
|
||||
if (user) writeFlag(CAMERA_FLAG, null);
|
||||
}
|
||||
|
||||
async function startCamera() {
|
||||
if (opening.current || scanner.current || !video.current) return; // a second click does nothing
|
||||
unlockAudio(); // needs the user gesture (a no-op for an automatic start)
|
||||
const ac = new AbortController();
|
||||
opening.current = ac;
|
||||
setCam('starting'); setCamError('');
|
||||
try {
|
||||
const sc = await startScanner(video.current, deviceId || undefined, {
|
||||
onIsbn: i => handlers.current.onIsbn(i), onOther: c => handlers.current.onOther(c), onEnded: () => handlers.current.onEnded(),
|
||||
}, ac.signal);
|
||||
if (!sc) return; // stopped or left the view while the permission prompt was open
|
||||
if (ac.signal.aborted) { sc.stop(); return; }
|
||||
scanner.current = sc;
|
||||
setCam('on');
|
||||
writeFlag(CAMERA_FLAG, '1');
|
||||
const v = video.current;
|
||||
if (v?.videoWidth) { setAspect(`${v.videoWidth} / ${v.videoHeight}`); setRes(`${v.videoWidth}×${v.videoHeight}`); }
|
||||
setDevices((await navigator.mediaDevices.enumerateDevices()).filter(d => d.kind === 'videoinput'));
|
||||
} catch (e) {
|
||||
if (ac.signal.aborted) return;
|
||||
setCam('off');
|
||||
setCamError(cameraMessage(e));
|
||||
if ((e as { name?: string })?.name === 'NotAllowedError') writeFlag(CAMERA_FLAG, null);
|
||||
} finally {
|
||||
if (opening.current === ac) opening.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function capture() {
|
||||
const sc = scanner.current;
|
||||
if (!sc || capturing) return;
|
||||
setCapturing(true);
|
||||
say('Trying… 0 frames', 'info', true);
|
||||
try {
|
||||
const r = await sc.capture(n => say(`Trying… ${n} frames`, 'info', true));
|
||||
if (scanner.current !== sc) return;
|
||||
if (r.isbn) gotIsbn(r.isbn);
|
||||
else if (r.other) { beepLow(); say('That barcode is not an ISBN', 'warn', true); }
|
||||
else { beepLow(); say(r.saved ? NOT_FOUND_SAVED : NOT_FOUND, 'warn', true); }
|
||||
} catch {
|
||||
say(NOT_FOUND, 'warn', true);
|
||||
}
|
||||
setCapturing(false);
|
||||
}
|
||||
const captureRef = useRef(capture);
|
||||
captureRef.current = capture;
|
||||
|
||||
// Stop the camera when leaving the view, and start it again when it was on last time and the browser
|
||||
// already allows it (no prompt).
|
||||
// The entry box keeps keyboard focus, unless another field or an open panel has it; Space takes a picture.
|
||||
useEffect(() => {
|
||||
if (readFlag(CAMERA_FLAG) === '1') {
|
||||
navigator.permissions?.query({ name: 'camera' as PermissionName })
|
||||
.then(p => { if (p.state === 'granted') void startCamera(); }, () => {});
|
||||
}
|
||||
return () => { stopCamera(false); clearTimeout(statusTimer.current); };
|
||||
}, []);
|
||||
|
||||
// Keep the ISBN box focused unless the user is typing in another field; Space takes a picture.
|
||||
useEffect(() => {
|
||||
const focusBox = () => {
|
||||
const focusEntry = () => {
|
||||
if (dialogOpen()) return;
|
||||
const a = document.activeElement;
|
||||
if (!a || a === document.body) isbnBox.current?.focus();
|
||||
if (!a || a === document.body) entry.current?.focus();
|
||||
};
|
||||
focusBox();
|
||||
const onOut = () => setTimeout(focusBox, 0);
|
||||
focusEntry();
|
||||
const onOut = () => setTimeout(focusEntry, 0);
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
unlockAudio();
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
const a = document.activeElement as HTMLElement | null;
|
||||
if (e.code === 'Space') {
|
||||
const inOtherField = a && a !== isbnBox.current && (a.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'SUMMARY'].includes(a.tagName));
|
||||
if (!inOtherField && scanner.current) { e.preventDefault(); if (!e.repeat) void captureRef.current(); }
|
||||
return;
|
||||
}
|
||||
if ((!a || a === document.body) && /^[0-9xX-]$/.test(e.key)) isbnBox.current?.focus();
|
||||
if (e.ctrlKey || e.metaKey || e.altKey || e.code !== 'Space' || dialogOpen()) return;
|
||||
if (!spaceIsForCamera(document.activeElement as HTMLElement | null, entry.current)) return;
|
||||
if (capture.current?.()) { e.preventDefault(); }
|
||||
};
|
||||
// A click on an empty part of the page puts the cursor back in the box.
|
||||
const onClick = () => setTimeout(focusEntry, 0);
|
||||
document.addEventListener('focusout', onOut);
|
||||
document.addEventListener('keydown', onKey);
|
||||
document.addEventListener('pointerdown', unlockAudio);
|
||||
document.addEventListener('click', onClick);
|
||||
return () => {
|
||||
document.removeEventListener('focusout', onOut); document.removeEventListener('keydown', onKey);
|
||||
document.removeEventListener('focusout', onOut);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
document.removeEventListener('pointerdown', unlockAudio);
|
||||
document.removeEventListener('click', onClick);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const onSubmit = (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
const raw = typed.trim();
|
||||
if (!raw) return;
|
||||
const isbn = normalizeIsbn(raw);
|
||||
if (!isbn) { beepLow(); setTypedError('Not a valid ISBN'); return; }
|
||||
setTypedError(''); setTyped('');
|
||||
beepAccept();
|
||||
void submitIsbn(isbn);
|
||||
};
|
||||
|
||||
const rows = session.order.map(id => getBook(id)).filter((b): b is Book => !!b);
|
||||
const shown: Status = status ?? (cam === 'on'
|
||||
? { text: 'Looking for a barcode…', tone: 'info', hold: true }
|
||||
: cam === 'starting'
|
||||
? { text: 'Starting the camera. Allow access if the browser asks.', tone: 'info', hold: true }
|
||||
: { text: 'The camera is off. Start it to scan, or type the ISBN below.', tone: 'info', hold: true });
|
||||
|
||||
const [aw, ah] = aspect.split('/').map(Number);
|
||||
const t = targetBox((aw || 16) / (ah || 9));
|
||||
const boxStyle = { left: `${t.left}%`, top: `${t.top}%`, width: `${t.width}%`, height: `${t.height}%` };
|
||||
const fix = (id: number) => onEdit({ kind: 'edit', id });
|
||||
|
||||
return (
|
||||
<div class="scan">
|
||||
<section class="left">
|
||||
<div class={'video-wrap' + (flash ? ' flash' : '')} style={{ aspectRatio: aspect }}>
|
||||
<video ref={video} playsInline muted style={{ transform: `scale(${-ZOOM}, ${ZOOM})` }} onLoadedMetadata={e => {
|
||||
const v = e.currentTarget; if (v.videoWidth) { setAspect(`${v.videoWidth} / ${v.videoHeight}`); setRes(`${v.videoWidth}×${v.videoHeight}`); }
|
||||
}} />
|
||||
{cam === 'on' ? (
|
||||
<>
|
||||
<div class="target" aria-hidden="true" style={boxStyle} />
|
||||
<div class="hint" aria-hidden="true">Hold the barcode in the box, about a forearm's length from the camera</div>
|
||||
<div class="scanning" aria-hidden="true"><span class="pulse" />Scanning</div>
|
||||
</>
|
||||
) : (
|
||||
<div class="video-empty">
|
||||
<button class="primary big" disabled={cam === 'starting'} onClick={startCamera}>{cam === 'starting' ? 'Starting camera…' : 'Start camera'}</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p class={'status ' + shown.tone} role="status" aria-live="polite" data-tone={shown.tone}>{shown.text}</p>
|
||||
{cam === 'on' && res ? <p class="muted small res" aria-label="Camera resolution">{res}</p> : null}
|
||||
<div class="row wrap">
|
||||
<button class="primary" disabled={cam !== 'on' || capturing} onClick={() => void capture()}
|
||||
title="Take one picture now and read it as carefully as possible (Space)">{capturing ? 'Reading…' : 'Capture'}</button>
|
||||
{cam === 'on' ? <button onClick={() => stopCamera(true)}>Stop camera</button> : null}
|
||||
{devices.length > 1 ? (
|
||||
<select aria-label="Camera" value={deviceId} onChange={e => {
|
||||
const v = e.currentTarget.value; setDeviceId(v); writeFlag('camera', v);
|
||||
}}>
|
||||
<option value="">Default camera</option>
|
||||
{devices.map((d, i) => <option value={d.deviceId}>{d.label || `Camera ${i + 1}`}</option>)}
|
||||
</select>
|
||||
) : null}
|
||||
<span class="muted small">{cam === 'on' ? 'Scans by itself. Capture or Space takes one careful picture.' : ''}</span>
|
||||
</div>
|
||||
{camError ? <p class="warn" role="alert">{camError}</p> : null}
|
||||
<form class="isbn-form" onSubmit={onSubmit}>
|
||||
<label>ISBN
|
||||
<input ref={isbnBox} class="mono" inputMode="numeric" autocomplete="off" placeholder="Type or scan an ISBN, then Enter"
|
||||
value={typed} onInput={e => { setTyped(e.currentTarget.value); setTypedError(''); }} />
|
||||
</label>
|
||||
{typedError ? <p class="error" role="alert">{typedError}</p> : null}
|
||||
{sendError ? <p class="error" role="alert">{sendError}</p> : null}
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="right">
|
||||
<h2>This session</h2>
|
||||
{rows.length === 0 ? <p class="muted">Scanned books appear here, one row per book.</p> : <p class="summary" aria-live="polite">{sessionSummary(rows)}</p>}
|
||||
<ul class="list">
|
||||
{rows.map(b => (
|
||||
<BookRow key={b.id} book={b} earlier={!!session.earlier[b.id]} touched={session.touched[b.id] ?? 0}
|
||||
editing={editId === b.id} onEdit={() => setEditId(editId === b.id ? null : b.id)} />
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class="forms">
|
||||
<SearchForm onAdded={addBook} />
|
||||
<LccnForm onAdded={addBook} />
|
||||
<ManualForm onAdded={addBook} />
|
||||
</section>
|
||||
<div class="scan-left">
|
||||
<Camera captureRef={capture} onIsbn={isbn => { void addByIsbn(isbn); }} />
|
||||
<LastScan onFix={fix} />
|
||||
<Entry inputRef={entry} onEdit={onEdit} />
|
||||
</div>
|
||||
<CardsToPrint onFix={fix} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BookRow({ book, earlier, touched, editing, onEdit }: { book: Book; earlier: boolean; touched: number; editing: boolean; onEdit: () => void }) {
|
||||
const [queuing, setQueuing] = useState(false);
|
||||
const s = rowState(book);
|
||||
return (
|
||||
<li class={'book ' + s.kind} data-state={s.kind} data-book-id={book.id}>
|
||||
{touched > 1 ? <span class="flashbar" key={touched} aria-hidden="true" /> : null}
|
||||
<div class="book-head">
|
||||
<div class="item-main">
|
||||
<strong class="title">{book.title}</strong>
|
||||
{book.authors.length ? <span class="muted">{book.authors.join(', ')}</span> : null}
|
||||
</div>
|
||||
{earlier ? (
|
||||
<div class="earlier">
|
||||
<span class="muted small">Already in catalog</span>
|
||||
{!book.inQueue ? (
|
||||
<button disabled={queuing} onClick={async () => {
|
||||
setQueuing(true);
|
||||
try { upsertBook(await api.queueBook(book.id)); } catch { /* the row stays as it was */ }
|
||||
setQueuing(false);
|
||||
}}>Queue reprint</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div class="book-state">
|
||||
<StateLabel book={book} />
|
||||
{s.kind === 'ready' ? <CallNo value={book.callNumber} approximate={book.confidence === 'approximate'} /> : null}
|
||||
{s.kind === 'looking' && s.note ? <span class="muted small note">{s.note}</span> : null}
|
||||
{s.kind === 'attention' ? (
|
||||
<>
|
||||
<span class="reason">{s.reason}</span>
|
||||
<button class="fix" onClick={onEdit} aria-expanded={editing}>Fix</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
{editing ? <BookEditor book={book} onClose={onEdit} /> : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function SearchForm({ onAdded }: { onAdded: (b: Book) => void }) {
|
||||
const [title, setTitle] = useState(''); const [author, setAuthor] = useState('');
|
||||
const [results, setResults] = useState<SearchResult[] | null>(null);
|
||||
const [msg, setMsg] = useState(''); const [busy, setBusy] = useState(false);
|
||||
const go = async (ev: Event) => {
|
||||
ev.preventDefault(); setBusy(true); setMsg('');
|
||||
try { setResults(await api.search(title.trim(), author.trim())); } catch (e) { setMsg((e as Error).message); }
|
||||
setBusy(false);
|
||||
};
|
||||
return (
|
||||
<details>
|
||||
<summary>Search by title and author</summary>
|
||||
<form onSubmit={go} class="stack">
|
||||
<label>Title<input value={title} onInput={e => setTitle(e.currentTarget.value)} /></label>
|
||||
<label>Author<input value={author} onInput={e => setAuthor(e.currentTarget.value)} /></label>
|
||||
<button type="submit" disabled={busy || (!title.trim() && !author.trim())}>{busy ? 'Searching' : 'Search'}</button>
|
||||
</form>
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
{results && results.length === 0 ? <p class="muted">No results.</p> : null}
|
||||
<ul class="list results">
|
||||
{results?.map(r => (
|
||||
<li><button class="result" onClick={async () => {
|
||||
try { const b = await api.fromSearch(r); upsertBook(b); onAdded(b); setResults(null); } catch (e) { setMsg((e as Error).message); }
|
||||
}}>
|
||||
<strong>{r.title}</strong>
|
||||
<span class="muted">{[r.authors.join(', '), r.year, r.publisher].filter(Boolean).join(' · ')}</span>
|
||||
</button></li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function LccnForm({ onAdded }: { onAdded: (b: Book) => void }) {
|
||||
const [lccn, setLccn] = useState(''); const [msg, setMsg] = useState('');
|
||||
return (
|
||||
<details>
|
||||
<summary>Enter LCCN</summary>
|
||||
<form class="stack" onSubmit={async ev => {
|
||||
ev.preventDefault(); setMsg('');
|
||||
try { const b = await api.addLccn(lccn.trim()); upsertBook(b); onAdded(b); setLccn(''); } catch (e) { setMsg((e as Error).message); }
|
||||
}}>
|
||||
<label>LCCN<input class="mono" value={lccn} onInput={e => setLccn(e.currentTarget.value)} /></label>
|
||||
<button type="submit" disabled={!lccn.trim()}>Add</button>
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
</form>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function ManualForm({ onAdded }: { onAdded: (b: Book) => void }) {
|
||||
const [title, setTitle] = useState(''); const [authors, setAuthors] = useState('');
|
||||
const [year, setYear] = useState(''); const [cn, setCn] = useState(''); const [msg, setMsg] = useState('');
|
||||
return (
|
||||
<details>
|
||||
<summary>Enter by hand</summary>
|
||||
<form class="stack" onSubmit={async ev => {
|
||||
ev.preventDefault(); setMsg('');
|
||||
const y = parseYear(year);
|
||||
if (!y.ok) { setMsg('Enter the year as digits, for example 2018, or leave it empty.'); return; }
|
||||
try {
|
||||
const b = await api.addManual({
|
||||
title: title.trim(), authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean),
|
||||
...(y.value !== null ? { year: y.value } : {}), ...(cn.trim() ? { callNumber: cn.trim() } : {}),
|
||||
});
|
||||
upsertBook(b); onAdded(b); setTitle(''); setAuthors(''); setYear(''); setCn('');
|
||||
} catch (e) { setMsg((e as Error).message); }
|
||||
}}>
|
||||
<label>Title<input value={title} onInput={e => setTitle(e.currentTarget.value)} required /></label>
|
||||
<label>Authors (separate with ;)<input value={authors} onInput={e => setAuthors(e.currentTarget.value)} /></label>
|
||||
<label>Year<input inputMode="numeric" value={year} onInput={e => setYear(e.currentTarget.value)} /></label>
|
||||
<label>Call number (optional)<input class="mono" value={cn} onInput={e => setCn(e.currentTarget.value)} /></label>
|
||||
<button type="submit" disabled={!title.trim()}>Add</button>
|
||||
{msg ? <p class="error" role="alert">{msg}</p> : null}
|
||||
</form>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user