dawarich/app/javascript/controllers/notifications_controller.js

80 lines
2.1 KiB
JavaScript
Raw Normal View History

import BaseController from "./base_controller"
import consumer from "../channels/consumer"
export default class extends BaseController {
static targets = ["badge", "list"]
static values = { userId: Number }
2024-11-03 09:21:29 -05:00
initialize() {
super.initialize()
2024-11-03 09:21:29 -05:00
this.subscription = null
}
connect() {
2024-11-03 09:21:29 -05:00
// Clean up any existing subscription
if (this.subscription) {
this.subscription.unsubscribe()
2024-11-03 09:21:29 -05:00
this.subscription = null
}
2024-11-03 09:21:29 -05:00
this.createSubscription()
}
disconnect() {
if (this.subscription) {
this.subscription.unsubscribe()
this.subscription = null
}
}
createSubscription() {
this.subscription = consumer.subscriptions.create("NotificationsChannel", {
connected: () => {
// console.log("[WebSocket] Connected to NotificationsChannel")
},
disconnected: () => {
// console.log("[WebSocket] Disconnected from NotificationsChannel")
},
received: (data) => {
// console.log("[WebSocket] Received notification:", data)
this.prependNotification(data)
}
})
}
prependNotification(notification) {
const existingNotification = this.listTarget.querySelector(`a[href="/notifications/${notification.id}"]`)
if (existingNotification) {
return
2024-11-03 09:21:29 -05:00
}
const li = this.createNotificationListItem(notification)
const divider = this.listTarget.querySelector(".divider")
if (divider) {
divider.parentNode.insertBefore(li, divider.nextSibling)
} else {
this.listTarget.prepend(li)
}
this.updateBadge()
}
createNotificationListItem(notification) {
const li = document.createElement("li")
li.className = "notification-item"
li.innerHTML = `
<a href="/notifications/${notification.id}">
${notification.title}
<div class="badge badge-xs justify-self-end badge-${notification.kind}"></div>
</a>
`
return li
}
updateBadge() {
const badgeCount = this.listTarget.querySelectorAll(".notification-item").length
this.badgeTarget.textContent = badgeCount
this.badgeTarget.classList.toggle("hidden", badgeCount === 0)
}
}