All files / munch-ease-frontend/src/composables useAlert.ts

100% Statements 29/29
71.42% Branches 5/7
100% Functions 4/4
100% Lines 29/29

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 301x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x  
import { ref } from 'vue'
 
type AlertType = 'success' | 'error' | 'info'
export type AlertMessage = { heading?: string; message: string; type: AlertType }
 
// Singleton reactive alert state for the app
const current = ref<(AlertMessage & { _ts: number }) | null>(null)
let timeoutId: ReturnType<typeof setTimeout> | null = null
 
function show(message: AlertMessage) {
  current.value = { ...message, _ts: Date.now() }
}
 
function clear() {
  current.value = null
}
 
function scheduleAutoDismiss(ms = 5000) {
  if (timeoutId) clearTimeout(timeoutId)
  if (!current.value) return
  timeoutId = setTimeout(() => {
    clear()
    timeoutId = null
  }, ms)
}
 
export function useAlert() {
  return { current, show, clear, scheduleAutoDismiss }
}