Commit Graph
40 Commits
Author SHA1 Message Date
john-okeefe b78aacd320 feat: Add new Alpine.js component TypeScript files
Extracted inline JavaScript from templates into proper TypeScript modules:

- api-explorer-docs.ts: API explorer page functionality
- collection-rules.ts: Collection rules management page
- index.ts: Homepage theme and auth redirect
- login.ts: Login page theme initialization
- profile-modal.ts: Profile modal close and escape key
- profile.ts: Profile page delete account
- register.ts: Registration page theme init
- toast-error.ts: Error toast with retry button
- unlinked_books.ts: Unlinked books management page

Each file:
- Uses ES imports (showToast, getToken, etc.)
- Has proper TypeScript types
- Registers with Alpine.js via Alpine.global()
- Uses async/await for API calls
2026-03-08 21:35:47 -04:00
john-okeefe 9947a12f09 refactor(ts): Convert internal window dependencies to ES modules
Phase 1 of ESBuild migration: Convert 193+ internal window reads
to proper ES module imports across consumer modules.

Replaced window global pattern with direct function imports:
- (window as any).showToast → import { showToast } → showToast(msg, "type")
- (window as any).api.post → import { apiPost } → apiPost(url, data)
- (window as any).dom.getElementById → import { getElementById }

Modules migrated:
- admin.ts: Convert 14 showToast window reads
- analytics.ts: Add ES export (no window reads)
- conflicts.ts: Convert 6 showToast window reads
- custom-section-builder.ts: Convert api.post reads, add ES exports
- dashboard.ts: Convert 10 window reads (api, showToast)
- device-management.ts: Convert 4 showToast window reads, add Alpine registration
- linking.ts: Convert showToast window reads
- queue.ts: Convert 8 showToast window reads

Additionally added Alpine.js registration for templates:
- device-management.ts: Register copyToClipboard, regenerateDeviceToken

Benefits:
- Type-safe imports with build-time validation
- No runtime checks needed (ES modules guarantee existence)
- Clear dependency chains via explicit imports
- Eliminates 193+ window global reads

Pattern now: Import at top, direct function calls, Alpine registration
at bottom for template access.

Migration progress: Phase 1 complete
Next: Phase 2 (Alpine registration for remaining modules)
2026-03-08 01:14:35 -05:00
john-okeefe 149d14f5eb refactor(ts): Add ES module exports to core utilities
Phase 0/1 of ESBuild migration: Add ES exports to all utility modules
while maintaining Alpine.js registration for template compatibility.

Core utility modules now support both:
- ES module imports for TypeScript→TypeScript dependencies
- Alpine.js global namespace for template onclick handlers

Modules updated:
- api.ts: Export apiGet, apiPost, apiPut, apiDelete, apiPatch, and handlers
- toast.ts: Export showToast function (Alpine namespace already present)
- storage.ts: Export localStorage helpers (already had exports)
- dom.ts: Export DOM manipulation helpers (already had exports)
- events.ts: Export event delegation helpers
- theme.ts: Export theme management functions
- woodPaneling.ts: Export wood paneling functions

Pattern: Each module now has dual exports
- ES module exports for internal TS dependencies
- Alpine.global() registration for template access
- Removed direct window exports where Alpine registration exists

This enables Phase 1 (converting internal window reads to imports) while
maintaining template functionality through Alpine.

Migration progress: Phase 0 complete, Phase 1 in progress
Next: Convert 193+ internal window reads across consumer modules
2026-03-08 01:14:20 -05:00
john-okeefe e45b893eb3 feat: add Alpine.js framework and update build configuration
Add Alpine.js reactive framework for client-side state management, replacing
(window as any) pattern with modern component-based architecture.

