This commit adds comprehensive functionality for filtering collections by library,
improves WebSocket real-time updates with user activity detection, and adds
extensive test coverage.
## Core Features
### Collection Library Filter
- Added library_id parameter to media-items search API
- Collections can now be filtered by specific library
- Toggle UI component for enabling/disabling library filter
- Default state is "checked" when library_id is present
- Consistent behavior across partial and fuzzy search modes
### WebSocket Auto-Reload Mitigation
- Added user activity detection to prevent disruptive page reloads
- Checks if user is actively typing in INPUT/TEXTAREA/SELECT elements
- Skips auto-reload when user is interacting with form elements
- Toast notifications still show for awareness
- Prevents data loss during editing operations
## Implementation Changes
### Backend
- internal/database/queries.sql.go: Added library filter support to search queries
- internal/handlers/media.go: Enhanced search with library_id parameter validation
- internal/handlers/collections.go: Updated collection handlers with library filtering
- internal/sync/websocket.go: Improved broadcast mechanism with user-scoped updates
- internal/router/frontend.go: Pass libraryID to collection templates
### Frontend
- templates/collections.templ: Added library filter toggle UI component
- web/src/collections.ts: TypeScript implementation with WebSocket integration
- templates/collections_templ.go: Generated template code
### Testing
- cmd/server/tests/search_test.go: Added TestCollectionSearchLibraryFilter
- cmd/server/tests/websocket_test.go: Added TestWebSocketUserScopedBroadcast
- New helper functions for creating libraries and media items via API
- Comprehensive test coverage for library filtering and user-scoped broadcasts
## API Documentation Updates
### Bruno Tests (Comprehensive Documentation)
- bruno/collections/*: Added detailed API documentation for all collection endpoints
- bruno/devices/*: Added device management and sync API documentation
- bruno/devices/kobo/api.yml: Kobo-specific sync protocol docs
- bruno/devices/koreader/api.yml: KOReader-specific sync protocol docs
- bruno/opds/*: Added OPDS feed and download endpoint documentation
- bruno/library/browse-folders.yml: Library folder browsing API docs
### New Bruno Tests
- bruno/media-items/Search All Libraries.yml: Test search without library filter
- bruno/media-items/Search Specific Library.yml: Test search with library filter
- bruno/media-items/Search Invalid Library ID.yml: Test error handling
## Documentation
- docs/developer/api/media-items/search_media_items.md: Updated with library_id parameter
- IMPLEMENTATION_COLLECTION_FIX.md: Comprehensive implementation guide with test scenarios
## Testing
### Integration Tests
- Library filter tests verify correct filtering across multiple libraries
- Invalid library_id tests ensure proper error handling
- WebSocket tests verify user-scoped broadcast behavior
- User A no longer receives User B's collection updates
### Manual Testing Scenarios
- Open collection in multiple tabs - updates propagate correctly
- Type in search box while another tab adds books - no disruptive reload
- Add/remove books from collection - toast notifications appear
- Toggle library filter - results update dynamically
## Technical Details
- WebSocket broadcasts are now user-scoped for privacy
- Active element detection uses tagName and contenteditable attributes
- Library ID validation uses UUID format checking
- Progressive enhancement maintained - page works without JavaScript
- All changes follow PROJECT_GUIDELINES.md conventions
- TypeScript only for frontend logic
- TailwindCSS only for styling
- Procedural programming style throughout
## Breaking Changes
None - all changes are additive and backward compatible.
Add comprehensive TypeScript utilities for collections page functionality.
1. HTMX Authentication (setupHTMXAuth):
- Adds Authorization header to all HTMX requests automatically
- Listens for htmx:configRequest event on document.body
- Injects Bearer token from localStorage
- Eliminates need for hx-headers attributes on individual elements
2. Smart Card Navigation (navigateToCollection):
- Implements event delegation to distinguish button clicks from card clicks
- Checks event.target to determine what user clicked
- Returns early if button clicked (lets HTMX handle button actions)
- Navigates to collection detail page only when card body clicked
- Uses data-href attribute for navigation target
3. Color Selection Helpers:
- selectColor(): Updates hidden input and visual selection state
- closeCollectionModal(): Removes modal from DOM after HTMX swap
- initColorSelection(): Applies border color classes to collection cards
using borderClasses mapping (blue→border-blue-500, etc.)
4. Icon Picker with Search:
- Hardcoded iconData object: 30 emojis with searchable keywords
(e.g., "📚": ["book", "books", "library", "read", "reading"])
- populateIconGrid(): Dynamically generates icon buttons from iconData
- selectIcon(): Updates hidden input with selected emoji
- filterIcons(): Real-time search filtering by emoji OR keywords
- showAllIcons(): Clears search filter
- initIconSelection(): Auto-initializes after HTMX modal swap
(listens for htmx:afterSwap event on #modal-container)
5. HTMX Modal Initialization:
- setupHTMXModalInit(): Listens for modal loads via HTMX
- Auto-initializes icon picker when modal content swapped into
#modal-container
All functions exported to window object for onclick attribute access.
Auto-initializes on DOMContentLoaded or immediately if DOM ready.
Pattern consistency:
- Follows same pattern as toast.js (global exports, auto-init)
- Uses TypeScript type annotations
- No OOP (functional style per project guidelines)
- Server-side rendering with HTMX (no AJAX data fetching)
- Update wood-light border from harsh black (#2a2a2a) to lighter warm brown (#8b5a2b) for better harmony with light background
- Update wood-dark border from #5c3317 to #7a5228 (slightly lighter medium brown) for improved visibility on dark backgrounds
- Update wood-mahogany border from #5c3317 to #8b3a3a (medium red-brown) to enhance mahogany's characteristic reddish tones
- Reduce background blend opacity from 60% to 40% to create more subtle text area background that complements new border colors
These changes improve visual consistency between border colors and their respective wood paneling backgrounds while maintaining good text contrast across all wood themes.
Fix multiple issues with wood paneling background image display
affecting overscroll area and page-specific rendering.
CSS changes in web/static/input.css:
- Add background-attachment: fixed to all wood paneling classes
- Prevents wood paneling from moving during page scroll
- Ensures wood paneling extends into overscroll area
- Applied to bg-wood-dark, bg-wood-light, bg-wood-mahogany
- Fix body and container selectors for wood paneling
- Ensure proper selector targeting for wood paneling application
- Use background-position: center for better alignment
- Use background-size: cover for full coverage
TypeScript changes in web/src/woodPanelingInit.ts:
- Add page detection to prevent wood paneling on collections page
- Check if #collections-container exists in DOM
- Only apply wood paneling on dashboard, not collections page
- Prevents ID collision between dashboard and collections containers
Template changes in templates/header.templ:
- No functional changes, only reformatting
These fixes ensure that:
1. Wood paneling displays consistently across the entire viewport
2. Wood paneling extends into the overscroll area when scrolling past content
3. Wood paneling is properly aligned and centered
4. Wood paneling doesn't interfere with collections page rendering
5. Both dashboard and collections pages can coexist without visual conflicts
Fix multiple issues with dashboard customization modal and slider
not working correctly per library.
Frontend changes in web/src/dashboard.ts:
- Fix openDashboardSettings() to use current library ID
- Add library_id parameter to dashboard preferences API call
- Show toast error message on API failure instead of opening modal
- Prevent opening modal with stale/inaccurate data
- Fix slider query parameter mismatch
- Change from 'libraryId' to 'library_id' to match backend API
- Fix DOM query from collectionList.querySelector to document.querySelector
- Ensure slider targets correct input element
- Fix saveDashboardSettings() to refresh current library
- Fetch current library data before saving preferences
- Use library_id from current library, not from URL
- Show toast error message on save failure
- Keep modal open on error for user to retry
- Add localStorage persistence for selected library
- Store selectedLibrary in localStorage after switching
- Enables persistence across page refreshes
- Improve switchLibrary() with fade transitions
- Add fade-out (150ms) before data fetch
- Add fade-in (300ms) after rendering new library
- Provide smooth visual feedback during library switches
- Apply preferences dynamically to modal
- Use applyPreferencesToModal() to update slider and toggles
- Ensure modal reflects current library's settings
Backend changes in internal/router/dashboard.go:
- Update GetDashboardPreferences to use library_id query parameter
- Matches frontend API call parameter naming
Template changes in templates/dashboard.templ:
- Remove duplicate renderDashboardCollections() inline script
- Functionality now handled by dashboard.ts
These fixes ensure that:
1. Dashboard settings work correctly per library
2. Slider reflects and updates the correct library's item limit
3. Toggles show accurate visibility state for each library
4. Library switches provide smooth visual feedback
5. Errors are properly surfaced to users via toast messages
- Convert indentation from 4 spaces to 2 spaces (matching project style)
- Standardize quotes to double quotes for consistency
- Reformat template literals for improved readability
This file contains the core bookshelf functionality including:
- Library selection and persistence
- Book rendering with cover images
- Pagination for large book collections
- Send force: true in scan API request body
- Rename 'Scan Library' button to 'Rescan Library'
- Replace Settings card with Watch Status display
- Add loadWatchStatus() to fetch and display watch mode status
- Remove inline script from admin.templ (moved to admin.ts)
Features:
- Complete dashboard redesign with improved UI components and layout
- Implement custom section builder for personalized book organization
- Add new events tracking system for user interactions
- Enhance search functionality with better static search.js
- Update TypeScript type definitions for API responses
Backend:
- Update Go dependencies in go.mod
- Add new frontend routes in router
Templates:
- Update admin and dashboard templates with new components
Frontend:
- Refactor analytics, collections, conflicts, and queue modules
- Add new documentation features in docs.ts
- Implement linking between books and collections
- Add toast notifications for user feedback
- Include placeholder book SVG asset
This commit consolidates multiple feature additions and improvements
across the entire stack including backend, templates, and frontend.
- Fix View All link flashing by preserving data-wood attribute when dashboard re-renders
- Update wood-dark text color to match wood-mahogany (#f5f5f5) for better consistency
- Add smart link colors for wood paneling (#0066cc for light wood, #66ccff for dark woods)
- Fix carousel arrow gradients to be less harsh on wood backgrounds (0.6 for light, 0.3 for dark)
- Remove accent color preservation rule that was conflicting with wood-specific link colors
- Add data-wood attribute to collections container for CSS targeting
- Update woodPaneling.ts and woodPanelingInit.ts to set/remove attribute
- Add CSS variables for wood-specific text colors (dark text on light wood, light text on dark wood)
- Add !important rules to override theme colors when wood is active
- Replace wood-dark and wood-mahogany textures with darker variants
- Add subtle borders to book cards on wood backgrounds
- Fix library edit form to use type_name instead of library_type_id for type dropdown
- Clear library-id input after successful delete to prevent create-then-delete bug
- This fixes the issue where creating a new library after deleting one would fail with 'Unknown error' due to stale library-id
- Create themeDropdown.ts to manage active state highlighting
- Show which theme/wood option is currently selected
- Use CSS classes instead of inline styles for indicators
- Wrap existing functions to update indicators on toggle
- Auto-initialize indicators on DOM ready
- Add woodPaneling.ts with localStorage-based paneling preferences
- Add woodPanelingInit.ts for early initialization (prevents flash)
- Support none, wood-light, wood-dark, wood-mahogany options
- Apply paneling to #collections-container only (not full body)
- Use Tailwind utility classes for backgrounds
- Use CSS variable classes for active indicators
- Export functions for HTML onclick handlers
- Auto-initialize on DOM ready
- Remove wood-light, wood-dark, wood-mahogany from ThemeType
- Remove wood theme gradient logic from applyTheme()
- Wood themes will be reimplemented as separate paneling feature
- Paneling will target dashboard bookshelf background only
-- Add dedicated delete confirmation modal to admin/library page
-- Refactor deleteLibrary() to use modal instead of inline confirm()
-- Add showDeleteModal(), hideDeleteModal(), confirmDeleteLibrary() functions
-- Modal displays clear warning about what gets deleted
-- Improves UX by making the confirmation dialog more prominent and informative
- Add optional data parameter to apiDelete() with generic type safety
- Enables DELETE requests with request bodies (needed for folder deletion)
- 100% backward compatible (optional parameter)
- Supports type-safe request body passing
Part of: Issue 1
- Reuse Create Library modal for edit mode
- Add hidden library-id input to track create vs edit
- Update handleCreateLibrarySubmit to detect mode and use PUT vs POST
- Implement editLibrary() to populate modal with existing data
- Pass library data to Edit button via data attributes
- Reset modal title when opening for create mode
Fixes: Issue 3
- Add password requirements checklist with visual indicators (✓/○)
- Implement real-time validation for length, case, numbers, special chars
- Add confirm password field with matching validation
- Disable submit button until all requirements are met
- Add TypeScript client-side validation with password manager compatibility
Phase 10.5.1: Add /custom-section frontend route
- Added route handler in internal/router/frontend.go
- Fetches user libraries and renders custom section builder template
Phase 10.5.2: Create custom section builder template
- Created templates/custom_section.templ with full UI
- Includes section details form, filter rules builder, manual book selection
- Live preview functionality with preview container
- Form actions for save/cancel
Phase 10.5.3: Create custom-section-builder TypeScript
- Created web/src/custom-section-builder.ts with 13+ filter fields
- Filter fields: title, author, genre, series, progress, rating, date_added, last_read, publisher, language, format, tags, narrators
- Procedural/imperative style (no OOP) as per guidelines
- Rule builder with AND/OR logic support
- Book search and multi-select functionality
- Live preview via /api/collections/preview endpoint
- Form validation and submission to /api/collections
Phase 10.5.4: Build TypeScript modules
- Compiled custom-section-builder.ts to web/static/custom-section-builder.js
- Verified successful compilation with no errors
- All existing TypeScript modules continue to compile
Phase 10.5.5: Add Bruno tests for custom section creation
- create-custom-section-rules.bru: Test creating section with filter rules
- create-custom-section-manual.bru: Test creating section with manual book selection
- create-custom-section-missing-fields.bru: Test error handling for missing required fields
Phase 10.6: Build Verification
- ✅ TypeScript modules compile successfully
- ✅ Templates generate successfully
- ✅ Go build succeeds with no compilation errors
- ✅ All build artifacts verified (dashboard.js, custom-section-builder.js, dashboard_templ.go, custom_section_templ.go)
This completes the Custom Section Builder feature, allowing users to create
personalized dashboard sections with flexible filter rules or manual book selection.
Replace library browser with Carousel-style collections carousel:
Template Changes (templates/dashboard.templ):
Complete rewrite from library browser to collections carousel:
1. Dashboard Main Template:
- Sticky library selector dropdown
- Customize dashboard button (settings modal)
- Refresh button
- Loading spinner for async operations
- Collections container with carousels
2. CollectionCarousel Component:
- Collection header with icon, title, description
- View All link for system collections
- Horizontal scrollable carousel track
- Left/right navigation buttons
- Book cards with cover images
- Empty state handling
3. BookCard Component:
- Aspect ratio [2/3] book cover
- Cover image with fallback to placeholder
- Title and author display
- Click handler for viewing book details
- Hover scale animation
4. DashboardSettingsModal Component:
- Draggable collection list for reordering
- Toggle switches for collection visibility
- "System" badges for system collections
- "Restore" buttons for system collections
- Items per section slider (10-50, step 5)
- Save/Cancel buttons
Template Features:
- Uses IsSystem boolean instead of Type string
- data-is-system attribute for JavaScript
- data-collection-id for DOM manipulation
- Supports drag-and-drop reordering
- Settings modal with live preview
TypeScript Implementation (web/src/dashboard.ts):
Core Functions:
- scrollCarousel: Smooth horizontal scrolling
- openDashboardSettings/closeDashboardSettings: Modal control
- toggleCollectionVisibility: Toggle visibility switches
- saveDashboardSettings: Save preferences to API
* Collects hidden_collections and collection_order
* Calls PUT /api/dashboard/preferences
* Reloads page on success
- restoreSystemCollection: Reset system collection to defaults
* Confirmation dialog
* Calls POST /api/dashboard/restore-system-collection
* Shows toast notifications
- switchLibrary: Switch between libraries
* Async fetch from API
* Re-renders collections
- renderCollections: Client-side rendering of collections
- renderBookCard: Generate book card HTML
- viewBook: Placeholder for book detail view
- reloadPage: Refresh page
- updateItemsCount: Update slider display
- initDragAndDrop: Drag-and-drop event handlers
Event Handling:
- Event delegation for performance
- data-action attributes for handler routing
- Proper type checking and null safety
- Error handling with toast notifications
Type Safety:
- Uses SectionData and BookInfo from api.d.ts
- Proper TypeScript types throughout
- Null checks for DOM elements
- Type assertions where needed
This implements Phase 9: Dashboard Template with unified collections terminology and full TypeScript interactivity.
- Update fetch interceptor to special-case 401 responses
- Clear invalid tokens from localStorage on 401 (token, refreshToken, user)
- Distinguish between page navigation and API calls:
- Page navigation: throw error to prevent further processing
- API calls: show toast error with session expired message
- Suppress network error toast for redirect errors
- Compile TypeScript to JavaScript
This ensures frontend properly handles expired sessions by clearing
stale credentials and showing appropriate error messages.
- Add Bearer token from localStorage to regenerate-token API request
- Update code formatting for consistency (double quotes, indentation)
This ensures the device token regeneration endpoint receives proper
authentication via the Authorization header.
- Add handler to regenerate device auth tokens
- Add PUT /api/devices/:id/regenerate-token route
- Returns new token and sync URLs for device configuration
- Add header.templ component with app title, search, theme switcher, user menu
- Implement dropdown menus for theme selection and user actions
- Add wood theme options (Wood Light, Wood Dark, Wood Mahogany)
- Support all existing themes with visual color swatches
- Auto-close dropdowns when clicking outside
- TypeScript header functionality with proper type safety
Features:
- Left: App title "📚 Bookmann" linking to /bookshelf
- Center: Search box (ready for future search functionality)
- Right: Theme switcher button with color dropdown → User icon menu
- User menu includes Settings, Admin Panel (if admin), and Logout
- Theme persistence to localStorage and server via API
- Change from htmx:beforeSwap to htmx:afterSwap event for better error timing
- Simplify event listener setup (removed duplicate handlers)
- Remove 'export {}' statement that was causing syntax errors
- Add proper TypeScript interface for HTMX event details
- Errors now detected after content swap, ensuring accurate error messages
- Toast notifications work correctly for all backend HTTP errors
Resolves JavaScript syntax error on page load and improves error handling.
- Create web/src/ for TypeScript source files
- Create web/static/ for compiled assets and runtime files
- Move input.css and style.css to web/static/
- Add toast.ts - Functional toast notification system
- Add theme.ts - Functional theme management system
- All code uses functional programming (no classes, no OOP)
- TypeScript provides full type safety
Separates frontend code from backend for better organization.