// change the color of a row for 2 seconds and clear it to normal let blink = (elem, color) => { // change the color of each td let cells = elem.getElementsByTagName("td"); for (let j = 0; j < cells.length; j++) { cells[j].style.backgroundColor = color; } // wait 2s and clear the color setTimeout(() => { for (let j = 0; j < cells.length; j++) { cells[j].style.backgroundColor = ""; } }, 2000); } function viewAddBook(book) { for (let key in book) { if (book[key] === null) { book[key] = "None"; } } let p = (arg) => { if (arg === "None") { return '

'; } return '

'; } let ps = (arg) => { if (arg == 0) return p("None"); if (arg == 1) return '

' else return '

'; } let booksTableBody = document.getElementById("books-table").getElementsByTagName('tbody')[0]; var newRow = booksTableBody.insertRow(1); newRow.innerHTML = ''+ ''+book.isbn+''+ ''+p(book.title)+book.title+'

'+ ''+p(book.author)+book.author+'

'+ ''+ps(book.status)+book.status_text+'

'+ ''+p(book.owner)+book.owner+'

'+ ''+p(book.category)+book.category+'

'+ ''+ ' '+ ' '+ ''+ ''; blink(newRow, "var(--color-action)"); } function viewUpdateBook(book) { for (let key in book) { if (book[key] === null) { book[key] = "None"; } } let p = (arg) => { if (arg === "None") { return '

'; } return '

'; } let pc = (arg) => { if (arg > 1) return p("None"); else return p(arg); } let booksTableBody = document.getElementById("books-table").getElementsByTagName('tbody')[0]; let rows = booksTableBody.getElementsByTagName("tr"); for (let i = 1; i < rows.length; i++) { let cells = rows[i].getElementsByTagName("td"); if (cells[0].innerText == book.isbn) { cells[1].innerHTML = p(book.title)+book.title+'

'; cells[2].innerHTML = p(book.author)+book.author+'

'; cells[3].innerHTML = p(book.publish_date)+book.publish_date+'

'; cells[4].innerHTML = p(book.publisher)+book.publisher+'

'; cells[5].innerHTML = p(book.category)+book.category+'

'; cells[6].innerHTML = pc(book.count)+book.count+'

'; blink(rows[i], "var(--color-action)"); return; } } } function viewDeleteBook(book) { let booksTableBody = document.getElementById("books-table").getElementsByTagName('tbody')[0]; let rows = booksTableBody.getElementsByTagName("tr"); for (let i = 1; i < rows.length; i++) { let cells = rows[i].getElementsByTagName("td"); if (cells[0].innerText == book.isbn) { let row = rows[i]; blink(row, "#f1acbb"); setTimeout(() => { booksTableBody.removeChild(row); }, 2000); } } } const listener = new EventSource("/app/listen"); listener.onmessage = (e) => { let data = JSON.parse(e.data); switch (data.type) { case "pong": console.log("pong!"); break; case "add_book": viewAddBook(data.book); break; case "update_book": viewUpdateBook(data.book); break; case "delete_book": viewDeleteBook(data.book); break; default: console.log("Unexpected response from SSE:", data); } };