Browse Source

refactor

main
pvincent 5 months ago
parent
commit
ef94b8b92b
  1. 33
      app/javascript/controllers/flash_toast_controller.js

33
app/javascript/controllers/flash_toast_controller.js

@ -8,6 +8,7 @@ export default class extends Controller {
static toastifyAlert
static lastId
// call once per browser
static load_once() {
this.initialized = true
@ -15,35 +16,37 @@ export default class extends Controller {
this.toastifyNotice = Toastify({ className: 'toastify-notice', ...commonOptions })
this.toastifyAlert = Toastify({ className: 'toastify-alert', ...commonOptions })
this.lastId = 0
console.log('FlashController ready!')
}
initialize() {
// console.log('FlashController initialize')
if (!this.constructor.initialized) this.constructor.load_once()
}
connect() {
// console.log(`FlashController connect last_id=<${this.constructor.lastId}>`)
const id = this.element.dataset.id
if (id != this.constructor.lastId) {
const notice = this.element.dataset.notice
const alert = this.element.dataset.alert
while (this.element.firstChild) { this.element.removeChild(this.element.firstChild) }
if (notice.length > 0) this.toastMessageFrom(id, notice, this.constructor.toastifyNotice)
if (alert.length > 0) this.toastMessageFrom(id, alert, this.constructor.toastifyAlert)
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)
}
// else console.log(`duplicate entry ${id}`)
}
toastMessageFrom(id, message, toastify) {
toastify.options.selector = this.element
showMessage(toastify, message) {
if (message.length > 0) {
toastify.options.selector = this.element // connect to stimulus element
toastify.options.text = message
toastify.showToast()
const toastType = toastify.options.className.split('-').pop()
console.info(`TOAST ${toastType}: ${message}`)
const lastClassNameWord = toastify.options.className.split('-').pop()
console.info(`TOAST ${lastClassNameWord}: ${message}`)
}
}
clearChildrenElement() {
const node = this.element
while (node.firstChild) { node.removeChild(node.firstChild) }
}
}
Loading…
Cancel
Save