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.

49 lines
1.7 KiB

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. static load_once() {
  9. this.initialized = true
  10. const commonOptions = { gravity: 'top', position: 'center', duration: 4000, offset: { y: '1em' }, close: true, escapeMarkup: false }
  11. this.toastifyNotice = Toastify({ className: 'toastify-notice', ...commonOptions })
  12. this.toastifyAlert = Toastify({ className: 'toastify-alert', ...commonOptions })
  13. this.lastId = 0
  14. console.log('FlashController ready!')
  15. }
  16. initialize() {
  17. // console.log('FlashController initialize')
  18. if (!this.constructor.initialized) this.constructor.load_once()
  19. }
  20. connect() {
  21. // console.log(`FlashController connect last_id=<${this.constructor.lastId}>`)
  22. const id = this.element.dataset.id
  23. if (id != this.constructor.lastId) {
  24. const notice = this.element.dataset.notice
  25. const alert = this.element.dataset.alert
  26. while (this.element.firstChild) { this.element.removeChild(this.element.firstChild) }
  27. if (notice.length > 0) this.toastMessageFrom(id, notice, this.constructor.toastifyNotice)
  28. if (alert.length > 0) this.toastMessageFrom(id, alert, this.constructor.toastifyAlert)
  29. this.constructor.lastId = id
  30. }
  31. // else console.log(`duplicate entry ${id}`)
  32. }
  33. toastMessageFrom(id, message, toastify) {
  34. toastify.options.selector = this.element
  35. toastify.options.text = message
  36. toastify.showToast()
  37. const toastType = toastify.options.className.split('-').pop()
  38. console.info(`TOAST ${toastType}: ${message}`)
  39. }
  40. }