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.idQueue = Array(5) } initialize() { if (!this.constructor.initialized) this.constructor.load_once() } connect() { const id = Number(this.element.dataset.id) const queue = this.constructor.idQueue if (!this.constructor.idQueue.includes(id)) { // test whether duplicates from the 5 latest items queue.splice(0, 0, id) queue.splice(5) this.clearChildrenElement() this.showMessage(this.constructor.toastifyNotice, this.element.dataset.notice) this.showMessage(this.constructor.toastifyAlert, this.element.dataset.alert) } // else console.warn(`reminiscient id <${id}> from queue <${queue}`) } 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#${this.constructor.idQueue[0]} ${lastClassNameWord}: ${message}`) } } clearChildrenElement() { const node = this.element while (node.firstChild) { node.removeChild(node.firstChild) } } }