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) }; }