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.

54 lines
1.7 KiB

5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
  1. import { Controller } from "@hotwired/stimulus"
  2. import Toastify from 'toastify-js'
  3. export default class extends Controller {
  4. static initialized = false
  5. static toastifyNotice
  6. static toastifyAlert
  7. static lastId
  8. // call once per browser
  9. static load_once() {
  10. this.initialized = true
  11. const commonOptions = { gravity: 'top', position: 'center', duration: 4000, offset: { y: '1em' }, close: true, escapeMarkup: false }
  12. this.toastifyNotice = Toastify({ className: 'toastify-notice', ...commonOptions })
  13. this.toastifyAlert = Toastify({ className: 'toastify-alert', ...commonOptions })
  14. this.idQueue = Array(5)
  15. }
  16. initialize() {
  17. if (!this.constructor.initialized) this.constructor.load_once()
  18. }
  19. connect() {
  20. const id = Number(this.element.dataset.id)
  21. const queue = this.constructor.idQueue
  22. if (!this.constructor.idQueue.includes(id)) { // test whether duplicates from the 5 latest items
  23. queue.splice(0, 0, id)
  24. queue.splice(5)
  25. this.clearChildrenElement()
  26. this.showMessage(this.constructor.toastifyNotice, this.element.dataset.notice)
  27. this.showMessage(this.constructor.toastifyAlert, this.element.dataset.alert)
  28. }
  29. // else console.warn(`reminiscient id <${id}> from queue <${queue}`)
  30. }
  31. showMessage(toastify, message) {
  32. if (message.length > 0) {
  33. toastify.options.selector = this.element // connect to stimulus element
  34. toastify.options.text = message
  35. toastify.showToast()
  36. const lastClassNameWord = toastify.options.className.split('-').pop()
  37. console.info(`TOAST#${this.constructor.idQueue[0]} ${lastClassNameWord}: ${message}`)
  38. }
  39. }
  40. clearChildrenElement() {
  41. const node = this.element
  42. while (node.firstChild) { node.removeChild(node.firstChild) }
  43. }
  44. }