Files
bookhoard/web/src/index.ts
T
john-okeefe 48eaa2d286 fix(alpine): wrap all Alpine.data() callbacks in arrow functions for proper component initialization
- Wrap all Alpine.data() object literals in arrow functions (() => ({}))
- This fixes "n.bind is not a function" errors when Alpine initializes components
- Alpine.data() requires a factory function, not a plain object
- Ensures each component instance gets its own closure and proper this binding

Fixed 24 TypeScript files:
- admin.ts, analytics.ts, api.ts, api-explorer-docs.ts
- bookshelf.ts, collection-rules.ts, collections.ts, conflicts.ts
- device-management.ts, docs.ts, header.ts, index.ts
- library.ts, linking.ts, login.ts, password_validation.ts
- profile-modal.ts, profile.ts, queue.ts, register.ts
- search.ts, theme.ts, toast-error.ts, toast.ts, unlinked_books.ts

Before: Alpine.data("name", { method1, method2 })
After:  Alpine.data("name", () => ({ method1, method2 }))

This is a critical fix for Alpine.js v3+ where components must be
registered as factory functions to ensure proper reactivity and
prevent binding errors during initialization.
2026-03-12 15:43:56 -04:00

51 lines
1.2 KiB
TypeScript

import { Alpine } from "./alpine";
import { applyTheme } from "./theme";
import { getToken } from "./storage";
function initIndexTheme(): void {
// Progressive enhancement: check localStorage immediately
const savedTheme = localStorage.getItem("theme");
if (savedTheme && savedTheme !== "tokyo-night") {
applyTheme(savedTheme);
}
}
function changeTheme(): void {
const select = document.getElementById("theme-select") as HTMLSelectElement;
if (!select) return;
const newTheme = select.value;
applyTheme(newTheme);
// Save to localStorage
localStorage.setItem("theme", newTheme);
}
async function checkAuthRedirect(): Promise<void> {
const token = getToken();
if (!token) return;
try {
const response = await fetch("/api/auth/profile", {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
// Token is valid, redirect to dashboard
window.location.href = "/dashboard";
}
} catch (error) {
console.error("Failed to check auth", error);
}
}
export { changeTheme, checkAuthRedirect, initIndexTheme };
Alpine.data("index", () => ({
changeTheme,
checkAuthRedirect,
initIndexTheme,
}));