page-toast.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. const DEFAULT_DURATION = 1000
  2. const globalListeners = []
  3. function getToastFromState(state = {}) {
  4. const errorText = String(state.errorText || '').trim()
  5. const systemTip = String(state.systemTip || '').trim()
  6. if (errorText) {
  7. return {
  8. text: errorText,
  9. type: 'error'
  10. }
  11. }
  12. if (systemTip) {
  13. return {
  14. text: systemTip,
  15. type: 'info'
  16. }
  17. }
  18. return {
  19. text: '',
  20. type: ''
  21. }
  22. }
  23. function createPageToast(page, initialState = {}, duration = DEFAULT_DURATION) {
  24. let active = true
  25. let timer = null
  26. let lastText = getToastFromState(initialState).text
  27. function clearTimer() {
  28. if (!timer) return
  29. clearTimeout(timer)
  30. timer = null
  31. }
  32. function clear() {
  33. clearTimer()
  34. page.setData({
  35. toastText: '',
  36. toastType: ''
  37. })
  38. }
  39. function show(text, type) {
  40. if (!active) return
  41. clearTimer()
  42. page.setData({
  43. toastText: text,
  44. toastType: type || 'info'
  45. })
  46. timer = setTimeout(() => {
  47. timer = null
  48. page.setData({
  49. toastText: '',
  50. toastType: ''
  51. })
  52. }, duration)
  53. }
  54. function showExternal(text, type) {
  55. const toastText = String(text || '').trim()
  56. if (!toastText) {
  57. lastText = ''
  58. return
  59. }
  60. if (!active) {
  61. lastText = toastText
  62. return
  63. }
  64. if (toastText === lastText) return
  65. lastText = toastText
  66. show(toastText, type)
  67. }
  68. function showFromState(state) {
  69. const toast = getToastFromState(state)
  70. if (!toast.text) {
  71. lastText = ''
  72. return
  73. }
  74. if (!active) {
  75. lastText = toast.text
  76. return
  77. }
  78. if (toast.text === lastText) return
  79. lastText = toast.text
  80. show(toast.text, toast.type)
  81. }
  82. function setActive(nextActive) {
  83. active = !!nextActive
  84. if (!active) clear()
  85. }
  86. function destroy() {
  87. clear()
  88. const index = globalListeners.indexOf(showExternal)
  89. if (index >= 0) globalListeners.splice(index, 1)
  90. }
  91. globalListeners.push(showExternal)
  92. return {
  93. clear,
  94. destroy,
  95. show,
  96. showFromState,
  97. setActive
  98. }
  99. }
  100. function notifyPageToast(text, type = 'info') {
  101. globalListeners.slice().forEach((listener) => {
  102. listener(text, type)
  103. })
  104. }
  105. module.exports = {
  106. createPageToast,
  107. notifyPageToast
  108. }