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

2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 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.lastId = 0
  15. }
  16. initialize() {
  17. if (!this.constructor.initialized) this.constructor.load_once()
  18. }
  19. connect() {
  20. const id = this.element.dataset.id
  21. if (id != this.constructor.lastId) { // test whether duplicates
  22. this.constructor.lastId = id
  23. this.clearChildrenElement()
  24. this.showMessage(this.constructor.toastifyNotice, this.element.dataset.notice)
  25. this.showMessage(this.constructor.toastifyAlert, this.element.dataset.alert)
  26. }
  27. }
  28. showMessage(toastify, message) {
  29. if (message.length > 0) {
  30. toastify.options.selector = this.element // connect to stimulus element
  31. toastify.options.text = message
  32. toastify.showToast()
  33. const lastClassNameWord = toastify.options.className.split('-').pop()
  34. console.info(`TOAST ${lastClassNameWord}: ${message}`)
  35. }
  36. }
  37. clearChildrenElement() {
  38. const node = this.element
  39. while (node.firstChild) { node.removeChild(node.firstChild) }
  40. }
  41. }