Files
bookhoard/web/src/bookPicker.ts
T
John O'Keefe aaf57a66a2 fix(ui): cookie-authed users' writes silently stranded behind bearer gates
THE CLASS: the /api JWT middleware's TokenLookup is
"cookie:token,header:Authorization:Bearer" — the token cookie always
rides same-origin fetches, so a signed-in user never needs the
localStorage bearer. But a dozen call sites gated their fetch on
`localStorage.getItem("token")` and early-returned when absent. The
global 401 interceptor CLEARS that localStorage entry on any session
rotation/blip — after which every gated write silently did nothing:
theme changes reverted on reload (the reported "can no longer change
themes", on top of the interpolation bug d5dbaa48 fixed), chain-order
selects, collection deletion, Add-to-collection submits, filter
save/load/delete, conflict actions, linking actions, stats charts,
tag suggestions, device management, admin scanner actions — all dead
for perfectly authenticated cookie users.

Fix: storage.ts exports authHeaders() (bearer when present, cookie
carries otherwise) and every gate/header site now uses it — theme.ts,
collections.ts (htmx auth, doRemoveBook/doBulkRemove, setChainOrder),
bookPicker submit, filter_builder suggestions + match count,
collection-rules apply hook, bookshelf save/load/delete filter,
conflicts x4, linking x3, admin scanner actions + polls (requireToken
removed — its "Session expired" toast fired for cookie users too),
dashboard preferences/sections, custom-section-builder, header
scanner poll, stats x3, tag suggestions, profile delete-account
(which also wrongly redirected cookie users to /login), and
device-management x4. Reads keep their graceful-empty behavior; the
bearers still ride along when present.

Pinned: the knob-matrix theme spec now REMOVES localStorage.token and
asserts the theme PUT still fires (cookie-only) and the class flips —
the exact strand that started this.

Found by noticing the panel browser's Nord click switched the class
but produced no PUT: the persistence half was gated on a token the
401 interceptor had cleared.
2026-10-31 17:02:44 -04:00

151 lines
3.7 KiB
TypeScript

// Book Picker for Collections - multi-select book picker modal
// CRITICAL: Selection state must persist across HTMX grid updates
import { authHeaders } from "./storage";
import { Alpine } from "./alpine";
import { showToast } from "./toast";
// Alpine.store for global book picker state
// Using store ensures state persists across HTMX DOM swaps
Alpine.store("bookPicker", {
isOpen: false,
selectedBooks: new Set<string>(),
// Picker scope (plan item 2.3): "books" (default) or "episodes" —
// YOUR subscriptions' episodes. Pure client-local tab state; the
// selection store is shared, ids never collide.
scope: "books",
open() {
this.isOpen = true;
this.selectedBooks.clear();
this.scope = "books";
this.loadBooks();
},
close() {
this.isOpen = false;
this.selectedBooks.clear();
},
switchScope(scope: "books" | "episodes") {
this.scope = scope;
if (scope === "episodes") {
this.loadEpisodes();
} else {
this.loadBooks();
}
},
toggleBook(bookId: string) {
if (this.selectedBooks.has(bookId)) {
this.selectedBooks.delete(bookId);
} else {
this.selectedBooks.add(bookId);
}
// Trigger Alpine reactivity by creating new Set
this.selectedBooks = new Set(this.selectedBooks);
},
isSelected(bookId: string): boolean {
return this.selectedBooks.has(bookId);
},
get selectedCount(): number {
return this.selectedBooks.size;
},
async loadBooks() {
const grid = document.getElementById("book-picker-grid");
if (!grid) return;
// Trigger initial HTMX load
window.htmx.trigger(grid, "loadBooks");
},
async loadEpisodes() {
const grid = document.getElementById("episode-picker-grid");
if (!grid) return;
window.htmx.trigger(grid, "loadEpisodes");
},
clearFilters() {
const filterDiv = document.getElementById("book-picker-filters");
if (!filterDiv) return;
const inputs = filterDiv.querySelectorAll('input[type="text"]') as NodeListOf<HTMLInputElement>;
inputs.forEach((input) => {
input.value = "";
});
this.loadBooks();
},
async submit() {
if (this.selectedBooks.size === 0) {
showToast("No books selected", "error");
return;
}
// Get collection ID from current page
const pathParts = window.location.pathname.split("/");
const collectionId = pathParts[pathParts.length - 1];
try {
const response = await fetch(`/api/collections/${collectionId}/books`, {
method: "POST",
headers: {
...authHeaders(),
"Content-Type": "application/json",
},
body: JSON.stringify({
book_ids: Array.from(this.selectedBooks),
}),
});
if (response.ok) {
showToast(`Added ${this.selectedBooks.size} items to collection`, "success");
this.close();
location.reload();
} else {
showToast("Failed to add items", "error");
}
} catch (error) {
console.error("Failed to add books:", error);
showToast("Error adding books", "error");
}
},
});
// Alpine component for book picker
// Provides methods for template to access store
Alpine.data("bookPicker", () => ({
get isOpen() {
return window.Alpine?.$store.bookPicker.isOpen;
},
get selectedCount() {
return window.Alpine?.$store.bookPicker.selectedCount;
},
toggleBook(bookId: string) {
window.Alpine?.$store.bookPicker.toggleBook(bookId);
},
isSelected(bookId: string): boolean {
return window.Alpine?.$store.bookPicker.isSelected(bookId);
},
clearFilters() {
window.Alpine?.$store.bookPicker.clearFilters();
},
close() {
window.Alpine?.$store.bookPicker.close();
},
submit() {
window.Alpine?.$store.bookPicker.submit();
},
}));