strings.Title has been deprecated since Go 1.18 because it does not
handle Unicode properly. Replace it with cases.Title from
golang.org/x/text which correctly handles language-specific title
casing. Applied to breadcrumb generation and document title formatting.
Simplify pointer creation in media scanner validation messages and worker
job timestamps by using inline new() instead of local variable + address-of.
In media_scanner.go this cleans up three validation error message returns
(manga/comics library format checks). In worker.go it simplifies StartedAt
and CompletedAt timestamp assignments.
Simplify pointer creation across kobo, koreader, and queue handlers by
replacing the two-step pattern (assign to local, then take address) with
inline new() calls. This reduces verbosity without changing behavior:
Before:
remaining := int(a - b)
pagesRemaining = &remaining
After:
pagesRemaining = new(int(a - b))
Covers page calculations, chapter/progress fields, UUID formatting,
and timestamp string conversions.
Replace the original 5-theme allowlist (light, sepia, dark, night,
high-contrast) with a richer 20-theme palette organized into tonal
families: neutrals (light, paper, slate, oled), warm tones (sepia,
parchment, warm, candlelight), cool tones (azure, sky, arctic, frost),
and evening tones (dusk, sunset, twilight, forest, moss, solarized).
The backend validator in UpdateSettings now accepts all 20 theme names,
and the frontend Tailwind build is updated to include the new theme CSS
variables and preflight reset.
Major rewrite of the web reader to properly interface with
@bookhoard/foliate-js, replacing the abandoned panel-detection
architecture with direct pan and zoom support built into the
foliate-js FixedLayout renderer.
Template (reader.templ):
- Fix critical bug: x-init config was using literal strings
'{ readerData.X }' inside a quoted attribute, which templ
treated as raw text and never interpolated. Values were never
actually passed to JavaScript. Now uses fmt.Sprintf() with
templ's expression attribute syntax ={ }.
- Pass fileUrl from server so foliate-js can open books directly.
- Redesign bottom bar with foliate-js parity: left/right navigation
buttons, progress slider with tick marks, and zoom controls
(zoom out, percentage display, zoom in, magnifier, pan/select
mode toggle for PDFs).
- Remove panel editor button and enablePanelDetection config.
- Add SVG icon styles for consistent reader controls.
Go types (templates/types.go):
- Expand ReaderMetadata with FormatGroup, MangaType,
ReadingDirection, FileURL, and LibraryID fields needed by
the reader frontend.
Router (internal/router/reader.go):
- Populate new ReaderMetadata fields from database values.
- Construct FileURL from library ID and file path for the
/uploads/library-{id}/* file serving route.
Reader JS (reader.ts):
- Full rewrite modeled on foliate-js Reader class, adapted for
Alpine.js. Opens books via view.open(fileUrl), accesses
view.renderer for zoom/pan/navigation, and wires up keyboard
shortcuts (+/-/0 for zoom, arrows for nav, Escape for magnifier).
- Uses view.isFixedLayout instead of importing FixedLayout class,
avoiding a TypeScript module resolution issue with the Vite alias.
Settings manager (settings-manager.ts):
- Remove dependency on deleted ReaderContext event bus.
- Export loadSettings/saveSettings/syncSettings directly as
standalone async functions.
Cleanup:
- Delete reader-context.ts and reader-events.ts (over-engineered
event system replaced by direct function calls).
- Remove panel_zoom_enabled from ReaderSettings type.
Apply Go 1.18+ language features and modern style:
internal/services/collection_service.go:
- Use map[string]any instead of map[string]interface{} (Go 1.18+)
- Use range clause with single variable for iteration-only loops
- Replace if-else chains with switch statements for better readability
- Remove explicit type initialization for zero values
internal/services/filters.go:
- Add Err prefix to custom error variable for error naming convention
internal/router/library.go:
- Use cfg.ProcessingIssuesHandler instead of local processingIssuesHandler variable
- Ensures proper dependency injection through router config
These changes follow current Go best practices and improve code readability.
Add frontend route /admin/libraries/:id/issues to display processing issues
management page for a specific library.
internal/router/frontend.go:
- Register GET /admin/libraries/:id/issues with admin middleware
- Fetch processing issue stats from database
- List processing issues for the library
- Convert database models to template types
- Render AdminProcessingIssues template with issues and stats
This provides the admin UI for viewing and managing processing errors that
occur during media scanning and import workflows.
Wire up the ProcessingIssuesHandler throughout the application:
cmd/server/main.go:
- Remove obsolete commented-out getTemplateUserWithTheme function
- Instantiate ProcessingIssuesHandler with database queries
- Add handler to router Config (with field alignment cleanup)
internal/router/router.go:
- Add ProcessingIssuesHandler field to router Config struct
- Reformat Config struct for better field alignment
This enables the processing issues API endpoints for listing and getting
statistics about issues within libraries, integrated with the admin UI.
Fix ResolveProcessingIssue and DeleteProcessingIssue methods to use proper
parameter structs instead of individual arguments.
Changes:
- ResolveProcessingIssue: Use database.ResolveProcessingIssueParams struct
with ID and MediaItemID fields instead of separate arguments
- DeleteProcessingIssue: Wrap issueID in pgtype.UUID struct
- Use map[string]any instead of map[string]interface{} for JSON responses
These changes align with the sqlc-generated database interface and ensure
type-safe parameter passing to the database layer.
Add Go package documentation comments to clarify the purpose and scope of:
- internal/handlers/: HTTP request/response handlers for authentication,
libraries, media items, reading, collections, dashboards, devices,
analytics, and system features
- internal/services/: Core business logic layer including media scanning,
library management, search, analytics, and conversion services
These doc comments improve code discoverability and help developers understand
the architectural separation between HTTP handling (handlers) and business
logic (services).
- Add ProcessingIssuesHandler with List and GetStats methods
- Add AdminProcessingIssues template for issues dashboard
- Display error/warning/info stats cards
- Sort issues by severity and creation date
- Add dismiss functionality for warnings and info items
- Add navigate to media item functionality
- Show issue type, description, and media details
- Add GET /admin/libraries/:id/issues/list for listing issues
- Add GET /admin/libraries/:id/issues/stats for issue statistics
- Integrate processing issues handler with library routes
- Add shouldEnablePanelDetection to determine when to enable panel detection
- Enable for manga/comics libraries with fixed_layout or comic_archive formats
- Fetch library type info using GetLibraryWithType query
- Pass panel detection config to reader initialization
- Include format_group, manga_type, and reading_direction in reader response
- Add ProcessingIssues model struct
- Update Querier interface with processing issues methods
- Add generated query implementations for CreateProcessingIssue, ListProcessingIssuesByLibrary, GetProcessingIssueStats, ResolveProcessingIssue, DeleteProcessingIssue
- Add GetLibraryWithType query for fetching library with type information
- Add CreateProcessingIssue with upsert for recording/renewing issues
- Add ListProcessingIssuesByLibrary with severity ordering and media item details
- Add GetProcessingIssueStats for error/warning/info counts
- Add ResolveProcessingIssue for marking issues as resolved
- Add DeleteProcessingIssue for removing resolved issues
- Add GetLibraryWithType for fetching library with type info for validation
Remove unused Epubcfi and Percentage fields from UpdateReadingProgressParams
struct to align with the new foliate-js based reader implementation.
The foliate-js library handles CFI tracking and percentage calculation
internally, so these parameters are no longer needed in the update API.
The reader now relies on foliate-js's built-in progress tracking mechanisms.
This change aligns the database layer with the foliate-js integration completed
in commit c7a9098 (feat: Replace foliate-js submodule with npm git dependency).
Changes:
- Remove Epubcfi field from UpdateReadingProgressParams struct
- Remove Percentage field from UpdateReadingProgressParams struct
- UpdateReadingProgress function now uses simplified parameter set
Refactor UpdateMediaReadingProgress handler to use UpdateUniversalProgress
database function, providing comprehensive progress tracking capabilities
including device sync information, viewport data, reading mode, and scroll
position for enhanced cross-platform reading synchronization.
Enhance reading progress tracking to support EPUB-specific location data:
- Add epubcfi field to store EPUB Canonical Fragment Identifier
- Add percentage field for normalized position across formats
- Update UpdateReadingProgress API handler to accept new fields
- Modify database queries to persist additional progress metadata
This enables precise position tracking in reflowable EPUB content
where page numbers are insufficient for accurate bookmarking.
- Add library_type_name to GetMediaItem handler response in media.go
- Remove empty LibraryName and LibraryTypeName fields from:
- ListMediaItemsRow in collections.go handler
- ListMediaItemsRow in dashboard_service.go
- These fields are now populated at the database level via trigger
The library_type_name is now automatically populated in the database
when a media item is created, so we remove the manual empty string
assignments and expose the actual value in the API response.
- Add library_type_name VARCHAR(50) column to media_items table in schema.sql
- Create PostgreSQL trigger 'set_library_type_name_on_insert' that automatically
populates library_type_name by joining libraries table with library_types on insert
- Add library_type_name parameter to CreateMediaItem SQL query
- Update Go models (models.go) to include LibraryTypeName field
- Add UpdateMediaItemChapterMetadata query method to querier.go
- Regenerate queries.sql.go with sqlc
This allows media items to store their library type (e.g., 'Books', 'Comics', 'Manga')
at the database level, enabling filtering and display without needing additional joins.
- templates/reader.templ: add script tag to load main.js
- Enables reader shell and Alpine components to initialize
- internal/handlers/reader.go: add GetMediaReadingProgress handler
- Backend now supports fetching reading progress via API
- GET /api/media-items/:id/progress returns current progress
- Fix function signatures in reader.go (c echo.Context -> c *echo.Context)
- Replace non-existent UserHasLibraryAccess with GetUserVisibleLibraries pattern
- Implement SSR reader route in router/reader.go with proper access control
- Add inline library access checking following existing codebase patterns
- Fix ReadingProgress struct to use LastReadAt instead of CreatedAt/UpdatedAt
- Ensure all reader endpoints use consistent library access validation
This provides the backend foundation for the reader feature with proper
access control and SSR rendering capabilities.
- Add panel_layout to getDefaultSettings() for dockable panels
- Remove template rendering from ShowReader (router handles SSR)
- Fix pgtype.Int4 marshaling to JSON (no explicit int conversion)
- Remove unused strings import from handlers
- Add modular dockable panel architecture with:
- Panel dock system (drag, lock, snap-back, window-shade)
- TOC, Settings, Navigator, Bookmarks as dockable components
- Lock toggle to prevent accidental moves
- Snap-back to last valid position if dropped in invalid area
- Per-user layout stored in reader_settings JSONB
- Update TypeScript types with PanelLayoutSettings and PanelState
- Add panel-dock-system.ts implementation to plan
- Add navigator-panel.ts for Affinity-style page navigation
- Update reader template with dockable panels and lock buttons
- Add Section 2.4 with database/Go implementation issues and fixes
- Document schema changes (DECIMAL -> REAL)
- Document all type fixes needed in reader.go
- Fix pgtype.UUID usage in test files by properly converting string UUIDs to pgtype.UUID
- Update numericToFloat to use pgtype.Float8 instead of pgtype.Numeric for DOUBLE PRECISION support
- Fix field name from WebURL to WebUrl to match current schema
These changes align with the recent community_rating type change to DOUBLE PRECISION
and ensure consistent type handling across the codebase.
Phase 6.1 implementation: Unit tests for metadata helper functions.
Test Coverage:
- TestNormalizeMangaType: Verify Manga field normalization to database enum values
(unknown, no, yes, yes_and_right_to_left)
- TestDetermineReadingDirection: Test reading direction computation heuristics
(explicit Manga field, Japanese language, webtoon/manhwa genre tags, Western default)
- TestNormalizeAgeRating: Verify age rating standardization
(Everyone, Teen, Mature, Adult with various input formats)
These tests ensure the helper functions correctly normalize ComicInfo.xml data
before storage in the database.
Relates to: Phase 6.1 unit testing
Implement SSR-first book detail page at /media/:uuid with complete
book information, progress tracking, and interactivity.
Features:
- Cover image (256x384px) with responsive layout
- Complete metadata: title, author, description, publisher, ISBN,
language, edition, page count, genre, copyright year, format
- External service links (Goodreads, Open Library, Google Books, Amazon)
with smart URL fallback: ID → ISBN → Title+Author
- Reading progress display with device sources (web/kobo/koreader)
- Sync progress modal for conflict resolution
- Collections display as clickable badges
- Notes/highlights counter with placeholder modal
- Rating display (1-10 scale with star rendering)
- HTML sanitization for book descriptions using bluemonday
Data Structure:
- handlers.MediaDetail embeds database.MediaItems for zero duplication
- Uses existing database queries (GetMediaItem, GetMediaRating, etc.)
- Follows project pattern: no parallel type systems
Frontend:
- TypeScript modal triggers (book-detail.ts)
- Alpine.js for modal interactions
- TailwindCSS styling with theme variables
- Responsive: cover-left layout, mobile stacks vertically
Backend:
- Route: GET /media/:uuid (protected)
- Handler: inline function in frontend.go following existing pattern
- Template: SSR-first with progressive enhancement
- Returns HTML only (API uses separate /api/media-items/:id endpoint)
Files created:
- internal/handlers/media_detail.go
- templates/book_detail.templ
- templates/book_detail_modals.templ
- web/src/book-detail.ts
Files modified:
- internal/router/frontend.go (add route)
- web/src/main.ts (import module)
Changed the 4 default system collection names from kebab-case to Title Case
with spaces for better readability and professional appearance:
Changes:
- "continue-reading" → "Continue Reading"
- "recently-added" → "Recently Added"
- "recently-read" → "Recently Read"
- "not-started" → "Not Started"
Implementation details:
- Collection Name field: Updated to Title Case (user-visible identifier)
- QueryType field: Unchanged, remains kebab-case (internal switch/case logic)
- All map keys updated to use new Title Case names as lookups
- Restore modal option values updated to match new names
Files modified:
- internal/handlers/auth.go: Default collection creation for new users
- internal/handlers/dashboard.go: Restore endpoint validation map
- internal/services/dashboard_service.go: System collection metadata map
- templates/restore_system_collection_modal.templ: Form option values
Benefits:
- Cleaner, more professional display names for end users
- Consistent with existing restore modal UI labels
- Improved user experience with properly formatted collection names
- Internal QueryType identifiers remain unchanged for code logic
Router changes for saved filters API:
- Add CreateFilterHTML handler to return HTML for HTMX requests
- Extract CreateFilterHTML function to handle filter creation logic
- Add wrapper for POST /api/saved-filters to detect HTMX requests
- HTMX requests: Return HTML via CreateFilterHTML
- Regular requests: Return JSON via existing handler
- Add collectFilterFormData helper to gather form data from #filter-form
- Improve error handling for duplicate filter names (409 Conflict)
- HTML responses include error messages for better UX
This enables the save filter modal to work without page refresh,
providing a smoother user experience with immediate visual feedback.
Database changes:
- Add unique index on saved_filters(user_id, name, resource_type)
Prevents duplicate filter names while allowing same name across
different users or different resource types
Search functionality fix:
- Remove DISTINCT ON (mi.id) from SearchMediaItemsUnified query
- Remove mi.id from ORDER BY clause (was required by DISTINCT ON)
- This allows user-selected sort field to be primary sort criteria
- Previously results were always sorted by ID first, making sort
dropdown ineffective
- Relevance score and title remain as fallback sorts
This fixes the sort dropdown functionality on the bookshelf page
where changing the sort option appeared to have no effect.
Updated the backend services and handlers to properly detect and pass
the has_cover parameter's validity state to the database layer.
Changes:
- services/search.go: Changed HasCover type from bool to pgtype.Bool
to support 3-state logic (NULL, TRUE, FALSE)
- handlers/media.go: Fixed 3-state detection by checking if has_cover
exists in query params before setting Valid flag
- router/search.go: Fixed 3-state detection to match media.go logic
- router/frontend.go: Use pgtype.Bool{Valid: false} for SSR initial
load to ensure no filtering occurs on first page load
The key fix is detecting whether the has_cover parameter was actually
sent in the request:
- Parameter not sent → pgtype.Bool{Bool: false, Valid: false}
- Parameter sent as "true" → pgtype.Bool{Bool: true, Valid: true}
- Parameter sent as "false" → pgtype.Bool{Bool: false, Valid: true}
Previously, media.go was hardcoding Valid: true, which meant it was
always filtering by has_cover=false (only books without covers) when
the parameter wasn't sent, causing searches to incorrectly return
0 results for queries like "1984".
This ensures consistency between the JSON API endpoint (media.go) and
the HTML endpoint (search.go), and fixes the critical bug where SSR
was returning 0 books on initial page load.
Fixed the SearchMediaItemsUnified query to properly handle the has_cover
parameter in three states:
- NULL (not specified): Show all books
- TRUE: Show only books with cover images
- FALSE: Show only books without cover images
Changes:
- Added explicit boolean casting (::bool) to sqlc.narg('has_cover')
to resolve PostgreSQL type inference error (SQLSTATE 42P08)
- Replaced single AND condition with OR'd logic to handle all three
states without mutual exclusion
- Used IS NULL check to detect when parameter is not specified
- Used IS TRUE/IS FALSE to explicitly check boolean states
The previous implementation had mutually exclusive AND conditions that
prevented any records from matching when has_cover was explicitly set
to TRUE or FALSE, causing the filter to block all searches.
This fix resolves the issue where searches were returning 0 results
regardless of other filter parameters when has_cover was included in
the query.
Replace direct database call with service layer to fix SSR
returning 0 books on initial page load.
Root Cause:
- SSR was calling cfg.Queries.SearchMediaItemsUnified directly
- API was using MediaHandler.ExecuteSearch via service layer
- Both code paths had different parameter structures
Solution:
- Use same MediaHandler.ExecuteSearch handler as API
- Build services.SearchParams struct (same as API path)
- Convert user.ID string to pgtype.UUID for service layer
- Remove unused books variable
Changes:
- Parse user.ID to UUID before building search params
- Build services.SearchParams with empty filters for SSR
- Call cfg.MediaHandler.ExecuteSearch instead of direct DB
- Use textToString helper (already exists in router package)
- Remove unused books variable declaration
Both SSR and API now use identical search logic, ensuring
consistent behavior. HTMX search continues working as before.
Fixes: Issue #1 - SSR returns 0 books on initial load
Related: Issue #2 - Search/filter returning JSON instead of HTML
Rewrite /api/media-items/search endpoint to detect HTMX requests and return appropriate response format. The endpoint now checks for HX-Request header and routes to HTML renderer or JSON handler accordingly.
- Check HX-Request header to detect HTMX requests
- Return HTML via BooksGrid template for HTMX requests
- Return JSON for API clients (existing behavior)
- Add handleSearchHTML function for HTML rendering
- Use shared MediaHandler.ExecuteSearch method
- Eliminates previous issue where JSON was rendered in browser
Add public ExecuteSearch method to MediaHandler that delegates to SearchService. Update SearchMediaItems to use the new shared service method instead of calling SearchMediaItemsUnified directly.
- Add ExecuteSearch wrapper method (line 160-162)
- Update SearchMediaItems to use searchService.ExecuteSearch
- Maintains existing JSON API behavior while enabling shared logic
Add shared search method that returns results with count. This method will be used by both JSON API endpoints and HTML rendering for HTMX, avoiding duplicate business logic.
- Extracts common search logic into reusable service method
- Returns search results with total count for pagination
- Follows DRY principle by eliminating duplicated search code
Improve media item search functionality with two key enhancements:
1. Date-prioritized year filtering:
- Prioritize date_published over copyright_year for year range queries
- Fall back to copyright_year when date_published is NULL
- Extract year from date_published timestamp for comparison
2. True exact search matching:
- Replace ILIKE pattern matching with exact equality for quoted queries
- Use search_query directly instead of wildcard pattern for exact matches
- Remove SearchPattern parameter and related wildcard logic
- Add COALESCE handling for author/series NULL values in exact matches
These changes make year filtering more accurate with published dates
and provide genuine exact matching when users wrap queries in quotes.
Refs internal/database/queries/queries.sql:475, internal/services/search.go:62
Implement sidecar-first metadata extraction approach that prioritizes
Calibre metadata.opf files over embedded metadata when available.
Key Features:
- Sidecar-first approach: Check for metadata.opf before extracting embedded
- Full Dublin Core namespace support: Use complete namespace URLs
- Calibre-specific meta tags: Extract series, series_index from <meta> tags
- Graceful degradation: Fall back to embedded metadata on parse failure
- Identifier extraction: Support ISBN and ASIN from Dublin Core identifiers
- Date parsing: Handle ISO 8601 timestamps and simple date formats
Implementation Details:
- Added extractCalibreSidecar() to check for and parse metadata.opf
- Added parseCalibreMetadataOPF() with full Dublin Core namespace handling
- Modified extractMetadata() to try sidecar first, fallback to embedded
- Added CalibreOPFMetadata struct for intermediate parsing
- Cover image support: findSidecarCover() for sidecar metadata
Tests:
- Unit tests for parseCalibreMetadataOPF() with real Calibre file examples
- Integration tests for Calibre library scanning
This allows users with Calibre-managed libraries to import their curated
metadata (series, tags, custom covers) into Bookhoard.
Fixes: #calibre-opf-support