You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.5 KiB
52 lines
1.5 KiB
import { Controller } from "@hotwired/stimulus"
|
|
import Toastify from 'toastify-js'
|
|
|
|
export default class extends Controller {
|
|
|
|
static initialized = false
|
|
static toastifyNotice
|
|
static toastifyAlert
|
|
static lastId
|
|
|
|
// call once per browser
|
|
static load_once() {
|
|
this.initialized = true
|
|
|
|
const commonOptions = { gravity: 'top', position: 'center', duration: 4000, offset: { y: '1em' }, close: true, escapeMarkup: false }
|
|
this.toastifyNotice = Toastify({ className: 'toastify-notice', ...commonOptions })
|
|
this.toastifyAlert = Toastify({ className: 'toastify-alert', ...commonOptions })
|
|
this.lastId = 0
|
|
}
|
|
|
|
initialize() {
|
|
if (!this.constructor.initialized) this.constructor.load_once()
|
|
}
|
|
|
|
connect() {
|
|
const id = this.element.dataset.id
|
|
if (id != this.constructor.lastId) { // test whether duplicates
|
|
this.constructor.lastId = id
|
|
|
|
this.clearChildrenElement()
|
|
this.showMessage(this.constructor.toastifyNotice, this.element.dataset.notice)
|
|
this.showMessage(this.constructor.toastifyAlert, this.element.dataset.alert)
|
|
}
|
|
}
|
|
|
|
showMessage(toastify, message) {
|
|
if (message.length > 0) {
|
|
toastify.options.selector = this.element // connect to stimulus element
|
|
toastify.options.text = message
|
|
toastify.showToast()
|
|
|
|
const lastClassNameWord = toastify.options.className.split('-').pop()
|
|
console.info(`TOAST ${lastClassNameWord}: ${message}`)
|
|
}
|
|
}
|
|
|
|
clearChildrenElement() {
|
|
const node = this.element
|
|
while (node.firstChild) { node.removeChild(node.firstChild) }
|
|
}
|
|
|
|
}
|