import { normalizeIsbn } from '../shared/isbn.ts'; export const REPEAT_MS = 5000; /** Remembers when each code was last reported, so a barcode held in view is announced once per 5 seconds. */ export interface ReadState { emittedAt: Record; rejectedAt: Record; } export function newReadState(): ReadState { return { emittedAt: {}, rejectedAt: {} }; } /** * Judge one decoded barcode. A valid ISBN-13 (check digit, 978 or 979 prefix) is accepted at once, with no * second confirming read: the EAN checksum already makes a false read very unlikely. Anything else * (a UPC, a price code, a bad check digit) is rejected. Neither is repeated within REPEAT_MS. */ export function acceptRead( state: ReadState, code: string, now: number, ): { state: ReadState; emit: string | null; reject: boolean } { const isbn = /^\d{13}$/.test(code) ? normalizeIsbn(code) : null; if (isbn === null) { const last = state.rejectedAt[code]; if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null, reject: false }; return { state: { ...state, rejectedAt: { ...state.rejectedAt, [code]: now } }, emit: null, reject: true }; } const last = state.emittedAt[isbn]; if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null, reject: false }; return { state: { ...state, emittedAt: { ...state.emittedAt, [isbn]: now } }, emit: isbn, reject: false }; } /** Record that an ISBN was just reported by some other path (the Capture button), so the loop stays quiet. */ export function markEmitted(state: ReadState, isbn: string, now: number): ReadState { return { ...state, emittedAt: { ...state.emittedAt, [isbn]: now } }; }