import { useEffect, useState } from 'preact/hooks'; 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. */ const pendingSince = new Map(); function trackPending(action: BookAction): void { const note = (b: Book, fromServerTime: boolean) => { if (b.status !== 'pending') { pendingSince.delete(b.id); return; } if (pendingSince.has(b.id)) return; const created = Date.parse(b.createdAt); pendingSince.set(b.id, fromServerTime && Number.isFinite(created) ? Math.min(created, Date.now()) : Date.now()); }; const now = Date.now(); if (action.type === 'upsert') { receivedAt.set(action.book.id, now); note(action.book, false); } else if (action.type === 'replace') { pendingSince.clear(); receivedAt.clear(); action.books.forEach(b => { receivedAt.set(b.id, now); note(b, true); }); } else { pendingSince.delete(action.id); receivedAt.delete(action.id); } } /** When the page last received each book, so a retry's remaining wait can be counted down locally. */ const receivedAt = new Map(); export function retryReceivedAt(book: Book): number { return receivedAt.get(book.id) ?? Date.now(); } export function lookupStartedAt(book: Book): number { return pendingSince.get(book.id) ?? Date.now(); } /** Re-renders once a second while `active`, and returns the current time. */ export function useNow(active: boolean): number { const [now, setNow] = useState(Date.now()); useEffect(() => { if (!active) return; setNow(Date.now()); const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, [active]); return now; } function notify(): void { listeners.forEach(l => l()); } export function dispatch(action: BookAction): void { trackPending(action); state = reduce(state, action); 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[] { const [, force] = useState(0); useEffect(() => { const l = () => force(n => n + 1); listeners.add(l); return () => { listeners.delete(l); }; }, []); 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]; } async function refetch(): Promise { try { dispatch({ type: 'replace', books: await api.listBooks('all') }); } catch { /* retried on next open */ } } /** One EventSource for the whole app. Every (re)connect refetches the full list. */ export function startLive(): void { const es = new EventSource('/api/events'); es.onopen = () => { void refetch(); }; es.addEventListener('book', e => { try { upsertBook(JSON.parse((e as MessageEvent).data) as Book); } catch { /* ignore */ } }); es.addEventListener('deleted', e => { try { dispatch({ type: 'delete', id: (JSON.parse((e as MessageEvent).data) as { id: number }).id }); } catch { /* ignore */ } }); }