Search results now show where you are in a book: a completed check at the 0.999 threshold (same cut as the filter status arms), a partial progress bar along the cover while mid-read, nothing when you never opened it. Rendered in BookCard (any grid whose adapter loads viewer progress) and in the header-search dropdown rows. The progress rides a LEFT JOIN reading_progress on the SAME user_id param SearchMediaItemsUnified already binds for library visibility — one requester param, no new wire inputs, row-neutral join (the table is UNIQUE per media_item+user). SearchMediaItemsUnifiedRow and BookInfo gain the keys additively (viewer_percentage null when unknown, library_name empty on feeds that don't load it); contract_pins.md carries the changelog entry and the pin tests widen in lockstep. The header dropdown itself migrates off the innerHTML string renderer in search.ts (a rendering-ownership violation: a templ twin existed via the HX-Request branch). The input now hx-gets layout=dropdown and swaps the new templ SearchResults partial — titles/authors highlighted server-side (escape-first, safe by construction), rows with the same progress overlays — while a slim Alpine component owns only client-local state (min-length gating, open/close, keyboard selection, htmx lifecycle). web/src/rendering-allowlist.txt drops the search.ts baseline to zero accordingly. Integration test pins the per-user join (fresh user sees 1.0/0.42/null on the fixture; the shared admin sees null everywhere — read-only) and the dropdown partial's overlays/count/row count.
110 lines
4.1 KiB
Go
110 lines
4.1 KiB
Go
package router
|
|
|
|
import (
|
|
"bookhoard/internal/database"
|
|
"bookhoard/internal/handlers"
|
|
"bookhoard/templates"
|
|
"bytes"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/labstack/echo/v5"
|
|
)
|
|
|
|
func registerSearchRoutes(cfg *Config) {
|
|
e := cfg.Echo
|
|
// JWT middleware for protected routes
|
|
jwtMiddleware := createJWTMiddleware(cfg)
|
|
protected := e.Group("/api", jwtMiddleware)
|
|
// Search endpoint - returns JSON or HTML based on HX-Request header
|
|
protected.GET("/media-items/search", func(c *echo.Context) error {
|
|
// Check if HTMX request (expects HTML)
|
|
if c.Request().Header.Get("HX-Request") == "true" {
|
|
return handleSearchHTML(c, cfg)
|
|
}
|
|
|
|
// Otherwise return JSON (API clients)
|
|
return cfg.MediaHandler.SearchMediaItems(c)
|
|
})
|
|
// Facet-value listings for the filter panel (faceted-navigation
|
|
// Batch C): /api/media-items/facets?facet=X&library_id=...
|
|
protected.GET("/media-items/facets", cfg.MediaHandler.GetFacets)
|
|
// Rule-builder live count (faceted plan Phase 9): the composed
|
|
// tree's true match count (COUNT(*)), rules + library scope.
|
|
protected.GET("/media-items/filter-count", cfg.MediaHandler.FilterCount)
|
|
protected.POST("/sync/books/query", cfg.MatchingHandler.QueryBooks)
|
|
}
|
|
|
|
// handleSearchHTML renders HTML response for HTMX requests
|
|
func handleSearchHTML(c *echo.Context, cfg *Config) error {
|
|
user, ok := c.Get("user").(database.Users)
|
|
if !ok {
|
|
return c.String(http.StatusUnauthorized, "Unauthorized")
|
|
}
|
|
// Extract filters via the SHARED parser (handlers.ParseMediaSearchParams)
|
|
// — the HTMX grid partial and the JSON endpoint can never disagree on
|
|
// which facet params exist or how they parse. (This branch previously
|
|
// dropped publisher_filter and narrator_filter entirely — the shared
|
|
// parser fixes that too.)
|
|
params := handlers.ParseMediaSearchParams(c)
|
|
params.UserID = user.ID
|
|
|
|
// Filter rule builder: a malformed qf is a 400, never a silently
|
|
// ignored token.
|
|
if params.FilterParseErr != "" {
|
|
return c.HTML(http.StatusBadRequest, `<div style="color: red;">Invalid filter</div>`)
|
|
}
|
|
limit := params.Limit
|
|
offset := params.Offset
|
|
libraryID := c.QueryParam("library_id")
|
|
|
|
// Family-lens gate: an explicit library_id outside the requester's
|
|
// visible set is a 403 (same rule as the JSON branch).
|
|
if params.LibraryID.Valid {
|
|
_, ids, err := cfg.LibraryService.VisibleLibrarySet(c.Request().Context(), user.ID)
|
|
if err != nil {
|
|
log.Printf("VisibleLibrarySet failed: %v", err)
|
|
return c.HTML(http.StatusInternalServerError, `<div style="color: red;">Search error</div>`)
|
|
}
|
|
visible := false
|
|
for _, id := range ids {
|
|
if id == params.LibraryID {
|
|
visible = true
|
|
break
|
|
}
|
|
}
|
|
if !visible {
|
|
return c.HTML(http.StatusForbidden, `<div style="color: red;">Library not visible</div>`)
|
|
}
|
|
}
|
|
|
|
// Execute search using handler method
|
|
results, totalCount, err := cfg.MediaHandler.ExecuteSearch(c.Request().Context(), params)
|
|
if err != nil {
|
|
log.Printf("Search error: %v", err)
|
|
return c.HTML(http.StatusInternalServerError, `<div style="color: red;">Search error</div>`)
|
|
}
|
|
// Convert to BookInfo
|
|
bookInfoList := handlers.BookCardsFromUnified(results)
|
|
// Stamp active conflict flags so cards route the play action correctly
|
|
bookInfoList = handlers.MarkActiveConflicts(c.Request().Context(), cfg.Queries, user.ID, bookInfoList)
|
|
// Render using BooksGrid template (or BookPickerGrid for collection picker)
|
|
var buf bytes.Buffer
|
|
switch {
|
|
case c.QueryParam("show_checkbox") == "true":
|
|
err = templates.BookPickerGrid(bookInfoList).Render(c.Request().Context(), &buf)
|
|
case c.QueryParam("layout") == "dropdown":
|
|
// Header-search dropdown: compact templ rows (rendering
|
|
// ownership) carrying the viewer's progress/completed overlay.
|
|
// Replaces the old innerHTML string renderer in search.ts.
|
|
err = templates.SearchResults(bookInfoList, c.QueryParam("q")).Render(c.Request().Context(), &buf)
|
|
default:
|
|
err = templates.BooksGrid(bookInfoList, limit, offset, totalCount, libraryID).Render(c.Request().Context(), &buf)
|
|
}
|
|
if err != nil {
|
|
log.Printf("Template render error: %v", err)
|
|
return c.HTML(http.StatusInternalServerError, `<div style="color: red;">Render error</div>`)
|
|
}
|
|
return c.HTML(http.StatusOK, buf.String())
|
|
}
|