import { Controller } from "@hotwired/stimulus" import Toastify from 'toastify-js' export default class extends Controller { static initialized = false static toastifyNotice static toastifyAlert static lastId 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 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) this.constructor.lastId = id } // else console.log(`duplicate entry ${id}`) } toastMessageFrom(id, message, toastify) { toastify.options.selector = this.element toastify.options.text = message toastify.showToast() const toastType = toastify.options.className.split('-').pop() console.info(`TOAST ${toastType}: ${message}`) } }