| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- const DEFAULT_DURATION = 1000
- const globalListeners = []
- function getToastFromState(state = {}) {
- const errorText = String(state.errorText || '').trim()
- const systemTip = String(state.systemTip || '').trim()
- if (errorText) {
- return {
- text: errorText,
- type: 'error'
- }
- }
- if (systemTip) {
- return {
- text: systemTip,
- type: 'info'
- }
- }
- return {
- text: '',
- type: ''
- }
- }
- function createPageToast(page, initialState = {}, duration = DEFAULT_DURATION) {
- let active = true
- let timer = null
- let lastText = getToastFromState(initialState).text
- function clearTimer() {
- if (!timer) return
- clearTimeout(timer)
- timer = null
- }
- function clear() {
- clearTimer()
- page.setData({
- toastText: '',
- toastType: ''
- })
- }
- function show(text, type) {
- if (!active) return
- clearTimer()
- page.setData({
- toastText: text,
- toastType: type || 'info'
- })
- timer = setTimeout(() => {
- timer = null
- page.setData({
- toastText: '',
- toastType: ''
- })
- }, duration)
- }
- function showExternal(text, type) {
- const toastText = String(text || '').trim()
- if (!toastText) {
- lastText = ''
- return
- }
- if (!active) {
- lastText = toastText
- return
- }
- if (toastText === lastText) return
- lastText = toastText
- show(toastText, type)
- }
- function showFromState(state) {
- const toast = getToastFromState(state)
- if (!toast.text) {
- lastText = ''
- return
- }
- if (!active) {
- lastText = toast.text
- return
- }
- if (toast.text === lastText) return
- lastText = toast.text
- show(toast.text, toast.type)
- }
- function setActive(nextActive) {
- active = !!nextActive
- if (!active) clear()
- }
- function destroy() {
- clear()
- const index = globalListeners.indexOf(showExternal)
- if (index >= 0) globalListeners.splice(index, 1)
- }
- globalListeners.push(showExternal)
- return {
- clear,
- destroy,
- show,
- showFromState,
- setActive
- }
- }
- function notifyPageToast(text, type = 'info') {
- globalListeners.slice().forEach((listener) => {
- listener(text, type)
- })
- }
- module.exports = {
- createPageToast,
- notifyPageToast
- }
|