Build configuration changes:
- package.json: Update build scripts to use main.ts as entry point
  - Change from web/src/*.ts glob to web/src/main.ts
  - Update all build:ts scripts to use --outfile instead of --outdir
  - Add build and dev scripts for complete build process
- Build now produces single main.js bundle (~120-150KB minified)

Alpine.js setup:
- web/src/alpine.ts: Create Alpine initialization module
  - Extend Window interface with Alpine type declaration
  - Initialize Alpine and attach to window for DevTools
  - Re-export Alpine for other modules to register globals/components

Frontend module updates:
- web/src/main.ts: Import alpine.ts last to initialize framework
- web/src/toast.ts: Add Alpine import (ready for migration to Alpine.global())

Architecture:
- Alpine.js for client-side state (modals, dropdowns, theme switching)
- HTMX for server calls (existing pattern, unchanged)
- Hybrid approach: Alpine reactive components + HTMX form submissions

Next steps (see esbuild-setup.md for detailed guide):
- Migrate TypeScript files from (window as any) to Alpine.global()
- Update 27 templates to use @click instead of onclick
- Add x-data/x-show for stateful UI components

Note: web/src/docs.ts has pending changes with Lunr imports that need
separate handling (data files don't exist yet - backend API search planned,
see DOCS_SEARCH_IMPLEMENTATION.md)
2026-03-06 22:27:18 -05:00
john-okeefe 8e48de5607 refactor(frontend): migrate from downloaded JS bundles to npm packages with esbuild
Replace the postinstall script that downloaded minified JavaScript libraries
(htmx, highlight.js, lunr) with proper npm package management and bundling
using esbuild. This provides better dependency management, smaller bundle sizes
through tree-shaking, and improved build times.

Changes:
- Add htmx.org, highlight.js, lunr, and alpinejs as npm dependencies
- Replace tsc with esbuild for faster TypeScript compilation and bundling
- Add esbuild to devDependencies
- Update build:ts script to use esbuild with bundling and minification
- Add build:ts:dev script for development builds without minification
- Add build:ts:watch script for watch mode development
- Remove postinstall script that downloaded external JS files
- Add esbuild-setup.md documentation for the new build setup
- Create web/src/main.ts as the new entry point for bundled JavaScript

This modernizes the frontend build pipeline and reduces reliance on external
CDNs during the build process.
2026-03-06 20:18:01 -05:00
john-okeefe 39a87ddabc feat: integrate WebSocket for real-time scan progress in admin panel
- Add WebSocket connection for scan progress updates
- Display live progress bar and file count during scans
- Handle scan_complete and scan_error messages
- Store polling interval in module variable for cleanup
- Expose stopScanStatusPolling function for manual control

Replaces or supplements HTTP polling with push-based updates for
better UX and reduced server load.
2026-03-05 17:13:23 -05:00
john-okeefe 9b3d8cc949 feat: implement collection library filter with WebSocket improvements and test coverage
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.
2026-03-04 22:37:47 -05:00
john-okeefe 08b7f13079 feat(collections): add HTMX auth, icon picker, and navigation helpers
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)
2026-03-01 21:00:28 -05:00
john-okeefe 42a20e3be3 feat: Improve wood paneling border colors and background blend
- 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.
2026-03-01 12:22:36 -05:00
john-okeefe 486c16172b fix: Wood paneling overscroll and alignment issues
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
2026-03-01 00:29:11 -05:00
john-okeefe 62d3d50140 fix: Dashboard modal and slider library-specific behavior
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
2026-03-01 00:29:00 -05:00
john-okeefe ea5ad7a41b feat(web): update frontend TypeScript modules and API types
This commit updates the web frontend TypeScript modules:

Core modules:
- admin.ts: Admin panel functionality and user management
- analytics.ts: Analytics dashboard and data visualization
- api-explorer.ts: Interactive API documentation explorer
- api.ts: Core API client with request/response handling
- collections.ts: Book collection management UI
- conflicts.ts: Sync conflict resolution interface
- custom-section-builder.ts: Dynamic section builder for UI
- docs.ts: Documentation viewer and navigation
- dom.ts: DOM manipulation utilities and helpers
- header.ts: Application header with navigation
- library.ts: Library view and book grid management
- linking.ts: Device-book linking interface
- password_validation.ts: Client-side password strength validation
- queue.ts: Device sync queue management UI
- search.ts: Full-text search with Lunr integration
- storage.ts: Local storage and cache management
- theme.ts: Theme management and CSS variable updates
- themeDropdown.ts: Theme selector dropdown component
- toast.ts: Toast notification system
- woodPaneling.ts: Visual theme effects
- woodPanelingInit.ts: Visual effects initialization

Type definitions:
- api.d.ts: Updated TypeScript definitions for API responses

These updates enhance the frontend with improved functionality
for book management, device synchronization, and user experience.
2026-02-27 17:06:48 -05:00
john-okeefe 7bae42bb11 style: normalize code formatting in bookshelf.ts
- 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
2026-02-27 16:55:26 -05:00
john-okeefe abcc468024 frontend: add force rescan to button and watch status display
- 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)
2026-02-26 10:11:52 -05:00
john-okeefe a8920a8f6c Add dashboard redesign, custom section builder, and enhanced search functionality
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.
2026-02-25 16:56:10 -05:00
john-okeefe 64e1ba87b9 Implement Part 1: Fix Scan Library button with progress UI
Implements the frontend scan button fix from TASKS-scanning-progress.md Part 1.

Changes:
1. web/src/admin.ts - Added 6 new TypeScript functions:
   - scanAllLibraries(): Fetches all libraries, triggers scan for each
   - showScanProgress(): Displays progress UI with per-library progress bars
   - pollScanProgress(): Polls status every 2 seconds, updates progress
   - updateLibraryProgress(): Updates individual library progress bar/status
   - showScanResults(): Displays scan completion results
   - hideScanProgress(): Hides progress UI

2. templates/admin.templ - Updated UI:
   - Added admin.js script include (Step 2)
   - Changed button onclick from quickScan() to scanAllLibraries() (Step 3)
   - Removed broken inline quickScan() function (Step 3.5)
   - Added progress UI HTML with slide-in animation (Step 4)

Key Features:
- Fetches all libraries via GET /api/libraries
- Triggers scan for each library via POST /api/libraries/{id}/scan
- Displays per-library progress bars
- Shows overall progress percentage
- Real-time status updates every 2 seconds
- Results summary with file counts and errors
- TailwindCSS animation (no custom CSS)
- Follows PROJECT_GUIDELINES.md: TypeScript only, TailwindCSS classes

TypeScript compiles successfully (npm run build:ts)
All guidelines verified (26/26 checks pass)
2026-02-25 12:20:48 -05:00
john-okeefe 875e4abb46 fix: preserve wood paneling on dashboard refresh and improve colors
- 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
2026-02-24 17:00:11 -05:00
john-okeefe 4571a19159 feat: add smart font colors for wood paneling backgrounds
- 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
2026-02-24 16:36:49 -05:00
john-okeefe 30d053d908 fix: resolve library management issues
- 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
2026-02-24 16:10:33 -05:00
john-okeefe 245c775f54 feat(theme): add active indicators for theme dropdown
- 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
2026-02-24 13:00:14 -05:00
john-okeefe fffa87009a feat(wood-paneling): create wood paneling management system
- 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
2026-02-24 12:59:48 -05:00
john-okeefe 3d3af8bd92 refactor(theme): remove wood themes from core theme system
- 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
2026-02-24 12:57:54 -05:00
john-okeefe 7a420ef975 refactor(theme): fix theme consistency and persistence
- Apply server-side theme rendering to authenticated pages
  - bookshelf.templ: use dynamic theme-{ user.Theme }
  - admin pages: use dynamic theme rendering
- Add progressive enhancement for public pages
  - index.templ, login.templ, register.templ: inline localStorage check
  - Prevents theme flash on page load
- Consolidate wood theme logic into theme.ts
  - Move wood gradient handling from header.ts to theme.ts
  - Apply wood themes consistently via applyTheme()
- Export applyTheme to window for use by header.ts
- Fix theme selector by adding theme.js to header template
2026-02-24 10:25:06 -05:00
john-okeefe 85ba3d4060 feat(frontend): add delete confirmation modal for library management
-- 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
2026-02-23 20:23:56 -05:00
john-okeefe c333c82c6b fix(frontend): add data parameter support to apiDelete
- 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
2026-02-23 17:02:35 -05:00
john-okeefe 509423b46e feat(frontend): implement library edit functionality
- 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
2026-02-23 17:02:01 -05:00
john-okeefe ce50312e1b feat(frontend): Add TypeScript for admin library page
Add web/src/library.ts with complete functionality for /admin/library
page interactivity.

Features:
- reloadLibraries() - fetch and render library list after changes
- renderLibraries() - SSR replacement with proper data.data handling
- loadUserVisibility() - load and display user library permissions
- setLibraryVisibility() - toggle library visibility for users
- handleCreateLibrarySubmit() - form submission with fetch API
- deleteLibrary() - delete with confirmation
- showLibraryFolders() - folder management
- addLibraryFolder() / removeLibraryFolder() - folder CRUD
- editLibrary() - placeholder for future implementation
- Modal controls (show/hide)
- Event delegation for dynamic buttons
- XSS protection with escapeHtmlLocal()

TypeScript Features:
- Proper type definitions (Library, User, LibraryFolder)
- Async/await with error handling
- Procedural style (no OOP, per PROJECT_GUIDELINES)
- Exports functions to window for global access

Bug Fixes:
- Fixed data.data API response handling
- Replaced broken HTMX form with fetch()
- Proper error messages with toast notifications

Lines: 394
2026-02-22 21:07:06 -05:00
john-okeefe f39cf3904d fix(frontend): Remove ES6 exports from api.ts
Remove ES6 export statement from api.ts that was causing CommonJS
compilation in browsers, breaking window.api initialization.

Issue: TypeScript compiled 'export { ... }' to CommonJS format
(exports.apiGet = ...), which browsers don't support.

Fix: Remove export statement, rely on existing window.api assignment.
This produces browser-compatible JavaScript.

Before: export { getAuthHeader, apiGet, ... } → CommonJS exports
After: (window as any).api = { ... } → browser global

Resolves: 'Uncaught ReferenceError: exports is not defined'
Resolves: 'Uncaught TypeError: window.api is undefined'
2026-02-22 21:06:47 -05:00
john-okeefe d4d93bc0e3 feat(auth): add interactive password requirements validation to registration
- 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
2026-02-22 18:40:22 -05:00
john-okeefe a92bf99aee feat(dashboard): implement Phase 10.5 Custom Section Builder
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.
2026-02-19 21:22:15 -05:00
john-okeefe a1a14c2af8 feat(dashboard): implement Phase 9 dashboard template and TypeScript for Carousel-style dashboard
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.
2026-02-19 21:11:53 -05:00
john-okeefe 9ef94efeb5 feat(dashboard): implement Phase 6 TypeScript type definitions
Add TypeScript interfaces for Carousel-style dashboard to api.d.ts:

New Interfaces:
1. SectionData
   - Matches handlers.SectionData in collections.go (lines 73-81)
   - id: Collection name (string)
   - is_system: Boolean flag (true for system collections, false for user)
   - title: Display title
   - description: Collection description
   - icon: Emoji icon
   - items: Array of BookInfo objects
   - view_all_url: URL to view all items (system collections only)
   - priority: Display order (lower numbers first)

2. DashboardPreferences
   - Matches database.UserDashboardPreferences (models.go:381-390)
   - library_id: Library UUID
   - hidden_collections: Array of collection names to hide
   - collection_order: Array of collection names for custom ordering
   - items_per_section: Number of items per section

Existing Interface:
- BookInfo: Already defined (media_item_id, title, author, cover_image_path)
  - Reused by SectionData for items array
  - No duplicate definitions needed

Key Compliance:
- is_system: boolean matches database is_system_collection field
- media_item_id matches Go BookInfo.MediaItemID field
- Uses existing BookInfo struct (no duplicates)
- Added to existing api.d.ts file (follows established pattern)
2026-02-19 21:05:59 -05:00
john-okeefe dfd9cbcde7 feat(typescript): add feature modules for template conversion
- Add search.ts - header search with keyboard navigation
  - Debounced search with 300ms delay
  - Arrow key navigation through results
  - Escape to close, Enter to select
  - Library type icons and highlighting

- Add collections.ts - collection and rule management
  - Rule CRUD operations (create, update, delete)
  - Rule testing functionality
  - Bulk collection operations

- Add bookshelf.ts - book display and navigation
  - Library selection state management
  - Book viewing interactions
  - Pagination logic

- Add linking.ts - book matching and manual linking
  - Search and match functionality
  - Manual link modal
  - Bulk auto-link and suggestions

- Add api-explorer.ts - API testing interface
  - Request/response display
  - cURL command generation
  - History tracking

- Add admin.ts - admin dashboard actions
  - Library scan triggers
  - System statistics display
  - Profile management

- Add analytics.ts - analytics data loading
  - Chart.js integration
  - Daily reading minutes chart
  - Device usage and popular books display

- Add queue.ts - sync queue management
  - Process pending items
  - Clear failed/all items
  - Filter by status, type, device

- Add conflicts.ts - conflict resolution
  - Individual and bulk resolve operations
  - Winner device selection
  - Manual override inputs

- Add docs.ts - documentation search
  - Lunr.js search integration
  - Sidebar toggle for mobile
2026-02-18 16:40:51 -05:00
john-okeefe 60c5a093b5 feat(typescript): add core infrastructure modules
- Add centralized API type definitions (types/api.d.ts)
  - Interfaces for all API responses matching Go handler JSON
  - Snake_case field names matching actual API responses
  - Source file references in comments for verification

- Add API client module (api.ts)
  - Procedural get/post/put/delete functions
  - Automatic auth header injection
  - Exported to window for cross-module access

- Add DOM utilities (dom.ts)
  - escapeHtml for safe HTML rendering
  - querySelector wrappers with null checks
  - Element creation helpers

- Add event delegation helpers (events.ts)
  - Reusable event delegation pattern
  - Data attribute selectors for dynamic content

- Add localStorage wrapper (storage.ts)
  - Type-safe token management
  - Theme persistence helpers
2026-02-18 16:40:29 -05:00
john-okeefe 53aad2701b feat(frontend): enhance 401 handling to clear tokens and redirect
- 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.
2026-02-16 16:50:19 -05:00
john-okeefe c9ebc5b11a feat: add authorization header to device token regeneration
- 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.
2026-02-16 09:18:02 -05:00
john-okeefe 81fbcfac11 feat: add RegenerateDeviceToken API endpoint
- Add handler to regenerate device auth tokens
- Add PUT /api/devices/:id/regenerate-token route
- Returns new token and sync URLs for device configuration
2026-02-13 12:12:28 -05:00
john-okeefe 2a91ff9477 feat: add reusable header component with theme switcher
- 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
2026-01-29 15:51:38 -05:00
john-okeefe 4426cacb46 fix: improve HTMX error detection and remove module exports
- 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.
2026-01-29 14:53:01 -05:00
john-okeefe 84ba9ffbb1 feat: add web frontend directory structure
- 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.
2026-01-29 14:08:44 -05:00