Files
myep/assets/controllers/toast_controller.js
T

51 lines
1.4 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)
}
// Listen for HTMX notification events
document.addEventListener('showNotifications', this.handleNotifications.bind(this))
}
disconnect() {
document.removeEventListener('showNotifications', this.handleNotifications.bind(this))
}
handleNotifications(event) {
const notifications = event.detail?.notifications || []
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'
}
}