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
@@ -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