All files / src/stores toast.store.ts

0% Statements 0/38
0% Branches 0/1
0% Functions 0/1
0% Lines 0/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                                                                                                                 
import { defineStore } from 'pinia'
 
export interface Toast {
  id: string
  message: string
  type: 'success' | 'error' | 'warning' | 'info'
  duration?: number
}
 
export const useToastStore = defineStore('toast', {
  state: () => ({
    toasts: [] as Toast[],
  }),
 
  actions: {
    addToast(toast: Omit<Toast, 'id'>) {
      const id = Math.random().toString(36).substring(2, 9)
      const duration = toast.duration || 5000
      
      this.toasts.push({ ...toast, id })
 
      setTimeout(() => {
        this.removeToast(id)
      }, duration)
 
      return id
    },
 
    removeToast(id: string) {
      const index = this.toasts.findIndex((t) => t.id === id)
      if (index > -1) {
        this.toasts.splice(index, 1)
      }
    },
 
    success(message: string, duration?: number) {
      return this.addToast({ message, type: 'success', duration })
    },
 
    error(message: string, duration?: number) {
      return this.addToast({ message, type: 'error', duration })
    },
 
    warning(message: string, duration?: number) {
      return this.addToast({ message, type: 'warning', duration })
    },
 
    info(message: string, duration?: number) {
      return this.addToast({ message, type: 'info', duration })
    },
 
    clear() {
      this.toasts = []
    },
  },
})