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
@@ -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>;
|
||||
}
|
||||
Reference in new issue
Block a user