feat(collections): add real-time updates via WebSocket (Limitation #4)

Implement real-time collection updates when books are added/removed:

Backend Changes:
- Added connManager to CollectionHandler struct
- Updated constructor to accept ConnectionManager
- Updated all NewCollectionHandler() calls in ebook.go and main.go
- Added WebSocket broadcasts in AddBooks() handler
- Added WebSocket broadcasts in BulkRemoveBooks() handler
- Broadcasts collection_updated events with:
  - collection_id: Which collection changed
  - action: books_added or books_removed
  - book_ids: Array of affected book IDs
  - count: Number of books changed

Frontend Changes:
- Added WebSocket connection in collections UI
- connectWebSocket() establishes connection to /ws/sync
- Listens for collection_updated events
- Shows toast notification on collection change
- Auto-reloads page after 1 second to show updated book list
- Auto-reconnect on disconnect (5s delay)
- Error handling for WebSocket failures

WebSocket Event Format:
{
  "type": "collection_updated",
  "timestamp": "2026-02-01T12:00:00Z",
  "data": {
    "collection_id": "uuid",
    "action": "books_added",
    "book_ids": ["uuid1", "uuid2"],
    "count": 2
  }
}

User Experience:
- When another user adds books to a collection, all connected clients see:
  1. Toast notification: "Collection updated: books_added (2 books)"
  2. Page auto-refreshes after 1 second
  3. Updated book list displays
- Same for book removal
- Works across multiple browser tabs/devices
- No manual refresh needed

Technical Notes:
- Broadcasts to ALL connected WebSocket clients
- Client-side filtering by collection_id
- Existing progress/conflict broadcasts continue to work
- Connection manager handles broadcast distribution

Resolves Limitation #4: Real-time Collection Updates
This commit is contained in:
john-okeefe committed 2026-02-01 00:54:41 -05:00
1 parent 4bc7a842b5
commit 40c732481a
5 files changed
+78 -6

No files matched your search

+35
View File
@@ -335,11 +335,46 @@ templ CollectionDetail(user User, collection CollectionDetailData, books []BookD
},
}{ end }
];
let ws = null;
function backToCollections() {
window.location.href = '/collections';
}
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/ws/sync`;
ws = new WebSocket(wsUrl);
ws.onopen = function() {
console.log('WebSocket connected');
};
ws.onmessage = function(event) {
const message = JSON.parse(event.data);
if (message.type === 'collection_updated' && message.data.collection_id === collectionId) {
showToast(`Collection updated: ${message.data.action} (${message.data.count} books)`, 'info');
setTimeout(() => {
location.reload();
}, 1000);
}
};
ws.onclose = function() {
console.log('WebSocket disconnected, reconnecting in 5s...');
setTimeout(connectWebSocket, 5000);
};
ws.onerror = function(error) {
console.error('WebSocket error:', error);
};
}
connectWebSocket();
function filterCollectionBooks() {
const searchTerm = document.getElementById('collection-search').value.toLowerCase();
const booksContainer = document.getElementById('books-container');
+1 -1
View File
@@ -233,7 +233,7 @@ func CollectionDetail(user User, collection CollectionDetailData, books []BookDa
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "</div></div><div id=\"add-books-modal\" class=\"hidden fixed inset-0 z-50 flex items-center justify-center\" style=\"background-color: rgba(0, 0, 0, 0.7);\"><div class=\"card rounded-lg p-6 w-full max-w-2xl mx-4\" style=\"background-color: var(--bg-secondary); border-color: var(--border);\"><div class=\"flex justify-between items-center mb-6\"><h2 class=\"text-xl font-bold\" style=\"color: var(--text-primary)\">Add Books to Collection</h2><button onclick=\"hideAddBooksModal()\" class=\"p-2 hover:opacity-80 rounded\" style=\"color: var(--text-primary)\">✕</button></div><p class=\"mb-4\" style=\"color: var(--text-secondary)\">Search and select books to add to this collection.</p><div class=\"mb-4\"><input type=\"text\" id=\"book-search\" placeholder=\"Search books...\" class=\"w-full px-4 py-2 border rounded-lg\" style=\"background-color: var(--bg-primary); color: var(--text-primary); border-color: var(--border);\"></div><div id=\"book-results\" class=\"max-h-64 overflow-y-auto mb-4\"></div><div class=\"flex justify-end space-x-3\"><button type=\"button\" onclick=\"hideAddBooksModal()\" class=\"btn-secondary px-4 py-2 rounded-lg\">Cancel</button> <button type=\"button\" onclick=\"addSelectedBooks()\" class=\"btn-primary px-4 py-2 rounded-lg\">Add Selected Books</button></div></div></div><script>\n let collectionId = '{ collection.ID }';\n let selectedBooks = new Set();\n let booksToRemove = new Set();\n let allBooks = [\n { range books }{\n {\n id: '{ book.MediaItemID }',\n title: '{ book.Title }',\n author: '{ book.Author }',\n cover: '{ book.CoverImagePath }'\n },\n }{ end }\n ];\n\n function backToCollections() {\n window.location.href = '/collections';\n }\n\n function filterCollectionBooks() {\n const searchTerm = document.getElementById('collection-search').value.toLowerCase();\n const booksContainer = document.getElementById('books-container');\n const bookCards = booksContainer.children;\n\n let visibleCount = 0;\n for (let i = 0; i < bookCards.length; i++) {\n const card = bookCards[i];\n if (card.id === 'empty-state') continue;\n\n const title = card.querySelector('.font-semibold')?.textContent.toLowerCase() || '';\n const author = card.querySelector('.text-sm')?.textContent.toLowerCase() || '';\n\n const matches = title.includes(searchTerm) || author.includes(searchTerm);\n\n if (matches || searchTerm === '') {\n card.style.display = '';\n visibleCount++;\n } else {\n card.style.display = 'none';\n }\n }\n }\n\n function showAddBooksModal() {\n document.getElementById('add-books-modal').classList.remove('hidden');\n selectedBooks.clear();\n document.getElementById('book-results').innerHTML = '<p class=\"text-sm\" style=\"color: var(--text-secondary)\">Enter at least 2 characters to search.</p>';\n }\n\n function hideAddBooksModal() {\n document.getElementById('add-books-modal').classList.add('hidden');\n document.getElementById('book-search').value = '';\n document.getElementById('book-results').innerHTML = '';\n selectedBooks.clear();\n }\n\n function searchBooks() {\n const searchTerm = document.getElementById('book-search').value;\n const container = document.getElementById('book-results');\n\n if (searchTerm.length < 2) {\n container.innerHTML = '<p class=\"text-sm\" style=\"color: var(--text-secondary)\">Enter at least 2 characters to search.</p>';\n return;\n }\n\n container.innerHTML = '<p class=\"text-sm\" style=\"color: var(--text-secondary)\">Searching...</p>';\n\n fetch(`/api/media-items/search?q=${encodeURIComponent(searchTerm)}`, {\n headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }\n })\n .then(response => response.json())\n .then(result => {\n if (result.data && result.data.length > 0) {\n let html = '<div class=\"space-y-2\">';\n result.data.slice(0, 50).forEach(book => {\n const isSelected = selectedBooks.has(book.media_item_id);\n const checkedAtLine truncated
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "</div></div><div id=\"add-books-modal\" class=\"hidden fixed inset-0 z-50 flex items-center justify-center\" style=\"background-color: rgba(0, 0, 0, 0.7);\"><div class=\"card rounded-lg p-6 w-full max-w-2xl mx-4\" style=\"background-color: var(--bg-secondary); border-color: var(--border);\"><div class=\"flex justify-between items-center mb-6\"><h2 class=\"text-xl font-bold\" style=\"color: var(--text-primary)\">Add Books to Collection</h2><button onclick=\"hideAddBooksModal()\" class=\"p-2 hover:opacity-80 rounded\" style=\"color: var(--text-primary)\">✕</button></div><p class=\"mb-4\" style=\"color: var(--text-secondary)\">Search and select books to add to this collection.</p><div class=\"mb-4\"><input type=\"text\" id=\"book-search\" placeholder=\"Search books...\" class=\"w-full px-4 py-2 border rounded-lg\" style=\"background-color: var(--bg-primary); color: var(--text-primary); border-color: var(--border);\"></div><div id=\"book-results\" class=\"max-h-64 overflow-y-auto mb-4\"></div><div class=\"flex justify-end space-x-3\"><button type=\"button\" onclick=\"hideAddBooksModal()\" class=\"btn-secondary px-4 py-2 rounded-lg\">Cancel</button> <button type=\"button\" onclick=\"addSelectedBooks()\" class=\"btn-primary px-4 py-2 rounded-lg\">Add Selected Books</button></div></div></div><script>\n let collectionId = '{ collection.ID }';\n let selectedBooks = new Set();\n let booksToRemove = new Set();\n let allBooks = [\n { range books }{\n {\n id: '{ book.MediaItemID }',\n title: '{ book.Title }',\n author: '{ book.Author }',\n cover: '{ book.CoverImagePath }'\n },\n }{ end }\n ];\n let ws = null;\n\n function backToCollections() {\n window.location.href = '/collections';\n }\n\n function connectWebSocket() {\n const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';\n const wsUrl = `${protocol}//${window.location.host}/ws/sync`;\n\n ws = new WebSocket(wsUrl);\n\n ws.onopen = function() {\n console.log('WebSocket connected');\n };\n\n ws.onmessage = function(event) {\n const message = JSON.parse(event.data);\n\n if (message.type === 'collection_updated' && message.data.collection_id === collectionId) {\n showToast(`Collection updated: ${message.data.action} (${message.data.count} books)`, 'info');\n\n setTimeout(() => {\n location.reload();\n }, 1000);\n }\n };\n\n ws.onclose = function() {\n console.log('WebSocket disconnected, reconnecting in 5s...');\n setTimeout(connectWebSocket, 5000);\n };\n\n ws.onerror = function(error) {\n console.error('WebSocket error:', error);\n };\n }\n\n connectWebSocket();\n\n function filterCollectionBooks() {\n const searchTerm = document.getElementById('collection-search').value.toLowerCase();\n const booksContainer = document.getElementById('books-container');\n const bookCards = booksContainer.children;\n\n let visibleCount = 0;\n for (let i = 0; i < bookCards.length; i++) {\n const card = bookCards[i];\n if (card.id === 'empty-state') continue;\n\n const title = card.querySelector('.font-semibold')?.textContent.toLowerCase() || '';\n const author = card.querySelector('.text-sm')?.textContent.toLowerCase() || '';\n\n const matches = title.includes(searchTerm) || author.includes(searchTerm);\n\n if (matches || searchTerm === '') {\n card.style.display = '';\n visibleCount++;\n } else {\n card.style.display = 'none';\n }\n }\n }\n\n function showAddBooksModal() {\n document.getElementById('add-books-modal').classList.remove('hidden');\n selectedBooks.clear();\n document.getElementById('book-results').innerHTML = '<p class=\"text-sm\" style=\"color: var(--text-secondary)\">Enter at least 2 characters to search.</p>';\n }\n\n function hideAddBooksModal() {\n document.getElementById('add-books-modal').classList.add('hidden');\n document.getElementById('book-search').value =Line truncated
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}