All files / src/stores toast.ts

100% Statements 16/16
100% Branches 3/3
100% Functions 7/7
100% Lines 14/14

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                      57x 57x     57x 1140x 1140x     5x       295x 295x 295x 295x 295x       147x       148x     1140x    
import { defineStore } from 'pinia'
import { ref } from 'vue'
 
export type ToastType = 'success' | 'error'
 
export interface Toast {
  id: number
  type: ToastType
  message: string
}
 
const SUCCESS_DURATION_MS = 4000
const ERROR_DURATION_MS = 7000
 
// @implements UC-TOAST-001.1
export const useToastStore = defineStore('toast', () => {
  const toasts = ref<Toast[]>([])
  let nextId = 1
 
  function dismiss(id: number) {
    toasts.value = toasts.value.filter((toast) => toast.id !== id)
  }
 
  function show(message: string, type: ToastType = 'success') {
    const id = nextId++
    toasts.value.push({ id, type, message })
    const duration = type === 'error' ? ERROR_DURATION_MS : SUCCESS_DURATION_MS
    setTimeout(() => dismiss(id), duration)
    return id
  }
 
  function success(message: string) {
    return show(message, 'success')
  }
 
  function error(message: string) {
    return show(message, 'error')
  }
 
  return { toasts, success, error, dismiss }
})