Toast.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Toast.js
  3. *
  4. * @author realor
  5. */
  6. import { I18N } from '../i18n/I18N.js'
  7. class Toast {
  8. constructor(message, ...args) {
  9. this.message = message
  10. this.millis = 2000
  11. this.i18n = null
  12. this.toastElem = document.createElement('div')
  13. this.toastElem.style.position = 'absolute'
  14. this.toastElem.style.left = '50%'
  15. this.toastElem.style.opacity = 0
  16. this.toastElem.className = 'toast'
  17. I18N.set(this.toastElem, 'innerHTML', message, ...args)
  18. this.setSize(180, 32)
  19. this.setTop(80)
  20. this.setClassName('toast')
  21. }
  22. static create(message, ...args) {
  23. return new Toast(message, ...args)
  24. }
  25. setClassName(className) {
  26. this.toastElem.classList.add(className)
  27. return this
  28. }
  29. setMillis(millis) {
  30. this.millis = millis
  31. return this
  32. }
  33. setTop(top) {
  34. this.toastElem.style.top = top + 'px'
  35. return this
  36. }
  37. setI18N(i18n) {
  38. this.i18n = i18n
  39. return this
  40. }
  41. setSize(width, height) {
  42. this.toastElem.style.width = width + 'px'
  43. this.toastElem.style.height = height + 'px'
  44. this.toastElem.style.marginLeft = '-' + width / 2 + 'px'
  45. return this
  46. }
  47. show() {
  48. if (!this.toastElem.parentNode) {
  49. if (this.i18n) {
  50. this.i18n.update(this.toastElem)
  51. }
  52. document.body.appendChild(this.toastElem)
  53. setTimeout(() => (this.toastElem.style.opacity = 1), 500)
  54. setTimeout(() => this.hide(), 500 + this.millis)
  55. }
  56. }
  57. hide() {
  58. this.toastElem.style.opacity = 0
  59. setTimeout(() => {
  60. let parentNode = this.toastElem.parentNode
  61. if (parentNode) {
  62. parentNode.removeChild(this.toastElem)
  63. }
  64. }, 1000)
  65. }
  66. }
  67. export { Toast }