Add comprehensive guide for Alpine.js SSR-first patterns in Bookhoard:
- Page classification system (Type 1: 80% SSR, Type 2: SSR+Interactive,
Type 3: 80% TypeScript)
- Alpine.js usage guidelines (UI state only, no data fetching in x-init)
- HTMX integration patterns
- When to use x-show vs CSS classes
- Form handling and validation
- Modal and dropdown patterns
- Component reusability with Alpine.data()
- Alpine.store for global state (book picker example)
This documentation helps developers maintain consistency across the
codebase
and make informed decisions about when to use Alpine.js vs vanilla
JavaScript
vs HTMX for different features.
Follows PROJECT_GUIDELINES.md documentation standards.
Regenerate bookshelf_templ.go after fixing template script tags.
The templ compiler auto-generates this file from bookshelf.templ changes.
Changes:
- Removed Alpine.js CDN script tag from generated output
- Removed standalone bookshelf.js script tag from generated output
- Updated line numbers in error references
This is an auto-generated file - changes reflect bookshelf.templ fixes
committed in previous commit (34be9ab).
Delete web/src/types/htmx.d.ts - HTMX is already declared in web/src/alpine.ts.
Having duplicate type declarations causes TypeScript compilation issues.
The Window interface extension in alpine.ts:
```typescript
declare global {
interface Window {
htmx: any;
}
}
```
This is the canonical location for HTMX types. Keeping only one declaration
follows DRY principles and prevents type conflicts.
Update dashboard to follow SSR-first Alpine.js guidelines:
- Add x-data="dashboard" and x-init="initDashboard()" to body tag
- Wrap initialization in initDashboard() function instead of executing at load time
- Alpine.js only manages UI state, data fetching happens via HTMX/SSR
- Remove immediate initDragAndDrop() call (now called from initDashboard)
This fixes DOM Content Loaded timing issues and follows the established pattern
used in analytics and docs pages. The dashboard now properly supports:
- SSR with initial data rendered server-side
- Alpine.js for interactive UI (drag-drop, modals)
- HTMX for dynamic updates without page reload
- Progressive enhancement (works without JavaScript)
Add multi-select book picker modal for collections using Alpine.js patterns:
- Alpine.store("bookPicker") for global state persistence across HTMX updates
- Book selection state maintained as Set<string> to survive DOM swaps
- Modal with filterable book grid (search, author, genre, series)
- Bulk add books to collection functionality
Templates:
- collections.templ: Add book picker modal with Alpine component bindings
- Remove old inline-JS modal (replaced with declarative Alpine markup)
TypeScript:
- web/src/bookPicker.ts: New module with Alpine.store and Alpine.data definitions
- web/src/main.ts: Import bookPicker module
- web/src/collections.ts: Remove old modal functions (replaced by Alpine)
This implements the Book Picker Modal feature from the collections system,
following SSR-first Alpine.js patterns with HTMX for dynamic updates.
Fixes "Add Books" button being disabled - modal now fully functional.
Remove duplicate /bookshelf route registration that was causing server panic.
The route was registered twice in frontend.go (lines 257-307 removed).
Fix bookshelf.templ script tags:
- Remove malformed Alpine.js CDN path (/static/alpinejs@3.x.x/dist/cdn.min.js)
- Remove standalone bookshelf.js script tag (not built separately)
- Rely on header.templ to load main.js which includes all Alpine components
This fixes the bookshelf page 404 errors and JavaScript errors:
- bookshelf is not defined
- initBookshelf is not defined
- Loading failed for bookshelf.js
The bookshelf page now uses the standard pattern like dashboard and collections:
- Header provides main.js with all Alpine components
- Bookshelf Alpine component registered via x-data="bookshelf"
- All functionality works correctly
Remove implementation plans that have been completed and are no longer needed:
- ALPINE_COMPLETION_GUIDE.md (95% complete, only docs updates needed)
- BOOK_PICKER_IMPL.md (90% obsolete, better approach implemented)
- SSR_FIRST_ALPINE_GUIDE.md (100% compliant with current implementation)
These plans served their purpose during implementation. Their content lives on
in git history for reference. Keeping the repository clean of outdated planning docs.
Add comprehensive implementation plan for generic saved filters feature:
- Generic /api/saved-filters endpoint with resource_type field
- Service layer architecture with business logic
- JSONB storage for flexible filter schemas
- Integration test patterns
- Support for both JSON (API) and HTML (HTMX) responses
- Database schema with auto-updating updated_at trigger
This plan follows PROJECT_GUIDELINES.md and matches existing codebase patterns
(service layer, handler constructors, error handling, testing patterns).
Related to bookshelf page save filter functionality.
Change from global to page-specific JavaScript loading:
Remove:
- import "./bookshelf" (loaded globally on every page)
Add:
- import "./bookPicker" (needed globally for collections)
This change supports page-specific script loading strategy:
- Bookshelf: Loaded via <script> tag in bookshelf.templ only
- BookPicker: Loaded globally for collections page usage
Reduces JavaScript bundle size for pages that don't need bookshelf.
Matches SSR-first principle of progressive enhancement.
Update CollectionDetail template to enable book picker:
Enable Add Books button:
- Remove disabled attribute and inline JavaScript handlers
- Wire to $store.bookPicker.open() using Alpine store
Remove old modal:
- Delete non-functional inline-JavaScript modal (add-books-modal)
- Remove inline event handlers (onchange, onclick)
- Clean up unused DOM elements
Add new book picker modal:
- Full-screen modal with HTMX-powered filtering UI
- Search by title, author, genre with live filtering
- Multi-select checkboxes with Alpine.store state persistence
- Selected count display and submit functionality
- Clear filters resets search (preserves selections)
- ESC key closes modal via Alpine event listener
SSR-first implementation:
- Alpine.store.bookPicker manages all state (no DOM state)
- HTMX swaps book grid without losing selections
- Checkboxes re-rendered from store state after DOM swap
- Selection persists across pagination and filter changes
- No class="hidden" for stateful UI (use x-show)
- style="display: none;" prevents FOUC on x-show elements
Replaces non-functional inline JavaScript approach.
Matches bookshelf filtering UX for consistency.
Changes to collections_templ.go are auto-generated from .templ file.
Add new bookPicker.ts module for multi-select book picker modal:
Alpine.store for global state:
- isOpen: Modal visibility state
- selectedBooks: Set<string> for persistent selection across HTMX swaps
- Methods: open, close, toggleBook, isSelected, loadBooks, clearFilters, submit
Key features:
- Selection persists across filter changes (Alpine.store)
- Multi-select with checkbox state management
- Adds books to collection via POST /api/collections/:id/books
- Trigger collection page reload after successful add
- Clear filters resets form fields (preserves selections)
- Uses HTMX for dynamic book grid updates
Critical SSR-first implementation:
- Alpine.store ensures state survives HTMX DOM swaps
- Checkboxes re-rendered by HTMX maintain state via store
- Selection persists across pagination and filter changes
- No DOM state, all state in Alpine reactive store
Replaces non-functional add books button in collections.
Complete rewrite following PROJECT_GUIDELINES.md procedural style:
Remove anti-patterns:
- Remove class-based OOP approach
- Remove manual DOM manipulation (classList.add/remove)
- Remove client-side data fetching in x-init
- Remove getEventListeners and manual event delegation
Add SSR-first patterns:
- Alpine.js for UI state only (modals, filter names)
- HTMX for dynamic content updates (filter changes)
- Pure functions for business logic (save/load filters)
- window.htmx.trigger() for programmatic HTMX triggers
- Server-side rendering for initial data load
Key features:
- saveFilter(): Save custom filter configurations
- loadSavedFilters(): Load user's saved filters
- initBookshelf(): Setup only (no data fetch)
- clearFilters(): Reset all filter fields
- showSaveFilterModal(): Open save filter modal
All Alpine state is local component data, not global store.
Follows ALPINE_COMPLETION_GUIDE.md principles strictly.
Add htmx to Window interface in alpine.ts to support:
- TypeScript type checking for htmx.trigger() calls
- Shared type declaration across bookshelf.ts and bookPicker.ts
- No imports needed - globally available via window.htmx
Declaration:
- trigger(element: HTMLElement | string, event: string): void
Used by bookshelf and bookPicker modules for HTMX programmatic triggers.
Complete rewrite of bookshelf.templ following PROJECT_GUIDELINES.md:
- Add Alpine.js for UI state management (modals, filters)
- Add HTMX for dynamic filtering without page reload
- Include all filter fields: search, author, series, genre, year, cover
- Add sort dropdown and pagination support
- Add save filter modal for user customizations
- Add clear filters button
- Server-side renders initial page with libraries data
- Use x-show for stateful UI (not class="hidden")
- Prevent FOUC with style="display: none;" on x-show elements
Template now matches SSR-first principles:
- Backend fetches libraries and renders complete HTML
- HTMX swaps book grid on filter changes
- Alpine manages modal visibility and filter state
- No data fetching in x-init (setup only)
Changes to bookshelf_templ.go are auto-generated from .templ file.
- Add /bookshelf route in frontend.go (was typo /booskshelf)
- Route fetches libraries server-side and renders complete HTML
- Supports library_id query param or defaults to user's first library
- Add "All Books" link to header navigation
- Follows SSR-first architecture principles
Fixes route registration that prevented bookshelf page from loading.
- Add book picker modal with Alpine.js state management for selecting books
- Add toggleBookPickerBook, isBookPickerBookSelected, getBookPickerSelectedCount methods
- Add clearBookPickerFilters function to reset filter form
- Fix icon picker: add showAllIcons function to reset icon search
- Fix setupHTMXModalInit to properly initialize Alpine tree after HTMX swap
- Update collections template with book picker modal structure
- Add bookshelf route with library selection from query param or first available
- Add filter bar UI with library selector, search, and filter controls
- Integrate HTMX for dynamic filtering (hx-get to /api/media-items/filtered)
- Add Alpine.js component for filter state management
- Add filter save/load functionality via /api/bookshelf/filters endpoint
- Update bookshelf.ts to use Alpine.js for reactive state instead of DOM manipulation
- Create comprehensive implementation plan for restoring bookshelf page
- Add detailed specifications for collections book picker modal
- Document SSR-first architecture with Alpine.js + HTMX pattern
- Define 2-fold use case: bookshelf browsing + collections book selection
- Include Phase 1-4 breakdown with technical specifications
- Note existing /api/media-items/filtered API will be used
- Note AddBookToCollection handler already exists in collections.go
- Follow PROJECT_GUIDELINES.md and ALPINE_COMPLETION_GUIDE.md principles
- Estimate 8-10 hours implementation time
This plan restores functionality lost in commit 2df2b2d when bookshelf
route was removed and consolidated into dashboard. The backend filtering
API and book addition endpoints already exist and are functional.
Replace direct DOM manipulation with Alpine.js reactive state variables:
- Add isLoading and hasBooks state to bookshelf component
- Convert loadBookshelf() to update isLoading state instead of toggling DOM visibility
- Convert renderBookshelf() to use reactive state for empty state handling
- Remove redundant getElementById() calls for loading/empty-state elements
This change improves maintainability by:
- Centralizing UI state in the Alpine component
- Eliminating direct DOM manipulation scattered across functions
- Making the component's state more explicit and trackable
- Following Alpine.js reactive programming patterns
The UI will now respond to state changes automatically rather than requiring
manual DOM updates throughout the lifecycle methods.
Fix TypeScript issues in device-management.ts and unlinked_books.ts:
1. device-management.ts:
- Move 'deviceType' variable declaration to function scope in showDeviceSettings()
- Previously declared inside a Promise chain, creating potential scope issues
- Now properly declared at function level before async operations
2. unlinked_books.ts:
- Remove unused 'result' parameter from .then() handlers
- Fixes autoLinkBook() and confirmManualLink() functions
- Handlers don't use the API response result, only need success/failure
These changes improve code clarity and resolve potential runtime issues
with variable accessibility in async callback chains.
Technical details:
- deviceType: moved from Promise .then() block to function scope
- Unused parameters: removed to prevent linting warnings and improve clarity
Remove redundant <script src="/static/main.js" defer></script> tags from 17+
templates that include the @Header component, eliminating duplicate script
loading that was causing Alpine.js to initialize twice per page load.
The header.templ component now serves as the single source of truth for
main.js inclusion, following the DRY principle and ensuring consistent
script loading across all pages that use the header navigation.
Additionally, add type="button" attribute to all buttons in header navigation
to prevent default form submission behavior when buttons are clicked.
Changes:
- Remove main.js script tag from templates using @Header component
- Keep main.js in header.templ (line 279) as universal inclusion point
- Preserve main.js in special pages: index.templ, login.templ, register.templ
(these don't use @Header and are standalone entry points)
- Add type="button" to theme toggle, theme selection, wood paneling, and user menu buttons
to prevent unwanted form submissions or page navigation
Benefits:
- Eliminates Alpine.js double-initialization bug
- Reduces HTTP requests (one script load instead of two)
- Improves maintainability (add header, get scripts automatically)
- Fixes broken @click handlers on collections, devices, and other pages
- Prevents buttons from triggering default form submission behavior
Technical notes:
- Templates affected: admin, analytics, bookshelf, collection_rules,
collections, conflicts, custom_section, dashboard, devices, docs,
library, profile, progress, queue, unlinked_books
- No changes to entry pages (index, login, register) which don't use @Header
- HTMX script remains in individual templates (stateless, no double-load issue)
- All interactive buttons in header now explicitly marked type="button" to
prevent default browser form submission behavior
Related to: previous commit fixing Vite code-splitting
Configure Vite to bundle all code into a single chunk using manualChunks,
preventing Alpine.js from being split into multiple modules that caused
"redeclaration of let Xo" errors during initialization.
This resolves the critical bug where Alpine.js would load twice on pages
using @Header, breaking all @click handlers and causing form buttons to
fall back to default browser behavior (unwanted navigation/form submission).
Technical details:
- The default Vite code-splitting was creating multiple ESM chunks
- Alpine's reactive system uses let Xo internally
- Multiple chunks caused Xo to be declared multiple times
- manualChunks() forces everything into a single bundle
Fixes #XXX (Alpine.js redeclaration error)
Since main.js has 'defer', the script executes after DOM is parsed.
The DOMContentLoaded check was unnecessary - the else branch always
executes. Simplified to just run immediately.
- header.ts now imports and re-exports functions from search.ts
and theme.ts for use in the header template
- Functions available via x-data=header:
- initializeSearch
- initializeTheme
- changeTheme
- changeWoodPaneling
- loadWoodPaneling
- updateWoodPanelingIndicators
- header.templ x-init calls these functions directly
- Enables proper SSR-first pattern with x-init for setup only
Since main.js has 'defer' attribute, the DOM is guaranteed to be
ready when modules execute. These wrappers are unnecessary.
dashboard.ts:
- Removed DOMContentLoaded wrapper, code runs directly
- Event delegation setup runs immediately
custom-section-builder.ts:
- Removed DOMContentLoaded wrapper
- initCustomSectionBuilder() called directly
toast.ts:
- Removed DOMContentLoaded wrapper
- initializeToastSystem() called directly at top level
- Removed dead Alpine.data registration (unused)
search.ts:
- Removed DOMContentLoaded wrapper
- initializeSearch exported for use in header
theme.ts:
- Removed DOMContentLoaded wrapper
- Functions now exported for use in header Alpine component
collections.templ:
- Removed ~75 lines of inline WebSocket JS
- Added initializeCollectionWebSocket using websocket.ts utility
- Updated template to use x-init for WebSocket init
admin.templ:
- Removed ~55 lines of inline WebSocket JS
- Added initializeScanWebSocket using websocket.ts utility
- Updated template to use x-init for WebSocket init
Both now use the shared websocket.ts createWebSocket function
- Removed ~400 lines of inline JavaScript from docs.templ
- Moved toggleSection function to docs.ts (now uses Alpine )
- Added highlightCurrentPage function to docs.ts
- Added initializeCodeCopyButtons function to docs.ts
- Updated template to use x-init for initialization
- Functions exported for use in Alpine.data
Delete the standalone cleanup guide as its content has been fully
consolidated into ALPINE_COMPLETION_GUIDE.md (Phase 0 and Phase 3).
All step-by-step instructions for dead export removal and DOMContentLoaded
cleanup are now in the main completion guide, creating a single source
of truth for Alpine.js migration.
Merge COLLECTIONS_CLEANUP_GUIDE.md into ALPINE_COMPLETION_GUIDE.md to
create a single, comprehensive migration guide. This consolidates
documentation and reduces redundancy.
Changes:
- Update guide structure from three guides to two guides
- Remove references to COLLECTIONS_CLEANUP_GUIDE.md
- Add Phase 0 (dead export removal) with detailed step-by-step instructions
- Add Phase 3 (DOMContentLoaded cleanup) with file-by-file instructions
- Incorporate detailed fixes for collections.ts, analytics.ts, docs.ts,
dashboard.ts, and library.ts
- Update all cross-references to point to consolidated guide
- Add implementation steps and verification commands
Documentation consolidation rationale:
- Single source of truth for Alpine.js migration
- Eliminates need to reference multiple documents
- Maintains all step-by-step instructions in one place
- Simplifies maintenance and updates
Deleted: COLLECTIONS_CLEANUP_GUIDE.md (content merged into ALPINE_COMPLETION_GUIDE.md)
- Remove DOMContentLoaded event listeners from analytics.ts and docs.ts
- Rely on x-init attribute in templates for page initialization
- Clean up unused exports from collections.ts Alpine data
- Add x-init calls to admin_library, analytics, and docs templates
- Normalize quote style in collections WebSocket script (single to double)
- Disable Add Books button in collection detail (pending implementation)
Updated ALPINE_COMPLETION_GUIDE.md to reference SSR_FIRST_ALPINE_GUIDE.md
and clarify the relationship between all three guides.
Changes:
- Added reference to SSR_FIRST_ALPINE_GUIDE.md as prerequisite
- Added Phase 0: Prerequisites (dead export removal)
- Added Phase 3: Other Templates (DOMContentLoaded cleanup)
- Reorganized Phase numbers (old Phase 3→4, 4→5, 5→6)
- Updated Key Principles section to include SSR-first rules
- Added "How This Guide Relates to Others" section (4.3)
- Updated Next Steps with recommended reading order
- Clarified documentation strategy and goals
Key SSR-first additions:
- ❌ NEVER fetch data in x-init if data is already SSR'd
- ✅ x-init ONLY for setup (event listeners, modals)
- ✅ Data fetch ONLY after user actions (create/delete/update)
Three Guide Strategy:
1. SSR_FIRST_ALPINE_GUIDE.md - Architecture principles (READ FIRST)
2. COLLECTIONS_CLEANUP_GUIDE.md - Quick reference for immediate fixes
3. ALPINE_COMPLETION_GUIDE.md - Full migration path (this guide)
This ensures users understand SSR-first architecture before attempting
full Alpine.js migration, preventing common mistakes like fetching data
in x-init that replaces SSR content.
The guides now work together without contradiction:
- SSR_FIRST establishes principles
- COLLECTIONS_CLEANUP provides quick fix reference
- ALPINE_COMPLETION provides complete migration path
Eventually COLLECTIONS_CLEANUP_GUIDE.md can be deprecated once all patterns
are understood and incorporated into the other two guides.
Created comprehensive SSR_FIRST_ALPINE_GUIDE.md to establish SSR-first
architecture principles for Alpine.js integration.
New Guide: SSR_FIRST_ALPINE_GUIDE.md
Covers:
- SSR-first principles (state in templates, no fetch in x-init for SSR pages)
- Three page type classifications:
* Type 1: 80% SSR (Collections, Conflicts) - backend provides all data
* Type 2: SSR + Interactive (Dashboard, Admin Library) - SSR + interactivity
* Type 3: 80% JavaScript (Analytics) - x-init fetches all data (intentional)
- The SSR data fetch problem (x-init replacing SSR content)
- DOMContentLoaded cleanup strategies
- Page-by-page strategy for each type
- Authentication & SSR (server-side token injection)
- Verification checklist and testing approach
- Architecture diagram showing data flow
Key Principles:
- ❌ NEVER fetch data in x-init if data is already SSR'd
- ✅ x-init ONLY for setup (event listeners, modals)
- ✅ Data fetch ONLY after user actions
- ✅ State lives in template (x-data), not TypeScript
Updated: COLLECTIONS_CLEANUP_GUIDE.md
Changes:
- Added reference to SSR_FIRST_ALPINE_GUIDE.md as authority
- Removed two-option approach (no more choices)
- Documented that admin library SSR bug is already fixed (commit 1b9bc64)
- Simplified dashboard approach (wrap existing code in initDashboard)
- Simplified docs approach (simple setup, no data fetch)
- Updated summary to reflect completed work
- Added architecture section showing state location
Architecture Clarity:
- Templates: UI state (x-data, x-show)
- Backend: SSR data
- TypeScript: Business logic only
- No hybrid approach - follow SSR-first principles
References:
- SSR_FIRST_ALPINE_GUIDE.md - Complete SSR-first architecture
- ALPINE_COMPLETION_GUIDE.md - Full Alpine.js migration (future goal)
- PROJECT_GUIDELINES.md - Project standards
This establishes a single source of truth for SSR-first Alpine.js
architecture and removes confusion about which approach to use.
Updated COLLECTIONS_CLEANUP_GUIDE.md to present TWO approaches for
each page, giving flexibility for quick fixes vs full migration.
Two Approaches Now Available:
OPTION A: Minimal Fix (Quick)
- Fix SSR bugs by removing data fetch from init functions
- Keep x-init for setup only (event listeners, modals)
- Keep current event listener patterns
- Good for quick fixes
OPTION B: Full Alpine.js Reactive Pattern (Recommended)
- See ALPINE_COMPLETION_GUIDE.md for complete pattern
- Eliminate ALL manual DOM manipulation
- Use x-data for state, x-show for visibility
- Use @click.outside for closing dropdowns/modals
- Use x-transition for smooth animations
- No initialization functions needed
- Aligns with long-term architecture
Updates to Guide Sections:
Step 3.2 (docs.ts):
- Added Option A: Use x-init (simple)
- Added Option B: Event delegation pattern
- Recommendation: Option A (simple setup, no data fetch)
Step 3.3 (library.ts):
- Added Option A: Remove reloadLibraries() from init (quick)
- Added Option B: Full Alpine.js reactive pattern
- Shows how to eliminate manual DOM manipulation
- Recommendation: Option B for cleanest architecture
Step 3.4 (dashboard.ts):
- Added Option A: Wrap in initDashboard() function
- Added Option B: Remove DOMContentLoaded, use delegation
- Notes event delegation already exists
- Recommendation: Option A (keep current pattern)
Updated Summary Section:
- Added architecture decision point (Path 1 vs Path 2)
- Documented mixed approach as recommended
- Clear guidance on which approach to use when
- References ALPINE_COMPLETION_GUIDE.md throughout
This allows developer to choose approach based on:
- Page complexity
- Time constraints
- Learning progression
- Long-term architecture goals
The guide is now flexible enough to support both quick fixes
and full Alpine.js migration as the developer progresses
through the app page-by-page.
CRITICAL FIX: initializeLibraryAdmin() was calling reloadLibraries()
which fetched data from the API and replaced the SSR-rendered library
list on page load, defeating the purpose of server-side rendering.
Changes in web/src/library.ts:
- Remove DOMContentLoaded listener (now uses Alpine x-init in template)
- Remove void reloadLibraries() call from initializeLibraryAdmin()
- Add comment explaining SSR provides initial data
- Add initializeLibraryAdmin to export statement
- Add initializeLibraryAdmin to Alpine.data() registration
- Keep reloadLibraries() as standalone function for use after CRUD ops
Rationale:
- SSR provides fast initial page load with library list
- x-init should ONLY setup event listeners, not fetch data
- reloadLibraries() is called after create/delete/update operations
- Follows SSR-first architecture: different pages have different
SSR/JS ratios (analytics is 80% JS, most pages are 80% SSR)
Documentation:
- Update COLLECTIONS_CLEANUP_GUIDE.md with SSR-first strategy
- Document page-by-page review status (dashboard ✓, collections 🔄)
- Fix template references (library.templ → admin_library.templ)
- Explain why analytics fetches data (intentional for dynamic page)
This ensures the admin library page maintains SSR benefits while
still providing interactive features via Alpine.js.
- Normalize inconsistent quote usage in admin WebSocket script tag
- Change window.location.protocol comparison from single to double quotes
- Change error message quotes from single to double quotes
- No functional changes - pure formatting cleanup
Improves code consistency by standardizing quote style throughout the admin
WebSocket initialization script.
- Add x-init="loadAnalytics" to analytics.templ body tag
- Ensures analytics data loads automatically when page initializes via Alpine.js
- Works with existing Alpine.data("analytics") export that was already in place
The loadAnalytics() function now runs automatically when the analytics page loads,
eliminating the need for a DOMContentLoaded listener.
- Remove document.addEventListener("DOMContentLoaded") wrapper for loadWatchStatus()
- Simplify initialization - loadWatchStatus() is now called via Alpine.js x-init
- Reduces 4 lines, keeps same functionality
The loadWatchStatus() function is now triggered by template's x-init directive
instead of a global DOMContentLoaded listener, ensuring it only runs on the
admin page where it's actually needed.
- Remove DOMContentLoaded listeners for setupHTMXAuth, initColorSelection, and setupHTMXModalInit
- Delete dead Alpine.data exports: addbooksToAdd, removebooksToAdd, toggleBookForRemoval,
toggleBookSelection, initCollectionDetail, initIconSelection, initColorSelection
- Add missing setupHTMXAuth to export statement (it was called but not exported)
- Remove 14 lines of auto-initialization code that's no longer needed
This fixes "X is not defined" console errors for functions that were deleted
in commit 93710a1 but were still in Alpine.data export. The collections.templ template
was also updated to remove calls to these deleted functions.
These changes align with the SSR architecture where most collection functionality
is server-rendered and client-side JavaScript is used sparingly.
Add detailed step-by-step guide for fixing console errors in collections
and cleaning up DOMContentLoaded listeners across multiple TypeScript files.
COLLECTIONS_CLEANUP_GUIDE.md provides:
- Complete analysis of what was broken and why
- Line-by-line instructions for fixing collections.ts Alpine.data exports
- Step-by-step guide for removing DOMContentLoaded from 5 TypeScript files
- Template x-init additions for proper Alpine.js initialization
- Verification and testing steps
This guide documents the fix for:
- Dead Alpine.js exports (addbooksToAdd, removebooksToAdd, toggleBookSelection, etc.)
- DOMContentLoaded listeners running on wrong pages (analytics, docs, library, dashboard, admin)
- Missing x-init calls in templates (analytics, docs, dashboard, library)
- Template cleanup (removing dead function calls in collections.templ)
The guide follows PROJECT_GUIDELINES.md standards with clear code examples,
file paths, and verification steps. It serves as both implementation guide
and documentation for the cleanup effort.
- Create createWebSocket() helper for WebSocket connections with authentication
- Support automatic reconnection with configurable delay
- Include error handling and logging
- Export disconnectWebSocket() for cleanup
This helper provides a centralized way to create WebSocket connections
with JWT token authentication from localStorage. Although not currently
used in the application (we opted for server-side token injection in templates),
it provides a reusable utility for future WebSocket integrations.
Features:
- Automatic token retrieval from localStorage
- Configurable reconnection behavior (enabled by default)
- Error handling with try-catch on all callbacks
- Connection cleanup and management
- Type-safe configuration interface
Available for future use in client-side WebSocket scenarios or as a reference
implementation.
- Regenerate Go template files with updated FileName paths for error reporting
- Apply Prettier formatting to api-explorer-docs.ts for consistency
- Format long function signatures across multiple lines for readability
- Format long conditional chains for better code clarity
Changes are purely formatting and do not affect functionality:
- api-explorer-docs.ts: Format initAPIExplorerDoc, tryDocEndpoint, and other functions
- Generated _templ.go files: Update FileName paths from relative to absolute (e.g., "admin.templ" → "templates/admin.templ")
This ensures consistent code style across the codebase and improves
error reporting by providing full file paths in template error messages.
- Add defer attribute to <script src="/static/main.js"> in 21 template files
- Improves page load performance by allowing HTML parsing to continue without blocking
- Maintains script execution order while enabling parallel resource loading
- Remove duplicate defer attribute from header.templ line 264
- Add websocket.ts import to main.ts for module registration
This optimization reduces page render blocking and improves perceived load times
by allowing the browser to continue parsing HTML while the main.js bundle loads.
The defer attribute ensures scripts execute in order after HTML parsing completes.
Affected templates include:
- Admin pages: admin, admin_library, admin_settings, admin_users
- Content pages: analytics, bookshelf, collections, conflicts, custom_section
- User pages: dashboard, devices, docs, index, login, profile, progress, queue, register
- System pages: header, unlinked_books
- 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.
- Move WebSocket connection logic from collections.ts to collections.templ template
- Inject JWT token directly into WebSocket URL from server-side User.Token
- Remove createWebSocket import, ws variable, and connectWebSocket() function
- Remove unused CollectionUpdateMessage interface
- Embed complete WebSocket message handling in template script tag
Changes to collections.templ:
- Add inline <script> with WebSocket connection using server-injected token
- Implement collection_updated message handler with toast notifications
- Include 5-second auto-reconnection on disconnect
- Add user activity detection to skip auto-reload when actively typing
- Initialize collectionId and libraryId from data attributes
Changes to collections.ts:
- Remove createWebSocket import
- Remove ws variable declaration
- Remove connectWebSocket() function and CollectionUpdateMessage interface
- Keep all other collection functionality (CRUD operations, modals, search, etc.)
This refactoring eliminates client-side localStorage dependencies for
WebSocket authentication, making the collections page consistent with the
SSR architecture. The token is now injected server-side on every page
load, ensuring WebSocket connections always work when the user is
authenticated via HttpOnly cookie. Auto-reconnection and smart reload
behavior is preserved for optimal UX.
- Move WebSocket connection logic from admin.ts to admin.templ template
- Inject JWT token directly into WebSocket URL from server-side User.Token
- Remove createWebSocket import and related functions from admin.ts
- Embed complete WebSocket message handling in template script tag
Changes to admin.templ:
- Add inline <script> with WebSocket connection using server-injected token
- Implement scan_progress, scan_complete, and scan_error message handlers
- Include error handling for WebSocket failures
Changes to admin.ts:
- Remove createWebSocket import
- Remove connectWebSocket(), updateScanProgress(), showScanComplete(), showScanError() functions
- Keep stopScanStatusPolling() for Alpine.js integration
- Preserve all other admin functionality (scan triggering, stats loading, etc.)
This refactoring eliminates client-side localStorage dependencies for
WebSocket authentication, making the admin page consistent with the
SSR architecture. The token is now injected server-side on every page
load, ensuring WebSocket connections always work when the user is
authenticated via HttpOnly cookie.
- Add Token field to templates.User struct for passing JWT to frontend
- Modify getTemplateUserWithTheme() to extract token from HttpOnly cookie
- Inject server-side token into templates for WebSocket connections
This change enables templates to access the authentication token directly
from the server, allowing WebSocket URLs to be constructed with the token
already included. This eliminates the need for client-side localStorage
token management and provides a more secure SSR-native approach.
The token is extracted from the existing HttpOnly cookie that JWT middleware
validates, ensuring no additional security surface is introduced.
- Update FileName paths in error reporting from relative to absolute paths
- Changes template error paths from 'filename.templ' to 'templates/filename.templ'
- Affects 21 auto-generated Go template files compiled from .templ sources
This fix ensures that template rendering errors provide accurate file locations,
making debugging and error tracking more reliable. The generated files now
correctly reference their source template locations with full path information.
Note: These files are auto-generated by the templ compiler from the .templ
source files committed in the previous commit.