Show author names in natural order everywhere

Names read from MARC personal-name fields are stored as "Steve Allen",
and names already stored as "Allen, Steve" are shown and printed in
natural order. Search matches both forms.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 14:09:09 -07:00
1 parent 7ae1bcef0a
commit 60fa4ef6f7
17 files changed
+183 -15

No files matched your search

+10
View File
@@ -275,6 +275,16 @@ test('print order and the book list break identical sort keys by author surname,
assert.deepEqual(pdfCalls[0]!.cards.map((c) => c.title), ['Day hikes', 'Sierra South', 'Alpine', 'Zebra trails']);
});
test('cards print stored author names in natural order', async () => {
const { req, db, pdfCalls } = setup();
db.insertPending({
title: 'Canyoneering 2', authors: ['Allen, Steve', 'Wilderness Press, Inc.'], callNumber: 'GV199.42 2020', sortKey: 'GV 0199.42 2020',
confidence: 'approximate', source: 'ol-edition', status: 'resolved', manualOverride: false, inQueue: true,
});
assert.equal((await req('GET', '/api/print.pdf')).status, 200);
assert.deepEqual(pdfCalls[0]!.cards[0]!.authors, ['Steve Allen', 'Wilderness Press, Inc.']);
});
test('a search result\'s LCCN (work-level) is not saved onto the book', async () => {
const { req } = setup();
const f = await (await req('POST', '/api/books/from-search', { result: { title: 'Hit', authors: ['X'], lccn: '96067014', lcc: [] } })).json() as any;
+2 -1
View File
@@ -3,6 +3,7 @@ import { compareShelf } from '../shared/shelf.ts';
import { join } from 'node:path';
import { Hono } from 'hono';
import type { Context } from 'hono';
import { displayAuthors } from '../shared/names.ts';
import type { Book, CardData, Hierarchy, SearchResult, Settings } from '../shared/types.ts';
import { normalizeIsbn } from '../shared/isbn.ts';
import { formatCallNumber, parseCallNumber, sortKeyOfRaw } from '../shared/callnumber.ts';
@@ -273,7 +274,7 @@ export function createApp(deps: AppDeps): Hono {
const cards: CardData[] = books.map((b) => {
return {
callNumber: b.callNumber!, hierarchy: hierarchyOf(b.callNumber, b.hierarchyTail),
title: b.subtitle ? `${b.title}: ${b.subtitle}` : b.title, authors: b.authors, publisher: b.publisher, year: b.year,
title: b.subtitle ? `${b.title}: ${b.subtitle}` : b.title, authors: displayAuthors(b.authors), publisher: b.publisher, year: b.year,
subjects: b.subjects, isbn13: b.isbn13, approximate: b.confidence === 'approximate',
};
});
+8
View File
@@ -105,3 +105,11 @@ test('a database made before the hierarchy tail gets the column; old books read
rmSync(dir, { recursive: true, force: true });
}
});
test('search finds an inverted stored name by its natural form', () => {
const db = openDb(':memory:');
db.insertPending({ title: 'Canyoneering 2', authors: ['Allen, Steve'] });
assert.equal(db.listBooks({ q: 'steve allen' }).length, 1);
assert.equal(db.listBooks({ q: 'allen, steve' }).length, 1);
assert.equal(db.listBooks({ q: 'nobody' }).length, 0);
});
+8 -4
View File
@@ -1,5 +1,6 @@
import { DatabaseSync } from 'node:sqlite';
import { compareShelf } from '../shared/shelf.ts';
import { displayAuthors } from '../shared/names.ts';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import type { Book, Confidence, Settings, Source, Status } from '../shared/types.ts';
@@ -139,13 +140,16 @@ export function openDb(path: string): Db {
if (filter === 'attention') where.push("status = 'needs_attention'");
const needle = q?.trim().toLowerCase();
if (needle) {
where.push(`(instr(lower(title), ?) > 0 OR instr(lower(authors), ?) > 0 OR
instr(lower(coalesce(isbn13, '')), ?) > 0 OR instr(lower(coalesce(call_number, '')), ?) > 0)`);
params.push(needle, needle, needle, needle);
// Authors are matched as stored and as displayed ("Allen, Steve" is found by "steve allen"), so this is done below.
}
const sql = `SELECT * FROM books ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
ORDER BY sort_key IS NULL, sort_key, id`;
return (db.prepare(sql).all(...params) as Row[]).map(toBook).sort(compareShelf);
const books = (db.prepare(sql).all(...params) as Row[]).map(toBook);
const found = needle
? books.filter((b) => [b.title, b.authors.join(' '), displayAuthors(b.authors).join(' '), b.isbn13 ?? '', b.callNumber ?? '']
.some((s) => s.toLowerCase().includes(needle)))
: books;
return found.sort(compareShelf);
},
updateBook(id, patch) {
const keys = Object.keys(patch).filter((k) => k in COLUMNS && (patch as Row)[k] !== undefined) as (keyof BookPatch)[];
+8
View File
@@ -26,3 +26,11 @@ test('recordMatches needs title and an author surname', () => {
assert.ok(!recordMatches(r, 'Something Else', 'Brooks'));
assert.ok(recordMatches(rec('Dune', ['Smith, Bob', 'Herbert, Frank']), 'Dune', 'Frank Herbert'));
});
test('recordMatches gives the same answer for inverted and natural author names', () => {
const r = rec('Canyoneering 2', ['Allen, Steve']);
for (const a of ['Allen, Steve', 'Steve Allen']) assert.ok(recordMatches(r, 'Canyoneering 2', a), a);
const n = rec('Canyoneering 2', ['Steve Allen']);
for (const a of ['Allen, Steve', 'Steve Allen']) assert.ok(recordMatches(n, 'Canyoneering 2', a), a);
for (const a of ['Mitchell, Joe', 'Joe Mitchell']) assert.ok(!recordMatches(r, 'Canyoneering 2', a), a);
});
+15
View File
@@ -110,3 +110,18 @@ test('subject tail: other thesauri are ignored, and no heading gives an empty ta
assert.deepEqual(fast.subjectTail, []);
assert.deepEqual(rec(f('245', '0', [['a', 'Title']])).subjectTail, []);
});
test('names: personal names with indicator 1 are put in natural order, others are kept as catalogued', () => {
const g = (tag: string, ind1: string, a: string) =>
`<datafield tag="${tag}" ind1="${ind1}" ind2=" "><subfield code="a">${a}</subfield></datafield>`;
const p = rec(g('100', '1', 'Allen, Steve,') + g('700', '1', 'Mitchell, Joe.'));
assert.deepEqual(p.meta.authors, ['Steve Allen']);
assert.deepEqual(p.names, ['Allen, Steve', 'Mitchell, Joe']);
const k = rec(g('100', '1', 'King, Martin Luther, Jr., 1929-1968.'));
assert.deepEqual(k.meta.authors, ['Martin Luther King Jr.']);
assert.deepEqual(rec(g('100', '0', 'Aristotle.')).meta.authors, ['Aristotle']);
assert.deepEqual(rec(g('100', '3', 'Smith, Family')).meta.authors, ['Smith, Family']);
assert.deepEqual(rec(g('110', '2', 'Sierra Club, Angeles Chapter.')).meta.authors, []);
assert.deepEqual(rec(g('700', '1', 'Secor, R. J.,') ).meta.authors, ['R. J. Secor']);
assert.deepEqual(rec(g('700', '3', 'Sierra Club, Angeles Chapter')).meta.authors, ['Sierra Club, Angeles Chapter']);
});
+9 -3
View File
@@ -50,11 +50,12 @@ function text(v: unknown): string {
return '';
}
interface Field { tag: string; ind2: string; subs: { code: string; value: string }[] }
interface Field { tag: string; ind1: string; ind2: string; subs: { code: string; value: string }[] }
function fieldsOf(rec: Node): Field[] {
return asArray(rec['datafield'] as Node | Node[] | undefined).filter(isNode).map((d) => ({
tag: String(d['@_tag'] ?? ''),
ind1: String(d['@_ind1'] ?? ' '),
ind2: String(d['@_ind2'] ?? ' '),
subs: asArray(d['subfield'] as unknown).map((s) => ({
code: isNode(s) ? String(s['@_code'] ?? '') : '',
@@ -80,7 +81,7 @@ export function cleanName(raw: string): string {
return s.trim();
}
/** "Herbert, Frank" -> "Frank Herbert"; "King, Martin Luther, Jr." -> "Martin Luther King Jr."; names without a comma are left alone. */
/** "Herbert, Frank" -> "Frank Herbert"; "King, Martin Luther, Jr." -> "Martin Luther King Jr."; names without a comma are left alone. Call it only for MARC personal names with a surname (first indicator 1). */
export function displayName(name: string): string {
const parts = name.split(',').map((p) => p.trim()).filter(Boolean);
if (parts.length < 2) return name.trim();
@@ -134,7 +135,12 @@ export function parseMarcRecord(rec: Node): MarcFields {
const f100 = all('100');
const names = uniq([...f100, ...all('700')].map((f) => cleanName(sub(f, 'a'))).filter(Boolean));
// The 100 is the author; 700s (editors, illustrators, co-authors) only stand in when there is none.
const authors = uniq((f100.length ? f100 : all('700')).map((f) => cleanName(sub(f, 'a'))).filter(Boolean).map(displayName));
// Only personal names with a surname (first indicator 1) are inverted; corporate (110/710) and forename-only or family
// names (indicator 0 or 3) are kept as catalogued.
const authors = uniq((f100.length ? f100 : all('700')).map((f) => {
const n = cleanName(sub(f, 'a'));
return f.ind1 === '1' ? displayName(n) : n;
}).filter(Boolean));
const pub = all('260')[0] ?? all('264').find((f) => f.ind2 === '1') ?? all('264')[0];
const publisher = pub ? trimPunct(sub(pub, 'b')) : '';
+14
View File
@@ -24,3 +24,17 @@ test('mainEntry: both name forms and suffixes give the surname', () => {
assert.equal(mainEntry(['King, Martin Luther, Jr.'], 'x'), 'King');
assert.equal(mainEntry(['Martin Luther King, Jr.'], 'x'), 'King');
});
test('cutter and main entry agree for inverted and natural names', () => {
const pairs: [string, string][] = [
['Allen, Steve', 'Steve Allen'], ['Kast-Myers, Marlise', 'Marlise Kast-Myers'], ['Secor, R. J.', 'R. J. Secor'],
['King, Martin Luther, Jr.', 'Martin Luther King Jr.'], ['Morey, Kathy', 'Kathy Morey'],
];
for (const [inv, nat] of pairs) {
assert.equal(mainEntry([inv], 'x'), mainEntry([nat], 'x'), inv);
assert.equal(cutterFor(mainEntry([inv], 'x')), cutterFor(mainEntry([nat], 'x')), inv);
}
assert.equal(mainEntry(['Allen, Steve'], 'x'), 'Allen');
assert.equal(mainEntry(['Steve Allen'], 'x'), 'Allen');
assert.equal(cutterFor(mainEntry(['Allen, Steve'], 'x')), cutterFor('Allen'));
});
+38
View File
@@ -0,0 +1,38 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { displayAuthor } from './names.ts';
test('inverted personal names become natural order', () => {
for (const [from, to] of [
['Allen, Steve', 'Steve Allen'],
['Morey, Kathy', 'Kathy Morey'],
['Kast-Myers, Marlise', 'Marlise Kast-Myers'],
['King, Martin Luther, Jr.', 'Martin Luther King Jr.'],
['Secor, R. J.', 'R. J. Secor'],
['Secor, R.J.', 'R.J. Secor'],
['Herbert, Frank', 'Frank Herbert'],
['Van Gogh, Vincent', 'Vincent Van Gogh'],
["O'Brien, Tim", "Tim O'Brien"],
['Allen,Steve', 'Steve Allen'],
] as const) assert.equal(displayAuthor(from), to);
});
test('natural names are unchanged', () => {
for (const n of ['Steve Allen', 'Joe Mitchell', 'Martin Luther King Jr.', 'R. J. Secor', 'Madonna', '', 'Frank Herbert, Jr.']) {
assert.equal(displayAuthor(n), n);
}
});
test('corporate and other non-personal names are left alone', () => {
for (const n of [
'Sierra Club, Angeles Chapter', 'University of Utah. Department of Geology', 'University of Utah, Department of Geology',
'Wilderness Press, Inc.', 'Smith, John and Jane', 'Smith, Jones, Brown, Green', 'Utah, 2020', 'Geological Survey, Utah',
'Sierra Club,', 'a, b',
]) assert.equal(displayAuthor(n), n);
});
test('is idempotent', () => {
for (const n of ['Allen, Steve', 'King, Martin Luther, Jr.', 'Wilderness Press, Inc.']) {
assert.equal(displayAuthor(displayAuthor(n)), displayAuthor(n));
}
});
+51
View File
@@ -0,0 +1,51 @@
/**
* Author names are stored in two shapes: inverted ("Allen, Steve", from Library of Congress MARC records saved by
* older versions) and natural ("Steve Allen", from Open Library, or typed by hand). displayAuthor() turns any stored
* string into natural order for display and printing.
*
* The rule is deliberately conservative: when in doubt the string is returned untouched. A name is inverted only if
* - it splits on commas into "Surname, Forenames" or "Surname, Forenames, Suffix" (Jr., Sr., II, III, IV);
* - the surname is one to three words, with no full stop followed by more text ("University of Utah. Dept");
* - the forenames are one to four name-like words: capitalised words, initials ("R."), hyphenated or apostrophe
* names, or lower-case particles ("de", "van"), and no corporate word (Inc., Club, Press, Chapter, ...).
* Surname and forenames are then swapped and the suffix follows the surname without a comma.
*/
const SUFFIX = /^(?:jr|sr|ii|iii|iv)\.?$/i;
const PARTICLES = new Set(['de', 'del', 'della', 'der', 'den', 'di', 'da', 'du', 'la', 'le', 'van', 'von', 'bin', 'ibn', 'al', 'el', 'ter', 'ten', 'st.']);
const CORPORATE = new Set([
'inc', 'inc.', 'llc', 'ltd', 'ltd.', 'co', 'co.', 'corp', 'corp.', 'company', 'limited', 'club', 'press', 'university', 'college',
'department', 'dept', 'dept.', 'society', 'association', 'committee', 'council', 'institute', 'chapter', 'survey', 'service',
'services', 'bureau', 'office', 'agency', 'commission', 'foundation', 'museum', 'library', 'publishers', 'publishing',
'editors', 'staff', 'board', 'division', 'group', 'team', 'network', 'federation', 'union', 'school', 'center', 'centre',
'authority', 'administration', 'government', 'ministry', 'conference', 'consortium', 'alliance', 'guild', 'books',
]);
const NAME_WORD = /^(?:\p{Lu}[\p{L}'’-]*\.?|\p{Lu}\.(?:\p{Lu}\.)*)$/u;
function plausibleForenames(s: string): boolean {
const words = s.split(/\s+/).filter(Boolean);
if (words.length < 1 || words.length > 4) return false;
for (const w of words) {
const lw = w.toLowerCase();
if (CORPORATE.has(lw)) return false;
if (PARTICLES.has(lw) || NAME_WORD.test(w)) continue;
return false;
}
return true;
}
export function displayAuthor(stored: string): string {
const s = stored.trim().replace(/\s+/g, ' ');
if (!s.includes(',')) return s;
const parts = s.split(',').map((p) => p.trim());
if (parts.length < 2 || parts.length > 3 || parts.some((p) => !p)) return s;
const [surname, forenames, suffix] = parts as [string, string, string | undefined];
if (suffix !== undefined && !SUFFIX.test(suffix)) return s;
const sw = surname.split(/\s+/);
if (sw.length > 3 || /\.\s+\S/.test(surname) || sw.some((w) => CORPORATE.has(w.toLowerCase()))) return s;
if (SUFFIX.test(forenames) || !plausibleForenames(forenames)) return s;
return [forenames, surname, suffix].filter(Boolean).join(' ');
}
/** displayAuthor over a list. */
export const displayAuthors = (authors: string[]): string[] => authors.map(displayAuthor);
+7
View File
@@ -19,3 +19,10 @@ test('identical sort keys: first author surname, then title, then id', () => {
// Input order does not matter.
assert.deepEqual([...books].reverse().sort(compareShelf).map((x) => x.id), [4, 2, 3, 5, 1, 6, 7]);
});
test('shelf tie-break treats inverted and natural names alike', () => {
const key = 'GV 0199.42 2020';
const books = [b(1, 'Same', ['Steve Allen'], key), b(2, 'Same', ['Allen, Steve'], key), b(3, 'Alpha', ['Bob Baker'], key), b(4, 'Alpha', ['Baker, Bob'], key)];
assert.deepEqual([...books].sort(compareShelf).map((x) => x.id), [1, 2, 3, 4]);
assert.deepEqual([...books].reverse().sort(compareShelf).map((x) => x.id), [1, 2, 3, 4]);
});
+2 -1
View File
@@ -1,10 +1,11 @@
import { displayAuthors } from '../../shared/names.ts';
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(' · ');
const byline = [displayAuthors(book.authors).join(', '), showYear ? book.year : null].filter(Boolean).join(' · ');
return (
<span class="row-main">
<span class="row-title">{book.title}</span>
+3 -2
View File
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'preact/hooks';
import type { Book, SearchResult } from '../../shared/types.ts';
import { displayAuthors } from '../../shared/names.ts';
import { api } from '../api.ts';
import type { BookPatch } from '../api.ts';
import { getBook, setLastScan, upsertBook, dispatch, useBooks } from '../live.ts';
@@ -39,7 +40,7 @@ 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 [authors, setAuthors] = useState(book ? displayAuthors(book.authors).join('; ') : initial?.authors ?? '');
const [publisher, setPublisher] = useState(book?.publisher ?? '');
const [year, setYear] = useState(book?.year?.toString() ?? '');
const [callNumber, setCallNumber] = useState(book?.callNumber ?? '');
@@ -98,7 +99,7 @@ function EditorForm({ book, fixing, initial, onClose }: {
function pick(r: SearchResult) {
setPicked(r);
setTitle(r.title);
setAuthors(r.authors.join('; '));
setAuthors(displayAuthors(r.authors).join('; '));
setPublisher(r.publisher ?? '');
setYear(r.year ? String(r.year) : '');
if (r.lcc[0]) setCallNumber(r.lcc[0]);
+2 -1
View File
@@ -1,3 +1,4 @@
import { displayAuthors } from '../../shared/names.ts';
import type { SearchResult } from '../../shared/types.ts';
/** Next highlighted index for an arrow key; -1 means nothing is highlighted. */
@@ -22,7 +23,7 @@ export function ResultList({ id, label, results, active, onPick, onHover, footer
<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>
<span class="result-sub">{[displayAuthors(r.authors).join(', '), r.year, r.publisher].filter(Boolean).join(' · ')}</span>
</li>
))}
{footer ? (
+2 -1
View File
@@ -1,6 +1,7 @@
import type { Book } from '../shared/types.ts';
import { parseCallNumber } from '../shared/callnumber.ts';
import { classNames } from '../shared/lcc-outline.ts';
import { displayAuthors } from '../shared/names.ts';
import { compareShelf } from './store.ts';
export interface LibraryGroup { key: string; heading: string; books: Book[] }
@@ -17,7 +18,7 @@ export function mainClass(book: Book): string | 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));
return [book.title, book.authors.join(' '), displayAuthors(book.authors).join(' '), book.isbn13 ?? '', book.callNumber ?? ''].some(s => s.toLowerCase().includes(needle));
}
export const needsAttention = (book: Book) => book.status === 'needs_attention';
+2 -1
View File
@@ -1,5 +1,6 @@
import type { Book } from '../shared/types.ts';
import { cardLines, formatCallNumber, parseCallNumber, withYear } from '../shared/callnumber.ts';
import { displayAuthors } from '../shared/names.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. */
@@ -21,7 +22,7 @@ export function findNeighbours(books: Book[], text: string, limit = 8): Book[] {
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 ([b.title, b.authors.join(' '), displayAuthors(b.authors).join(' ')].some(s => s.toLowerCase().includes(needle))) out.push(b);
if (out.length >= limit) break;
}
return out;
+2 -1
View File
@@ -1,3 +1,4 @@
import { displayAuthors } from '../../shared/names.ts';
import { useState } from 'preact/hooks';
import { api } from '../api.ts';
import { rowState } from '../bookstate.ts';
@@ -32,7 +33,7 @@ export function LastScan({ onFix }: { onFix: (id: number) => void }) {
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}
{book.authors.length ? <p class="last-author">{displayAuthors(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' ? (