diff --git a/IMPLEMENTATION_COLLECTION_FIX.md b/IMPLEMENTATION_COLLECTION_FIX.md
index 04d72e5..bccd13b 100644
--- a/IMPLEMENTATION_COLLECTION_FIX.md
+++ b/IMPLEMENTATION_COLLECTION_FIX.md
@@ -2,7 +2,12 @@
## Overview
-Fix the broken `/collections/:id` page (inline JS bug) and add library_id support to the search API. This uses a hybrid approach: minimal TypeScript for client-only features, HTMX-like patterns for CRUD operations.
+Fix the broken `/collections/:id` page (inline JS bug) and add library_id support to the search API. This is a **full-stack task** involving:
+- Backend: Search API enhancement, WebSocket permission fix
+- Database: SQL query modification
+- Frontend: TypeScript conversion, UI improvements
+
+Uses hybrid approach: minimal TypeScript for client-only features, HTMX-like patterns for CRUD operations, WebSocket for real-time sync.
---
@@ -10,20 +15,221 @@ Fix the broken `/collections/:id` page (inline JS bug) and add library_id suppor
| File | Changes |
|------|---------|
-| `templates/collections.templ` | Remove inline JS, add data attributes, add toggle UI |
-| `web/src/collections.ts` | Add minimal TypeScript functions (~60 lines) |
+| `internal/sync/websocket.go` | Add user-scoped broadcast method |
+| `internal/handlers/collections.go` | Use user-scoped broadcasts |
+| `internal/database/queries.sql` | Add library_id filter to search |
| `internal/handlers/media.go` | Add library_id param to search handler |
-| `internal/router/frontend.go` | (No changes needed - existing modals work) |
+| `templates/collections.templ` | Remove inline JS, add data attributes, add toggle UI |
+| `web/src/collections.ts` | Add TypeScript with WebSocket support |
+| `internal/router/frontend.go` | Pass libraryID to template |
+| `cmd/server/tests/collections_test.go` | Add integration tests |
+| `docs/developer/api/search.md` | Document library_id parameter |
+| `bruno/collections/search-with-library-filter.yml` | API test for new parameter |
---
-## Step 1: Update Search API to Accept library_id
+## Git Commit Strategy
+
+Use multiple logical commits:
+
+1. **feat(websocket): Add user-scoped broadcasting**
+ - `internal/sync/websocket.go`
+ - `internal/handlers/collections.go`
+ - Tests for user-scoped broadcasts
+
+2. **feat(database): Add library_id filter to search queries**
+ - `internal/database/queries.sql`
+ - Regenerate `internal/database/queries.sql.go`
+ - Verify params struct updated
+
+3. **feat(api): Add library_id parameter to search endpoint**
+ - `internal/handlers/media.go`
+ - Integration tests for library filtering
+
+4. **refactor(templates): Remove inline JS from collection detail**
+ - `templates/collections.templ`
+ - `internal/router/frontend.go`
+ - `web/src/collections.ts`
+
+5. **feat(frontend): Add library filter toggle UI**
+ - `templates/collections.templ`
+ - `web/src/collections.ts`
+
+6. **docs(api): Document library_id search parameter**
+ - `docs/developer/api/search.md`
+ - `bruno/collections/search-with-library-filter.yml`
+
+---
+
+## Step 1: Add User-Scoped Broadcasting (WebSocket Fix)
+
+### File: `internal/sync/websocket.go`
+
+**Add after line 94** (after existing `Broadcast` method):
+
+```go
+// BroadcastToUser sends a message to all connections for a specific user
+func (m *ConnectionManager) BroadcastToUser(userID string, msg BroadcastMessage) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ for _, conn := range m.connections {
+ if conn.UserID == userID {
+ select {
+ case conn.Send <- msg:
+ default:
+ // Channel full, skip this connection
+ log.Printf("WebSocket: Channel full for %s, skipping broadcast", conn.DeviceName)
+ }
+ }
+ }
+}
+```
+
+**Why**: Current `Broadcast()` sends to ALL users (security issue). User-scoped broadcasts ensure collection updates only go to that user's devices.
+
+---
+
+## Step 2: Update Collections Handler to Use User-Scoped Broadcasts
+
+### File: `internal/handlers/collections.go`
+
+**Find all instances of** `h.connManager.Broadcast` **and replace with user-scoped**:
+
+**Line 333** (AddBooks):
+```go
+if addedCount > 0 && h.connManager != nil {
+ h.connManager.BroadcastToUser(userUUID.String(), wsync.BroadcastMessage{
+ Type: "collection_updated",
+ Timestamp: time.Now().Format(time.RFC3339),
+ Data: map[string]interface{}{
+ "collection_id": collectionID.String(),
+ "action": "books_added",
+ "book_ids": addedBookIDs,
+ "count": addedCount,
+ },
+ })
+}
+```
+
+**Line 401** (RemoveBook):
+```go
+if h.connManager != nil {
+ h.connManager.BroadcastToUser(userUUID.String(), wsync.BroadcastMessage{
+ Type: "collection_updated",
+ Timestamp: time.Now().Format(time.RFC3339),
+ Data: map[string]interface{}{
+ "collection_id": collectionID.String(),
+ "action": "book_removed",
+ "book_id": bookID.String(),
+ },
+ })
+}
+```
+
+**Line 831** (BulkRemoveBooks):
+```go
+if removedCount > 0 && h.connManager != nil {
+ h.connManager.BroadcastToUser(userUUID.String(), wsync.BroadcastMessage{
+ Type: "collection_updated",
+ Timestamp: time.Now().Format(time.RFC3339),
+ Data: map[string]interface{}{
+ "collection_id": collectionID.String(),
+ "action": "books_bulk_removed",
+ "book_ids": removedBookIDs,
+ "count": removedCount,
+ },
+ })
+}
+```
+
+**Why**: Ensures collection updates only broadcast to the user who made the change, not all connected users.
+
+---
+
+## Step 3: Add library_id Filter to SQL Query
+
+### File: `internal/database/queries.sql`
+
+**Find the `SearchMediaItems` query** (around line 393):
+
+**Current:**
+```sql
+-- name: SearchMediaItems :many
+SELECT mi.*, l.name as library_name, lt.name as library_type_name
+FROM media_items mi
+JOIN libraries l ON mi.library_id = l.id
+JOIN library_types lt ON l.library_type_id = lt.id
+LEFT JOIN library_visibility lv ON l.id = lv.library_id AND lv.user_id = sqlc.narg('user_id')
+WHERE COALESCE(lv.is_visible, true) = true
+ AND (
+ mi.title ILIKE sqlc.narg('search_pattern') OR
+ mi.author ILIKE sqlc.narg('search_pattern') OR
+ mi.series ILIKE sqlc.narg('search_pattern') OR
+ sqlc.narg('search_pattern') = ANY(mi.tags_search) OR
+ sqlc.narg('search_pattern') = ANY(mi.contributors_search)
+ )
+ORDER BY ...
+```
+
+**Add library_id parameter and filter**:
+
+```sql
+-- name: SearchMediaItems :many
+SELECT mi.*, l.name as library_name, lt.name as library_type_name
+FROM media_items mi
+JOIN libraries l ON mi.library_id = l.id
+JOIN library_types lt ON l.library_type_id = lt.id
+LEFT JOIN library_visibility lv ON l.id = lv.library_id AND lv.user_id = sqlc.narg('user_id')
+WHERE COALESCE(lv.is_visible, true) = true
+ AND ($5::uuid IS NULL OR mi.library_id = $5::uuid) -- library_id filter
+ AND (
+ mi.title ILIKE sqlc.narg('search_pattern') OR
+ mi.author ILIKE sqlc.narg('search_pattern') OR
+ mi.series ILIKE sqlc.narg('search_pattern') OR
+ sqlc.narg('search_pattern') = ANY(mi.tags_search) OR
+ sqlc.narg('search_pattern') = ANY(mi.contributors_search)
+ )
+ORDER BY ...
+```
+
+**Also update `SearchMediaItemsFuzzy`** (around line 418) with the same filter:
+```sql
+WHERE COALESCE(lv.is_visible, true) = true
+ AND ($5::uuid IS NULL OR mi.library_id = $5::uuid) -- library_id filter
+ AND (
+ word_similarity(sqlc.narg('search_query'), mi.title) > 0.3 OR
+ ...
+ )
+```
+
+**Regenerate database code:**
+```bash
+cd internal/database
+sqlc generate
+```
+
+**Verify** `internal/database/queries.sql.go` now has:
+```go
+type SearchMediaItemsParams struct {
+ UserID pgtype.UUID `db:"user_id" json:"user_id"`
+ SearchPattern pgtype.Text `db:"search_pattern" json:"search_pattern"`
+ Offset pgtype.Int4 `db:"offset" json:"offset"`
+ Limit pgtype.Int4 `db:"limit" json:"limit"`
+ LibraryID pgtype.UUID `db:"library_id" json:"library_id"` // NEW
+}
+```
+
+---
+
+## Step 4: Update Search API to Accept library_id
### File: `internal/handlers/media.go`
-**Find** (around line 1418-1442):
+**Find** (around line 1418-1472):
+
+**Current:**
```go
-// SearchMediaItems handles GET /api/media-items/search
func (mh *MediaHandler) SearchMediaItems(c echo.Context) error {
query := c.QueryParam("q")
userID := c.Get("user_id").(string)
@@ -48,11 +254,26 @@ func (mh *MediaHandler) SearchMediaItems(c echo.Context) error {
Limit: pgtype.Int4{Int32: limit, Valid: true},
Offset: pgtype.Int4{Int32: offset, Valid: true},
})
+
+ if err != nil && err != pgx.ErrNoRows {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+
+ if len(partialResults) > 0 {
+ return c.JSON(http.StatusOK, partialResults)
+ }
+
+ fuzzyResults, err := mh.db.SearchMediaItemsFuzzy(c.Request().Context(), database.SearchMediaItemsFuzzyParams{
+ SearchQuery: pgtype.Text{String: query, Valid: true},
+ UserID: pgtype.UUID{Bytes: userUUID, Valid: true},
+ Limit: pgtype.Int4{Int32: limit, Valid: true},
+ Offset: pgtype.Int4{Int32: offset, Valid: true},
+ })
+ // ... rest of function
```
-**Replace with**:
+**Replace with:**
```go
-// SearchMediaItems handles GET /api/media-items/search
func (mh *MediaHandler) SearchMediaItems(c echo.Context) error {
query := c.QueryParam("q")
userID := c.Get("user_id").(string)
@@ -68,13 +289,13 @@ func (mh *MediaHandler) SearchMediaItems(c echo.Context) error {
}
// Validate library_id if provided
- var libUUID *uuid.UUID
+ var libUUID pgtype.UUID
if libraryID != "" {
lib, err := uuid.Parse(libraryID)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid library_id"})
}
- libUUID = &lib
+ libUUID = pgtype.UUID{Bytes: lib, Valid: true}
}
limit := int32(50)
@@ -83,81 +304,62 @@ func (mh *MediaHandler) SearchMediaItems(c echo.Context) error {
searchPattern := "%" + query + "%"
// Build params - conditionally add library_id filter
- params := database.SearchMediaItemsParams{
+ partialParams := database.SearchMediaItemsParams{
SearchPattern: pgtype.Text{String: searchPattern, Valid: true},
UserID: pgtype.UUID{Bytes: userUUID, Valid: true},
Limit: pgtype.Int4{Int32: limit, Valid: true},
Offset: pgtype.Int4{Int32: offset, Valid: true},
+ LibraryID: libUUID, // May be invalid (empty)
}
- // If library_id provided, add to query params
- if libUUID != nil {
- params.LibraryID = pgtype.UUID{Bytes: *libUUID, Valid: true}
+ partialResults, err := mh.db.SearchMediaItems(c.Request().Context(), partialParams)
+
+ if err != nil && err != pgx.ErrNoRows {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
- partialResults, err := mh.db.SearchMediaItems(c.Request().Context(), params)
+ if len(partialResults) > 0 {
+ return c.JSON(http.StatusOK, partialResults)
+ }
+
+ // Fuzzy search also gets library_id filter
+ fuzzyParams := database.SearchMediaItemsFuzzyParams{
+ SearchQuery: pgtype.Text{String: query, Valid: true},
+ UserID: pgtype.UUID{Bytes: userUUID, Valid: true},
+ Limit: pgtype.Int4{Int32: limit, Valid: true},
+ Offset: pgtype.Int4{Int32: offset, Valid: true},
+ LibraryID: libUUID, // May be invalid (empty)
+ }
+
+ fuzzyResults, err := mh.db.SearchMediaItemsFuzzy(c.Request().Context(), fuzzyParams)
+
+ if err != nil && err != pgx.ErrNoRows {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+
+ if len(fuzzyResults) == 0 {
+ return c.JSON(http.StatusNotFound, map[string]interface{}{
+ "error": "no results found",
+ "query": query,
+ "results": []interface{}{},
+ })
+ }
+
+ return c.JSON(http.StatusOK, fuzzyResults)
+}
```
-**Note**: You need to check if `SearchMediaItemsParams` in `database.SearchMediaItemsParams` already has a `LibraryID` field. If not, you'll need to add it to the SQL query.
+**Why**: Both partial and fuzzy searches respect library filter for consistent UX.
---
-## Step 2: Add library_id to SQL Query (if needed)
-
-### File: `internal/database/queries.sql`
-
-**Find** the `SearchMediaItems` query:
-```sql
--- name: SearchMediaItems :many
-SELECT ...
-FROM media_items mi
-WHERE ...
-```
-
-**Add** library_id filter (if not present):
-```sql
--- name: SearchMediaItems :many
-SELECT mi.id, mi.user_id, mi.title, mi.author, mi.cover_image_path, mi.library_id, ...
-FROM media_items mi
-WHERE ...
- AND ($1::uuid IS NULL OR mi.library_id = $1::uuid) -- Add this filter
-```
-
-**Update** the `SearchMediaItemsParams` struct in `queries.sql.go` if needed to include LibraryID.
-
----
-
-## Step 3: Remove Inline JS from Template
+## Step 5: Remove Inline JS from Template
### File: `templates/collections.templ`
-**Find** the inline script block (lines 255-520):
-```go
-
-```
-
-**Replace with** a hidden data element (add after the `
` tag or where appropriate):
+**Add after the `` tag** (after line 116):
```go
```
-**Note**: You need to pass `libraryID` to the template. Check the handler in `frontend.go` that renders `CollectionDetail` and add `libraryID` to the template data.
+**Also update the CollectionDetail function signature** (around line 105):
+
+**Current:**
+```go
+func CollectionDetail(user User, collection CollectionData, books []handlers.BookInfo) templ.Component {
+```
+
+**Replace with:**
+```go
+func CollectionDetail(user User, collection CollectionData, books []handlers.BookInfo, libraryID string) templ.Component {
+```
---
-## Step 4: Add Toggle UI to Add Books Modal
+## Step 6: Add Toggle UI to Add Books Modal
### File: `templates/collections.templ`
-**Find** the Add Books modal (around line 157):
+**Find the Add Books modal content** (around line 228):
+
+**Current:**
```go
-
+
+
+ ...
+
Search and select books to add to this collection.
+
+
+
+
```
-**Add** the toggle after this button:
+**Replace with:**
```go
-
- {# Toggle only shows when library_id is present - handled by JS #}
+
+
+ ...
+
Search and select books to add to this collection.
+
+
+
+
+
+
+
+
+
+
```
-**Find** the Add Books modal content (around line 339 in generated, find in source):
-```go
-
- ...
-
Search and select books to add to this collection.
-
-
-
-
-```
-
-**Replace with**:
-```go
-
- ...
-
Search and select books to add to this collection.
-
-
-
-
-
-
-
-
-
-
-```
+**Note**: The `onchange="searchBooks()"` ensures the search re-runs when toggle changes.
---
-## Step 5: Add Minimal TypeScript Functions
+## Step 7: Add TypeScript Functions with WebSocket Support
### File: `web/src/collections.ts`
-**Add** at the end of the file:
+**Add at the end of the file**:
```typescript
// ============================================================================
-// Collection Detail Page - Minimal TypeScript (~60 lines)
+// Collection Detail Page - TypeScript with WebSocket Support
// ============================================================================
-interface BookItem {
- id: string;
+interface SearchBookResult {
+ media_item_id: string;
title: string;
- author: string;
- cover: string;
+ author: string | null;
+ cover_image_path: string | null;
+ library_id: string;
+ library_name: string;
+}
+
+interface CollectionUpdateMessage {
+ type: string;
+ data: {
+ collection_id: string;
+ action: string;
+ count?: number;
+ book_id?: string;
+ };
}
let collectionId = "";
let libraryId = "";
let selectedBooks = new Set
();
let booksToRemove = new Set();
+let ws: WebSocket | null = null;
// Initialize from data attributes (called on page load)
function initCollectionDetail(): void {
@@ -255,7 +471,7 @@ function initCollectionDetail(): void {
if (dataEl) {
collectionId = dataEl.dataset.id || "";
libraryId = dataEl.dataset.libraryId || "";
-
+
// Show/hide library filter toggle based on whether library_id is present
const filterContainer = document.getElementById("library-filter-container");
if (filterContainer) {
@@ -269,12 +485,15 @@ function initCollectionDetail(): void {
}
}
}
+
+ // Initialize WebSocket connection
+ connectWebSocket();
}
// Get current library filter setting
function getLibraryFilterParam(): string {
if (!libraryId) return "";
-
+
const checkbox = document.getElementById("filter-by-library") as HTMLInputElement;
if (checkbox && checkbox.checked) {
return `&library_id=${libraryId}`;
@@ -282,12 +501,65 @@ function getLibraryFilterParam(): string {
return "";
}
+// WebSocket connection for real-time collection updates
+function connectWebSocket(): void {
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ const token = localStorage.getItem("token");
+ if (!token) return;
+
+ const wsUrl = `${protocol}//${window.location.host}/ws/sync?token=${token}`;
+
+ ws = new WebSocket(wsUrl);
+
+ ws.onopen = (): void => {
+ console.log("WebSocket connected");
+ };
+
+ ws.onmessage = (event: MessageEvent): void => {
+ try {
+ const message = JSON.parse(event.data) as CollectionUpdateMessage;
+
+ if (message.type === "collection_updated" && message.data.collection_id === collectionId) {
+ const actionText = message.data.action === "books_added"
+ ? `Added ${message.data.count || 0} book(s)`
+ : message.data.action === "book_removed"
+ ? "Removed a book"
+ : message.data.action === "books_bulk_removed"
+ ? `Removed ${message.data.count || 0} book(s)`
+ : "Collection updated";
+
+ (window as any).showToast?.(actionText, "info");
+
+ // Auto-reload after 1 second to see updates
+ setTimeout(() => {
+ location.reload();
+ }, 1000);
+ }
+ } catch (error) {
+ console.error("Failed to parse WebSocket message:", error);
+ }
+ };
+
+ ws.onclose = (): void => {
+ console.log("WebSocket disconnected, reconnecting in 5s...");
+ setTimeout(connectWebSocket, 5000);
+ };
+
+ ws.onerror = (error: Event): void => {
+ console.error("WebSocket error:", error);
+ };
+}
+
+function backToCollections(): void {
+ window.location.href = "/collections";
+}
+
// Modal functions (called from onclick attributes)
function showAddBooksModal(): void {
const modal = document.getElementById("add-books-modal");
if (modal) modal.classList.remove("hidden");
selectedBooks.clear();
-
+
const results = document.getElementById("book-results");
if (results) {
results.innerHTML = 'Enter at least 2 characters to search.
';
@@ -297,17 +569,17 @@ function showAddBooksModal(): void {
function hideAddBooksModal(): void {
const modal = document.getElementById("add-books-modal");
if (modal) modal.classList.add("hidden");
-
+
const searchInput = document.getElementById("book-search") as HTMLInputElement;
if (searchInput) searchInput.value = "";
-
+
const results = document.getElementById("book-results");
if (results) results.innerHTML = "";
-
+
selectedBooks.clear();
}
-// Search books - now includes library filter
+// Search books - includes library filter
async function searchBooks(): Promise {
const searchInput = document.getElementById("book-search") as HTMLInputElement;
const container = document.getElementById("book-results");
@@ -323,21 +595,32 @@ async function searchBooks(): Promise {
const libraryFilter = getLibraryFilterParam();
const token = localStorage.getItem("token");
-
+ if (!token) {
+ container.innerHTML = 'Authentication required
';
+ return;
+ }
+
try {
const response = await fetch(`/api/media-items/search?q=${encodeURIComponent(searchTerm)}${libraryFilter}`, {
headers: { Authorization: `Bearer ${token}` },
});
- const result = await response.json();
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+
+ const result = await response.json() as SearchBookResult[];
if (result.length > 0) {
let html = '';
- result.slice(0, 50).forEach((book: any) => {
+ result.slice(0, 50).forEach((book) => {
const isSelected = selectedBooks.has(book.media_item_id);
const checkedAttr = isSelected ? "checked" : "";
const authorHtml = book.author ? `
${book.author}
` : "";
- const libraryBadge = book.library_id === libraryId ? '
This Library' : '';
-
+ const libraryBadge = book.library_id === libraryId
+ ? '
This Library'
+ : "";
+
html += `
{
container.innerHTML = '
No books found
';
}
} catch (error) {
+ console.error("Search error:", error);
container.innerHTML = '
Failed to search books
';
}
}
@@ -382,6 +666,10 @@ async function addSelectedBooks(): Promise
{
const bookIds = Array.from(selectedBooks);
const token = localStorage.getItem("token");
+ if (!token) {
+ (window as any).showToast?.("Authentication required", "error");
+ return;
+ }
try {
const response = await fetch(`/api/collections/${collectionId}/books`, {
@@ -396,11 +684,12 @@ async function addSelectedBooks(): Promise {
if (response.ok) {
(window as any).showToast?.(`Added ${bookIds.length} book(s) to collection`, "success");
hideAddBooksModal();
- location.reload();
+ // Note: WebSocket will trigger page reload automatically
} else {
(window as any).showToast?.("Failed to add books", "error");
}
} catch (error) {
+ console.error("Add books error:", error);
(window as any).showToast?.("Failed to add books", "error");
}
}
@@ -410,6 +699,10 @@ async function removeBook(bookId: string): Promise {
if (!confirm("Remove this book from the collection?")) return;
const token = localStorage.getItem("token");
+ if (!token) {
+ (window as any).showToast?.("Authentication required", "error");
+ return;
+ }
try {
const response = await fetch(`/api/collections/${collectionId}/books/${bookId}`, {
@@ -419,11 +712,12 @@ async function removeBook(bookId: string): Promise {
if (response.ok) {
(window as any).showToast?.("Book removed from collection", "success");
- location.reload();
+ // Note: WebSocket will trigger page reload automatically
} else {
(window as any).showToast?.("Failed to remove book", "error");
}
} catch (error) {
+ console.error("Remove book error:", error);
(window as any).showToast?.("Failed to remove book", "error");
}
}
@@ -465,6 +759,10 @@ async function removeSelectedBooks(): Promise {
const bookIds = Array.from(booksToRemove);
const token = localStorage.getItem("token");
+ if (!token) {
+ (window as any).showToast?.("Authentication required", "error");
+ return;
+ }
try {
const response = await fetch(`/api/collections/${collectionId}/books/bulk-remove`, {
@@ -476,14 +774,19 @@ async function removeSelectedBooks(): Promise {
body: JSON.stringify({ book_ids: bookIds }),
});
- const result = await response.json();
- if (result.removed > 0) {
- (window as any).showToast?.(`Removed ${result.removed} book(s) from collection`, "success");
- location.reload();
+ if (response.ok) {
+ const result = (await response.json()) as { removed: number };
+ if (result.removed > 0) {
+ (window as any).showToast?.(`Removed ${result.removed} book(s) from collection`, "success");
+ // Note: WebSocket will trigger page reload automatically
+ } else {
+ (window as any).showToast?.("Failed to remove books", "error");
+ }
} else {
(window as any).showToast?.("Failed to remove books", "error");
}
} catch (error) {
+ console.error("Bulk remove error:", error);
(window as any).showToast?.("Failed to remove books", "error");
}
}
@@ -521,6 +824,7 @@ function filterCollectionBooks(): void {
(window as any).updateSelectedCount = updateSelectedCount;
(window as any).removeSelectedBooks = removeSelectedBooks;
(window as any).filterCollectionBooks = filterCollectionBooks;
+(window as any).backToCollections = backToCollections;
// Auto-initialize
if (document.readyState === "loading") {
@@ -532,18 +836,20 @@ if (document.readyState === "loading") {
---
-## Step 6: Update Handler to Pass libraryID to Template
+## Step 8: Update Handler to Pass libraryID to Template
### File: `internal/router/frontend.go`
-**Find** the collection detail handler (around line 420):
+**Find the collection detail handler** (around line 430-432):
+
+**Current:**
```go
// Render the CollectionDetail template
var buf bytes.Buffer
err = templates.CollectionDetail(user, colData, books).Render(c.Request().Context(), &buf)
```
-**Replace with**:
+**Replace with:**
```go
// Get library_id from query params for template
libraryID := c.QueryParam("library_id")
@@ -553,22 +859,255 @@ var buf bytes.Buffer
err = templates.CollectionDetail(user, colData, books, libraryID).Render(c.Request().Context(), &buf)
```
-**Note**: You may need to update the `CollectionDetail` function signature in `templates/collections.templ` to accept `libraryID` parameter.
+---
+
+## Step 9: Add Integration Tests
+
+### File: `cmd/server/tests/collections_test.go`
+
+**Create or update with library filter tests**:
+
+```go
+package main
+
+import (
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+// TestCollectionSearchLibraryFilter tests library_id filtering in search
+func TestCollectionSearchLibraryFilter(t *testing.T) {
+ ts := setupTestServer(t)
+ defer ts.cleanup()
+
+ // Create test user and authenticate
+ user := ts.createUser(t, "testuser", "password")
+ token := ts.loginUser(t, user.ID, "password")
+
+ // Create two libraries
+ lib1 := ts.createLibrary(t, user.ID, "Library 1")
+ lib2 := ts.createLibrary(t, user.ID, "Library 2")
+
+ // Add books to each library
+ book1 := ts.createBook(t, lib1.ID, "Harry Potter 1")
+ book2 := ts.createBook(t, lib2.ID, "Harry Potter 2")
+
+ // Create collection
+ collection := ts.createCollection(t, user.ID, "My Collection")
+
+ tests := []struct {
+ name string
+ query string
+ libraryID string
+ expectedCount int
+ shouldContain string
+ }{
+ {
+ name: "no filter - both books",
+ query: "Harry",
+ libraryID: "",
+ expectedCount: 2,
+ shouldContain: "", // Either book
+ },
+ {
+ name: "filter library 1",
+ query: "Harry",
+ libraryID: lib1.ID.String(),
+ expectedCount: 1,
+ shouldContain: book1.ID.String(),
+ },
+ {
+ name: "filter library 2",
+ query: "Harry",
+ libraryID: lib2.ID.String(),
+ expectedCount: 1,
+ shouldContain: book2.ID.String(),
+ },
+ {
+ name: "invalid library_id",
+ query: "Harry",
+ libraryID: uuid.New().String(),
+ expectedCount: 0, // No books in random library
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ url := "/api/media-items/search?q=" + tt.query
+ if tt.libraryID != "" {
+ url += "&library_id=" + tt.libraryID
+ }
+
+ var result []map[string]interface{}
+ resp := ts.doRequest(t, "GET", url, token, nil, &result)
+
+ if resp.StatusCode != 200 && tt.expectedCount > 0 {
+ t.Errorf("Expected status 200, got %d", resp.StatusCode)
+ }
+
+ if len(result) != tt.expectedCount {
+ t.Errorf("Expected %d results, got %d", tt.expectedCount, len(result))
+ }
+
+ if tt.shouldContain != "" && len(result) > 0 {
+ found := false
+ for _, book := range result {
+ if book["id"] == tt.shouldContain {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Errorf("Expected book %s not found in results", tt.shouldContain)
+ }
+ }
+ })
+ }
+}
+
+// TestWebSocketUserScopedBroadcast tests that broadcasts only go to the user who made changes
+func TestWebSocketUserScopedBroadcast(t *testing.T) {
+ ts := setupTestServer(t)
+ defer ts.cleanup()
+
+ // Create two users
+ user1 := ts.createUser(t, "user1", "password")
+ user2 := ts.createUser(t, "user2", "password")
+
+ token1 := ts.loginUser(t, user1.ID, "password")
+ token2 := ts.loginUser(t, user2.ID, "password")
+
+ // Connect both users via WebSocket
+ ws1 := ts.connectWebSocket(t, token1)
+ defer ws1.Close()
+
+ ws2 := ts.connectWebSocket(t, token2)
+ defer ws2.Close()
+
+ // User1 adds book to collection
+ collection := ts.createCollection(t, user1.ID, "User1 Collection")
+ book := ts.createBook(t, user1.ID, "Test Book")
+
+ ts.doRequest(t, "POST", "/api/collections/"+collection.ID.String()+"/books", token1,
+ map[string]interface{}{"book_ids": []string{book.ID.String()}}, nil)
+
+ // User1 should receive collection_updated message
+ msg1 := ts.readWSMessage(t, ws1, 2*time.Second)
+ if msg1["type"] != "collection_updated" {
+ t.Errorf("User1 should receive collection_updated, got %s", msg1["type"])
+ }
+
+ // User2 should NOT receive collection_updated message
+ msg2 := ws1.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
+ _, _, err := ws2.ReadMessage()
+ if err == nil {
+ t.Errorf("User2 should not receive collection_updated message")
+ }
+}
+```
---
-## Step 7: Update Template to Accept libraryID
+## Step 10: Update Documentation
-### File: `templates/collections.templ`
+### File: `docs/developer/api/search.md`
-**Find** the CollectionDetail function signature:
-```go
-func CollectionDetail(user User, collection CollectionData, books []handlers.BookInfo) templ.Component {
+**Add library_id parameter documentation**:
+
+```markdown
+# Search API
+
+## Search Media Items
+
+Searches for media items across all libraries.
+
+**Endpoint:** `GET /api/media-items/search`
+
+**Query Parameters:**
+
+| Parameter | Type | Required | Description |
+|-----------|--------|----------|--------------------------------------------|
+| q | string | Yes | Search query (min 2 characters) |
+| library_id| string | No | Filter results to specific library (UUID) |
+
+**Example Request:**
+
+```bash
+# Search all libraries
+curl -H "Authorization: Bearer $TOKEN" \
+ "https://bookhoard.example/api/media-items/search?q=harry%20potter"
+
+# Search specific library
+curl -H "Authorization: Bearer $TOKEN" \
+ "https://bookhoard.example/api/media-items/search?q=harry&library_id=123e4567-e89b-12d3-a456-426614174000"
```
-**Replace with**:
-```go
-func CollectionDetail(user User, collection CollectionData, books []handlers.BookInfo, libraryID string) templ.Component {
+**Response:**
+
+Array of media items (partial match) or (fuzzy match):
+```json
+[
+ {
+ "id": "...",
+ "title": "Harry Potter and the Sorcerer's Stone",
+ "author": "J.K. Rowling",
+ "library_id": "...",
+ "library_name": "E-Books",
+ ...
+ }
+]
+```
+```
+
+### File: `bruno/collections/search-with-library-filter.yml`
+
+**Create Bruno test**:
+
+```yaml
+meta:
+ name: Search with Library Filter
+ type: Collection
+ description: Tests library_id parameter in search API
+
+collections:
+ - name: Search All Libraries
+ request:
+ method: GET
+ url: "{{baseUrl}}/api/media-items/search"
+ query:
+ q: "harry"
+ headers:
+ Authorization: "Bearer {{token}}"
+ assert:
+ - status: 200
+ - jsonpath: "$[?(@.title)].length" > 0
+
+ - name: Search Specific Library
+ request:
+ method: GET
+ url: "{{baseUrl}}/api/media-items/search"
+ query:
+ q: "harry"
+ library_id: "{{libraryId}}"
+ headers:
+ Authorization: "Bearer {{token}}"
+ assert:
+ - status: 200
+ - jsonpath: "$[?(@.library_id == '{{libraryId}}')].length" > 0
+
+ - name: Invalid Library ID
+ request:
+ method: GET
+ url: "{{baseUrl}}/api/media-items/search"
+ query:
+ q: "test"
+ library_id: "invalid-uuid"
+ headers:
+ Authorization: "Bearer {{token}}"
+ assert:
+ - status: 400
+ - jsonpath: "$.error" == "invalid library_id"
```
---
@@ -577,32 +1116,51 @@ func CollectionDetail(user User, collection CollectionData, books []handlers.Boo
| Step | File | Lines Changed | Purpose |
|------|------|---------------|---------|
-| 1 | `internal/handlers/media.go` | ~15 | Add library_id param to search |
-| 2 | `internal/database/queries.sql` | ~2 | Add library_id filter to SQL |
-| 3 | `templates/collections.templ` | -265 + 20 | Remove inline JS, add data attributes |
-| 4 | `templates/collections.templ` | ~15 | Add toggle UI to modal |
-| 5 | `web/src/collections.ts` | +~180 | Add minimal TypeScript |
-| 6 | `internal/router/frontend.go` | ~5 | Pass libraryID to template |
-| 7 | `templates/collections.templ` | ~3 | Accept libraryID in function signature |
+| 1 | `internal/sync/websocket.go` | +20 | Add user-scoped broadcast method |
+| 2 | `internal/handlers/collections.go` | ~9 | Use user-scoped broadcasts |
+| 3 | `internal/database/queries.sql` | ~4 | Add library_id filter to SQL |
+| 3b | `internal/database/queries.sql.go` | auto | Regenerate with sqlc |
+| 4 | `internal/handlers/media.go` | ~30 | Add library_id param to search |
+| 5 | `templates/collections.templ` | -265 + 25 | Remove inline JS, add data attributes |
+| 6 | `templates/collections.templ` | ~10 | Add toggle UI with onchange |
+| 7 | `web/src/collections.ts` | +~320 | Add TypeScript with WebSocket |
+| 8 | `internal/router/frontend.go` | ~3 | Pass libraryID to template |
+| 9 | `cmd/server/tests/collections_test.go` | +~150 | Integration tests |
+| 10 | `docs/developer/api/search.md` | +~30 | API documentation |
+| 10 | `bruno/collections/...` | +~50 | Bruno API tests |
---
## Testing Checklist
+### Manual Testing
+
- [ ] Navigate to `/collections/:id` - page loads without JS errors
- [ ] Navigate to `/collections/:id?library_id=xxx` - page loads with toggle visible
- [ ] Click "Add Books" - modal opens
- [ ] Search in modal - results appear
- [ ] With library_id + toggle checked - only books from that library shown
- [ ] With library_id + toggle unchecked - all books shown
-- [ ] Add book to collection - success toast + page reloads
-- [ ] Remove book from collection - success toast + page reloads
+- [ ] Check/uncheck toggle - search re-runs automatically
+- [ ] Add book to collection - toast appears, page reloads via WebSocket
+- [ ] Open same collection in second tab - first tab shows update when second tab adds book
+- [ ] Remove book from collection - toast appears, page reloads
- [ ] Search within collection - books filter client-side
+### Automated Testing
+
+- [ ] `go test ./cmd/server/tests -run TestCollectionSearchLibraryFilter`
+- [ ] `go test ./cmd/server/tests -run TestWebSocketUserScopedBroadcast`
+- [ ] Bruno tests: `search-with-library-filter.yml`
+- [ ] Verify no WebSocket messages go to wrong users
+
---
## Notes
-- The WebSocket real-time sync was removed from the TypeScript for simplicity. Can be added back if needed.
-- The toggle default is "checked" (filter by library) when library_id is present, matching the dashboard context.
-- The existing API handlers (`AddBooks`, `RemoveBook`, `BulkRemoveBooks`) don't need changes - they work with or without library_id.
+- **WebSocket real-time sync is preserved** for multi-device/tab updates
+- **User-scoped broadcasts** ensure privacy (User A doesn't see User B's collection updates)
+- **Toggle default is "checked"** (filter by library) when library_id is present
+- **Search respects library filter** in both partial and fuzzy searches for consistency
+- **All changes follow PROJECT_GUIDELINES.md**: TypeScript only, TailwindCSS only, procedural style
+- **Progressive enhancement maintained**: Page works without JS (server-side rendered)