feat: 项目接口联调
This commit is contained in:
79
src/features/notifications/store.ts
Normal file
79
src/features/notifications/store.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import {create} from 'zustand'
|
||||
|
||||
export type ToastType = 'success' | 'error'
|
||||
|
||||
type ToastState = {
|
||||
message: string
|
||||
type: ToastType
|
||||
visible: boolean
|
||||
}
|
||||
|
||||
type ToastStore = {
|
||||
toast: ToastState | null
|
||||
showToast: (message: string, type?: ToastType) => void
|
||||
clearToast: () => void
|
||||
}
|
||||
|
||||
let toastTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
export function resolveToastMessage(source: unknown, fallback = '') {
|
||||
if (typeof source === 'string' && source.trim()) {
|
||||
return source.trim()
|
||||
}
|
||||
|
||||
if (typeof source === 'object' && source !== null && 'msg' in source) {
|
||||
const message = (source as {msg?: unknown}).msg
|
||||
if (typeof message === 'string' && message.trim()) {
|
||||
return message.trim()
|
||||
}
|
||||
}
|
||||
|
||||
return fallback.trim()
|
||||
}
|
||||
|
||||
export const useToastStore = create<ToastStore>((set) => ({
|
||||
toast: null,
|
||||
showToast: (message, type = 'success') => {
|
||||
if (toastTimer) {
|
||||
clearTimeout(toastTimer)
|
||||
}
|
||||
|
||||
set({
|
||||
toast: {
|
||||
message,
|
||||
type,
|
||||
visible: true,
|
||||
},
|
||||
})
|
||||
|
||||
toastTimer = setTimeout(() => {
|
||||
set({toast: null})
|
||||
toastTimer = null
|
||||
}, 2000)
|
||||
},
|
||||
clearToast: () => {
|
||||
if (toastTimer) {
|
||||
clearTimeout(toastTimer)
|
||||
toastTimer = null
|
||||
}
|
||||
set({toast: null})
|
||||
},
|
||||
}))
|
||||
|
||||
export function notifySuccess(source: unknown, fallback = '') {
|
||||
const message = resolveToastMessage(source, fallback)
|
||||
if (!message) {
|
||||
return
|
||||
}
|
||||
|
||||
useToastStore.getState().showToast(message, 'success')
|
||||
}
|
||||
|
||||
export function notifyError(source: unknown, fallback = '') {
|
||||
const message = resolveToastMessage(source, fallback)
|
||||
if (!message) {
|
||||
return
|
||||
}
|
||||
|
||||
useToastStore.getState().showToast(message, 'error')
|
||||
}
|
||||
Reference in New Issue
Block a user