The test was checking for hexadecimal entity ' but templ actually outputs
the decimal entity ' for apostrophes. This commit updates the assertion to
match the actual HTML output from the templ library.
Remove COMMUNITY_RATING_TYPE_CHANGE.md as this was a planning document
for the community rating field type change (FLOAT4 → FLOAT8) which has
now been completed and integrated into the main implementation.
The community rating field is now:
- Type: DOUBLE PRECISION (FLOAT8) in database schema
- Range: 0.0-10.0 (not 0-5 like user ratings)
- Displayed on frontend with star rating and numeric score
- Properly distinguished from user ratings
This documentation is no longer needed since the feature is complete.
Add comprehensive integration tests for all 8 comic metadata display steps
on the book detail page, ensuring frontend rendering works correctly with
real database data.
## Test Coverage
### Step Tests (8 individual tests)
1. Reading Direction Badge - Tests RTL, LTR, vertical, and auto-hide behavior
2. Community Rating Display - Validates star rendering and numeric score
3. Comic-Specific Badges - Tests age rating, B&W, and story arc badges
4. Universal Series Info - Tests series count, volume, and imprint display
5. Comic-Specific Metadata - Tests manga type, scan info, alternate series
6. Summary Section - Tests ComicInfo.xml summary rendering
7. Metadata Notes Section - Tests technical notes display
8. Web URL Link - Tests external link rendering with security attributes
### Test Case Scenarios (4 complete scenarios)
1. Japanese Manga - Complete metadata display (RTL + all badges)
2. Western Comic - LTR direction with story arc
3. Webtoon/Manhwa - Vertical reading direction
4. Regular Ebook - No comic metadata (minimal display)
### Authentication Tests (2 tests)
- Anonymous users are denied access (401)
- Regular users can view metadata (same as admins)
### Edge Case Tests (2 tests)
- Minimal Metadata - Only required fields (no optional metadata)
- All Fields Together - Comprehensive metadata display
## Test Infrastructure
- Uses setupTestServer() helper for isolated test environment
- Uses createComicMediaItem() helper for flexible test data creation
- Uses createLibrary() helper with automatic cleanup
- Tests use pgtype types matching production code
- All tests run with admin authentication by default
- Tests check both structure and content in rendered HTML
## Test Details
- 21 total subtests covering all metadata display features
- Tests verify HTML structure, content presence, and proper escaping
- Uses t.Run() for organized test output
- Tests clean up resources automatically with t.Cleanup()
- Checks for proper HTML entity encoding (e.g., apostrophes)
- Validates conditional rendering (hide when values not set)
## Known Issues
- Metadata Notes content validation uses partial string matching to handle
HTML escaping variations
- Reading Direction test checks specific direction strings (RTL/LTR/VERTICAL)
to avoid false positives from emoji appearing elsewhere in the UI
- Community Rating test uses colon ("Community Rating:") to avoid matching
HTML comments
Related: Template implementation commit (562ca53)
Implement comprehensive comic metadata display features on the SSR book detail
page, supporting all 8 metadata fields from ComicInfo.xml and other sources.
## Template Changes (book_detail.templ)
### Step 1: Reading Direction Badge
- Display directional badge (RTL, LTR, VERTICAL) for manga/comics
- Uses 📖 icon with uppercase direction text
- Auto-hides when direction is "auto" (default)
- Styled with accent color for visibility
### Step 2: Community Rating Display
- Show pre-existing community rating from metadata (0.0-10.0 scale)
- Distinct from user ratings with visual differentiation
- Uses renderStars() helper for visual star display
- Shows both stars and numeric score (e.g., "★★★★☆ 8.5 / 10")
- Smaller, subtler styling than user rating
### Step 3: Comic-Specific Badges
- Age Rating: Content maturity indicator
- Black & White: Visual style badge
- Story Arc: Narrative arc name with 📚 icon
- Badges styled as pills with subtle borders
- Only display when values are present
### Step 4: Universal Series Info
- Series Count: Total items in series
- Volume: Volume/omnibus number
- Imprint: Publisher imprint (e.g., Vertigo)
### Step 5: Comic-Specific Metadata
- Manga Type: Raw/Comic/Manga classification
- Scan Information: Scanner group, resolution
- Alternate Series: Different series numbering
### Step 6: Summary Section
- Display ComicInfo.xml summary when present
- Separate from description field
- Sanitized HTML output with bluemonday
- Scrollable container for long summaries
### Step 7: Metadata Notes
- Technical notes from metadata files
- Internal/useful information (scanner, source, etc.)
- Card-style display with clear typography
### Step 8: Web URL Link
- External link to info sources (Goodreads, ComicVine, etc.)
- Opens in new tab with security attributes
- Displays clean domain name
## Utils Changes (templates/utils.go)
Added helper functions:
- getAlternateSeries(): Extract alternate series from JSONB
- getDomainName(): Extract clean domain for display
- formatAlternateInfo(): Format readable alternate series string
## Implementation Plan
Updated FRONTEND_IMPLEMENTATION_PLAN_COMIC_METADATA.md with:
- Disabled markdownlint for MD013 (line length)
- Added spacing for readability
## Technical Details
- All fields use pgtype.Text/Int4/Bool for NULL handling
- Template conditionals check Valid flag before accessing values
- Consistent styling using CSS custom properties
- HTML escaping for security (except summary with bluemonday)
- Responsive design with mobile-friendly layouts
Related: Database schema already supports all metadata fields
Add comprehensive planning document for displaying new ComicInfo.xml
metadata fields on the book detail page.
New fields to be added:
- Reading direction (RTL/LTR/vertical) badge
- Community rating display (0-10 scale)
- Universal fields: series count, volume, imprint, age rating
- Comic-specific: manga type, story arc, scan info, B&W flag
Implementation approach:
- SSR-first rendering (no client-side fetching)
- TailwindCSS only (no custom CSS)
- Conditional display based on field validity
- Follows existing template patterns
This document provides step-by-step implementation guidance
with code examples and testing scenarios for the frontend team.
Related: IMPLEMENTATION_PLAN_MERGE_METADATA_READING_DIRECTION.md
Update TestRestoreSystemCollection_ValidNames to use the correct
title case format for system collection names.
The API handler validates these specific collection names:
- "Continue Reading"
- "Recently Added"
- "Recently Read"
- "Not Started"
The test was previously using kebab-case names (e.g., "continue-reading")
which were being rejected by the validation logic with 400 Bad Request.
This aligns the test with the updated collection name format used
throughout the application.
This commit fixes multiple issues in the comic metadata test suite that were causing test failures:
1. UUID Byte-Order Corruption
- Fixed byte-order corruption when converting library IDs
- Previously used [16]byte(uuid.MustParse(libraryID)) which corrupted bytes
- Now parse UUID once and reuse the parsed UUID variable
- Matches pattern used successfully in calibre_integration_test.go
2. Test Isolation
- Each sub-test now creates its own isolated library
- Previously all sub-tests shared one library, causing cross-test pollution
- ListMediaItemsByLibrary returns items from previous tests
- New libraries: "RTL Manga Test Library", "Western Comic Test Library", "Minimal Metadata Test Library"
3. Query Function Selection
- Replaced SearchMediaItems with ListMediaItemsByLibrary
- SearchMediaItems requires search_pattern parameter which was missing
- ListMediaItemsByLibrary is simpler and more appropriate for these tests
4. Explicit Default Values
- MangaType and ReadingDirection now explicitly set to expected defaults
- Database defaults not applied when pgtype fields have Valid: false
- "Comic with minimal metadata" test now sets: MangaType="unknown", ReadingDirection="auto"
5. Library Naming for Cleanup
- All library names now include "Test" for proper cleanup
- Test cleanup deletes libraries with "test" in name (case-insensitive)
- Prevents orphaned libraries from accumulating in database
All tests in TestComicMetadataExtraction now pass:
- CBZ with RTL manga ✓
- CBZ with Western comic ✓
- Comic with minimal metadata ✓
- 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.
Document rationale for changing community_rating from DECIMAL(3,1) to DOUBLE PRECISION.
Contents:
- Comparison of original DECIMAL choice vs DOUBLE PRECISION benefits
- Code simplicity analysis (complex pgtype.Numeric vs simple pgtype.Float8)
- Migration notes for existing databases (manual ALTER TYPE command)
- Impact analysis (no API or UI changes, only internal Go code)
Provides complete justification for the type change and migration instructions
for anyone reviewing the git history or schema changes.
Relates to: Schema change commit (DOUBLE PRECISION for community_rating)
Phase 6.2 implementation: Add comprehensive integration test code to plan.
Documentation Updates:
- Changed community_rating from DECIMAL(3,1) to DOUBLE PRECISION throughout plan
- Fixed function name references: processNewMediaItems → processMediaFile (correct name)
- Added complete integration test implementation (TestComicMetadataExtraction,
TestReadingDirectionAPI, TestUniversalMetadataFields, TestComicSpecificFields)
- Replaced skeleton TestMergeMetadata with actual test code using setupTestServer
- Added context-based location markers (3 lines before/after) for easier code navigation
- Removed TODO comment reference (doesn't exist in current code)
- Updated all line number references and added plan update summary
- Verified test helper usage: setupDeviceTest for library creation
Integration Tests Added:
- Full comic metadata field testing (manga_type, reading_direction, series_count, volume,
imprint, age_rating, community_rating as pgtype.Float8, story_arc, is_black_and_white)
- Reading direction API testing (rtl, ltr, auto filtering)
- Universal field testing for both comic and ebook libraries
- Comic-specific field testing (alternate_info JSONB, scan_information, summary, metadata_notes)
All tests use proper test_helpers pattern with setupDeviceTest and verify DOUBLE PRECISION
storage for CommunityRating field.
Relates to: Phase 6.2 integration testing documentation
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
Change community_rating from DECIMAL(3,1) to DOUBLE PRECISION to:
- Eliminate awkward pgtype.Numeric conversion in Go code
- Enable direct pgtype.Float8 mapping from ComicInfo.xml float64
- Simplify code by matching natural types (XML float64 → PostgreSQL DOUBLE PRECISION → Go pgtype.Float8)
- Remove need for string formatting and Scan() method calls
The floating-point precision error (< 0.00001%) is negligible for 0-10 rating scale.
This simplifies Phase 4 implementation significantly.
Column comment updated to reflect DOUBLE PRECISION type.
Relates to: Phase 1 database schema changes for comic metadata support
Add 14 new columns to media_items table for comprehensive comic and manga
metadata support, including reading direction fields and universal metadata
that applies to all media formats.
New Columns:
- Reading direction: manga_type (raw ComicInfo.xml field), reading_direction (computed)
- Universal series: series_count, volume (apply to ebooks, audiobooks, comics)
- Publisher info: imprint, age_rating (all formats)
- Comic-specific: story_arc, is_black_and_white, alternate_info, scan_information, summary
- Additional metadata: metadata_notes, community_rating, web_url
Constraints:
- manga_type CHECK: unknown, no, yes, yes_and_right_to_left
- reading_direction CHECK: auto, ltr, rtl, vertical
Indexes (8 new):
- idx_media_items_reading_direction, idx_media_items_manga_type
- idx_media_items_story_arc, idx_media_items_imprint
- idx_media_items_age_rating, idx_media_items_series_count, idx_media_items_volume
- idx_media_items_alternate_info_gin (GIN index for JSONB queries)
Documentation:
- Added COMMENT ON COLUMN for all 14 new fields
- Distinctions between comic-specific and universal fields clearly documented
This supports the ComicInfo.xml v2.0 standard with 29 fields and enables
proper reading direction detection for manga, webtoons, and Western comics.
Part of Phase 1: Database Schema Changes
Implementation: IMPLEMENTATION_PLAN_MERGE_METADATA_READING_DIRECTION.md
This document provides a complete implementation plan for extracting ALL 19
ComicInfo.xml v2.0 fields with smart metadata merging and universal metadata
support across all media types (ebooks, audiobooks, comics).
Key features planned:
- Complete ComicInfo.xml v2.0 support (all 19 fields)
- Smart metadata merging: Calibre metadata.opf + ComicInfo.xml + folder structure
- Universal metadata fields (5 fields apply to ALL formats):
* age_rating: Content classification (Everyone, Teen, Mature, Adult)
* series_count: Total items in series
* volume: Collected edition/omnibus number
* imprint: Publisher subdivision
* web_url: Info page URLs (Goodreads, Audible, ComicVine, etc.)
- Comic-specific fields (10 fields):
* manga_type, reading_direction: Reading direction detection
* story_arc, scan_information, alternate_info, summary, etc.
- Genre/tag processing: ALL genres appear in tags array without duplication
* Uses existing 'genre' column for primary genre
* processGenresAndTags() ensures no duplicate genres in tags
* Works for EPUB, ComicInfo.xml, PDF metadata
- 15 new database columns, 8 indexes
- Full-stack support: database → Go → API → TypeScript → frontend
- Comprehensive testing and documentation
Plan organization:
- 10 phases: Database schema → Data structures → Smart merging → API updates
- Includes detailed commit strategy with sequential git add/commit/push commands
- Testing checklist with manual verification steps
- Bruno API test specifications
- Documentation updates (user + API reference)
This plan follows PROJECT_GUIDELINES.md requirements:
- No new services or handlers (reuses existing media_scanner.go)
- Uses setupTestServer() helper for integration tests
- Includes Bruno YAML files for API testing
- Sequential git commits with detailed messages
- Reuses existing code patterns and database schema
Update Bruno API test collections with latest test data:
Bookhoard.yml environment:
- Update media_item_id to current database value after recent
database recreation/schema updates
Create Media Rating test:
- Change test rating from 8 to 7 to test different rating value
for validation
These are test infrastructure updates only, no application code changes.
Improve star rating display on book detail page to show always-visible
5-star rating scale with theme-aware colors and visual half-star rendering.
Changes:
Enhanced renderStars() function:
- Always displays 5 stars (0/5 now shows 5 grey stars instead of empty)
- Filled stars use var(--accent) color (theme-aware highlight)
- Empty stars use var(--text-secondary) (theme-aware grey, adapts to light/dark themes)
- Half-stars use CSS linear-gradient (90deg) to split star vertically:
- Left half: var(--accent) (filled, color)
- Right half: var(--text-secondary) (empty, grey)
- Uses webkit-background-clip and text-fill-color transparent for gradient effect
Added getBookRating() helper function:
- Returns rating value or 0 if book.Rating is nil
- Allows unrated books to display 0/5 (5 grey stars)
- Makes rating section always visible instead of hiding when nil
Template changes:
- Updated rating display to always show (no conditionals)
- Removed text-yellow-400 class (colors now inline with theme vars)
- Added templ.Raw() wrapper for HTML rendering (prevents escaping)
- Simplified rating display logic
Benefits:
- Users can now see rating scale even when book isn't rated
- Visual half-star is much more intuitive than ½ text character
- Theme-aware colors adapt to light/dark mode automatically
- Follows existing patterns ( UnsafeHTML, CSS variables, etc.)
This makes the rating section more discoverable and user-friendly.
Add clickable links to book detail page (/media/:uuid) from:
- Dashboard: BookCard components now link to detail page
- Changed from data-action pattern to direct <a> tags
- Removes unused viewBook() function and switch case
- Follows progressive enhancement (works without JS)
- Collections: Book titles link to detail page
- Books displayed in collection detail view
- Progress: Book titles link to detail page
- Progress cards now have clickable title links
All links use direct navigation for better UX and progressive enhancement.
Book detail page can display comprehensive metadata, reading progress,
sync status, and external service links.
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)
Add utility functions for rendering book metadata:
- renderStars(): Convert rating (1-10 scale) to star display
- formatFileSize(): Convert bytes to human-readable format (KB, MB, GB)
- getExternalURL(): Generate URLs for external book services
with smart fallback: ID → ISBN → Title+Author search
Supports Goodreads, Open Library, Google Books, Amazon
These helpers make book detail template cleaner and follow DRY principle.
Add github.com/microcosm-cc/bluemonday for safe HTML sanitization.
This library is industry-standard, actively maintained, and has zero
telemetry/network calls.
License: BSD-3-Clause (compatible with project's GPL-3 license)
Used for sanitizing book description HTML before rendering.
Update 'Manage Folders' button text to 'Manage Libraries and Folders'
to better reflect the full functionality of managing both libraries
and scan directories in one place.
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
Fixed multiple issues preventing the collections page and modals from working correctly:
1. Alpine Expression Error on page load:
- Added missing semicolon between function calls in x-init directive
- Added missing parentheses to initializeCollectionWebSocket() call
- Collections page now loads without JavaScript errors
2. Modal container removal bug:
- Fixed closeCollectionModal() removing #modal-container parent element
- Changed from modal.parentElement.remove() to modal.remove()
- Modal can now be opened and closed multiple times without errors
- Fixes htmx:targetError when trying to open modal after first close
3. Emoji grid display:
- Modal now properly preserves container across open/close cycles
- setupHTMXModalInit() can successfully repopulate icon grid
- Emoji picker displays correctly on all modal opens
Technical details:
- templates/collections.templ: Fixed x-init syntax errors
- web/src/collections.ts: Fixed modal close logic to preserve container
- Modal container persists across HTMX swaps, allowing repeated use
The load filter dropdown was being cut off when the button was positioned
on the left side of the screen due to static right-0 alignment. This became
more problematic as the button position changes with window resize.
Changes:
- Added dynamic dropdown alignment calculation based on button position
and available viewport space
- Implemented smart positioning logic that checks available space on both
left and right sides before deciding alignment
- Added window resize listener using requestAnimationFrame to dynamically
update dropdown position while open
- Added data-load-filter-btn attribute for reliable DOM querying
- Changed from static right-0 to dynamic :class binding for left/right
alignment
Technical details:
- Alpine.js state: dropdownAlign tracks current alignment (left/right)
- calculateAlignment() method computes button position and available space
- Uses getBoundingClientRect() to measure button position relative to viewport
- Prefers side with >=320px space, otherwise chooses larger side
- requestAnimationFrame ensures smooth updates during resize without
performance degradation
Fixes issue where dropdown extends beyond viewport edge when button
is near left or right edge of screen.
Cleanup of project files:
- Remove CALIBRE_OPF_IMPLEMENTATION.md (obsolete documentation)
- Remove Bruno API collection files for field value searches:
- Field Values Search - Authors.yml
- Field Values Search - Genres.yml
- Field Values Search - Languages.yml
- Field Values Search - Series.yml
These files are no longer needed as the functionality has been
implemented and the API has evolved.
CSS changes for bookshelf page:
Tristate button styles (input.css):
- Add .tristate-btn base class with transition effects
- Three state-specific classes with dynamic colors:
- .state-null (Any): Neutral style with --text-secondary
- .state-true (Has Cover): Green success style using color-mix()
- .state-false (No Cover): Red/warning style using color-mix()
- Theme-aware coloring using CSS variables:
- Background: var(--bg-primary) with color overlays
- Border: var(--border) base color
- Text: var(--text-primary) for readability
- Hover and active states for better UX
- Flex layout for proper icon/text alignment
- Support for light and dark themes automatically
Style.css update:
- Minor adjustment for compatibility
The tristate button provides clear visual feedback for the has_cover
filter state with automatic theme adaptation.
Major refactoring of bookshelf filter logic:
Filter loading improvements:
- Add clearFormWithoutSubmit() helper to reset form without submission
- Refactor clearFilters() to reuse clearFormWithoutSubmit() helper
Reduces code duplication from 38 lines to 8 lines
- Update loadFilter() to call clearFormWithoutSubmit() before populating
This ensures all stale data from previous filter is cleared
- Move has_cover handling before empty value check
Fixes issue where has_cover=false was being skipped
- Remove automatic HTMX trigger note from cycleHasCover()
Fixed issues:
- Author field staying populated when switching to filter without author
- has_cover tristate button not updating when switching between filters
- has_cover button not updating from "Has Cover" to "Any" when loading filter without has_cover
- General stale data retention when loading different saved filters
HTMX event handling:
- Add event listener in initBookshelf() for htmx:afterSwap events
- Listens on #saved-filters-list element (the swap target)
- Calls afterFilterSave() to close modal and show success toast
- Properly handles Alpine component state access
All filter operations now work correctly with proper state management
and no visual artifacts from previous filters.
Template changes for bookshelf page:
Cover filter (tristate button):
- Replace checkbox with 3-state button: Any (null) → Has Cover → No Cover
- Add Alpine state management for hasCoverState (true/false/null)
- Button shows dynamic icon and label based on state:
- ○ Cover: Any
- ✓ Has Cover
- ✗ No Cover
- Hidden input conditionally rendered by Alpine (x-if="hasCoverState !== null")
- Only submits "true"/"false" or not at all, never empty string
- Theme-aware styling using CSS variables and color-mix()
Filter management improvements:
- Add name="library" attribute to library select for proper form submission
- Create filter_item.templ component for rendering individual filter items
- Add Load Filter and Delete Filter buttons with Alpine event handlers
- Update save filter form to use HTMX attributes:
- hx-post, hx-target, hx-swap, hx-include for AJAX submission
- @htmx:afterRequest event for modal cleanup
This fixes issues where:
- Library wasn't being submitted with search/filter requests
- has_cover was sending empty string causing no results
- Saved filters couldn't be loaded or deleted
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.
- Update Combined Search and Filters: change has_cover to true, tags_filter to fic
- Update sequence numbers for all search requests (1-7)
- Ensure consistent request ordering in search folder
- Remove obsolete scenarios/ folder and move requests to root media-items/
- Create new filters/ folder for field value autocomplete searches
- Move Field Values Search requests from search/ to filters/ for clarity
- Move Search Media Items from scenarios/ to search/ for consistency
- Update sequence numbers across all media-items requests (2-13)
- Remove redundant folder configuration files
- Improve API collection organization for better discoverability
- Update library_id in Bookhoard environment configuration
- Add post-response script to Get Libraries (Admin) endpoint
- Script automatically extracts and saves first library_id from response
- Enables seamless API testing without manual variable updates
Updated the Bruno API test collection to include tests for the new
3-state has_cover filter functionality.
Changes:
- Added test cases for has_cover=true, has_cover=false, and has_cover
not specified to verify all three states work correctly
- Updated environment configuration to support the new filter parameter
These tests verify that the has_cover filter properly handles:
- NULL (not specified): Returns all books
- TRUE: Returns only books with cover images
- FALSE: Returns only books without cover images
This ensures the 3-state boolean implementation works correctly across
all scenarios and prevents regression of the bug where searches were
returning 0 results.
Updated the clearFilters() function to properly reset the filter form
and trigger form submission.
Changes:
- Use form.reset() instead of manually clearing each input for
cleaner, more reliable form reset
- Manually reset pagination hidden inputs (limit=50, offset=0) after
form.reset() to ensure pagination state is properly cleared
- Changed HTMX trigger from "change" to "submit" to match the new
visible form structure
- Simplified loadFilter function to not clear the form before
populating, just update existing field values
The previous implementation was manually iterating through all inputs
and resetting them one by one, which was error-prone and didn't
properly handle the pagination state. The new implementation uses
the browser's native form.reset() for reliable form clearing.
This fix ensures that clicking "Clear" properly resets all filters
and pagination, allowing users to start fresh with their search.
Restructured the bookshelf filter form to be a proper visible form
instead of individual inputs with HTMX attributes pointing to a
hidden form.
Changes:
- Wrapped all filter inputs in a visible <form id="filter-form">
with hx-get="/api/media-items/search" and hx-target="#books-grid"
- Removed redundant HTMX attributes from individual inputs since
they're now part of the form
- Added "Search" submit button to explicitly trigger form submission
- Moved hidden pagination state inputs (limit, offset) inside the form
- Preserved all existing functionality: autocomplete, fuzzy search,
saved filters, clear filters button
- Added checked attribute to has_cover checkbox for default state
This change fixes the architectural issue where filter inputs were
outside the form and relied on hx-include, which was fragile and
made form handling complex. The new structure is more maintainable
and follows standard HTML form patterns.
The form now properly includes all filter parameters when submitted,
ensuring that search, filters, and pagination work correctly together.
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
Add books-grid wrapper div and pagination controls to BookShelf
template to fix HTMX targeting issue.
Changes:
- Add id="books-grid" wrapper div around BooksGrid component
- Add pagination section with Previous/Next buttons
- Pagination uses HTMX to target #books-grid for updates
- Include #filter-form in HTMX requests to preserve filters
Fixes pagination displaying inside the grid instead of below it.
The wrapper div ensures HTMX replaces only the grid content,
not the pagination controls.
Related: Issue #2 - Fix pagination display location
Remove wrapper div and pagination from BooksGrid component.
The component now only renders book cards, making it more reusable.
Changes:
- Remove books-grid wrapper div from BooksGrid
- Remove pagination controls from BooksGrid
- Component now only renders book card grid
This allows the parent template to control the wrapper div
placement and pagination location, which is needed for proper
HTMX targeting on the bookshelf page.
Related: Issue with pagination displaying inside grid instead of below
Replace inline book grid and pagination HTML with reusable BooksGrid component. This eliminates 43 lines of duplicate code and follows DRY principle.
- Replace inline books grid (lines 322-364) with @BooksGrid() call
- Pagination now rendered by BooksGrid component
- Maintains same functionality with cleaner code
- Generated bookshelf_templ.go updated by templ compiler