57 lines
1.8 KiB
JavaScript
57 lines
1.8 KiB
JavaScript
import { Controller } from '@hotwired/stimulus'
|
|
import Toastify from 'toastify-js'
|
|
|
|
export default class extends Controller {
|
|
|
|
static values = { text: String, class: String }
|
|
|
|
connect() {
|
|
// Show toast from Stimulus values (existing functionality)
|
|
if (this.hasTextValue) {
|
|
this.showToast(this.textValue, this.classValue)
|
|
}
|
|
|
|
// Bind handler for proper cleanup
|
|
this.boundHandleNotifications = this.handleNotifications.bind(this)
|
|
|
|
// Listen for custom HTMX notification events on document.body
|
|
// Events from HX-Trigger response headers bubble up to document.body
|
|
document.body.addEventListener('showNotifications', this.boundHandleNotifications)
|
|
}
|
|
|
|
disconnect() {
|
|
document.body.removeEventListener('showNotifications', this.boundHandleNotifications)
|
|
}
|
|
|
|
handleNotifications(event) {
|
|
// HTMX wraps the trigger value in an object with 'value' and 'elt' properties
|
|
// event.detail.value contains the actual array from the HX-Trigger header
|
|
const notifications = event.detail?.value || []
|
|
|
|
notifications.forEach(notification => {
|
|
const className = this.getClassForType(notification.type)
|
|
this.showToast(notification.message, className)
|
|
})
|
|
}
|
|
|
|
showToast(text, className = '') {
|
|
Toastify({
|
|
duration: 5000,
|
|
text: text,
|
|
gravity: 'top',
|
|
position: 'right',
|
|
className: className,
|
|
close: true,
|
|
}).showToast()
|
|
}
|
|
|
|
getClassForType(type) {
|
|
const typeMap = {
|
|
'success': 'toastify--success',
|
|
'warning': 'toastify--warning',
|
|
'info': 'toastify--info',
|
|
}
|
|
|
|
return typeMap[type] || 'toastify--info'
|
|
}
|
|
} |