Skip to content

Commit

Permalink
fix(useToast): add in queue and improve unique ids
Browse files Browse the repository at this point in the history
Resolves #2686
  • Loading branch information
benjamincanac committed Jan 24, 2025
1 parent 8d941e1 commit 213b366
Showing 1 changed file with 29 additions and 8 deletions.
37 changes: 29 additions & 8 deletions src/runtime/composables/useToast.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ref, nextTick, readonly } from 'vue'
import { useState } from '#imports'
import type { ToastProps } from '../types'

Expand All @@ -8,20 +9,40 @@ export interface Toast extends Omit<ToastProps, 'defaultOpen'> {

export function useToast() {
const toasts = useState<Toast[]>('toasts', () => [])
const maxToasts = 5
const running = ref(false)
const queue: Toast[] = []

function add(toast: Partial<Toast>): Toast {
const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`

async function processQueue() {
if (running.value || queue.length === 0) {
return
}

running.value = true

while (queue.length > 0) {
const toast = queue.shift()!

await nextTick()

toasts.value = [...toasts.value, toast].slice(-maxToasts)
}

running.value = false
}

async function add(toast: Partial<Toast>): Promise<Toast> {
const body = {
id: new Date().getTime().toString(),
id: generateId(),
open: true,
...toast
}

const index = toasts.value.findIndex((t: Toast) => t.id === body.id)
if (index === -1) {
toasts.value.push(body)
}
queue.push(body)

toasts.value = toasts.value.slice(-5)
await processQueue()

return body
}
Expand Down Expand Up @@ -55,7 +76,7 @@ export function useToast() {
}

return {
toasts,
toasts: readonly(toasts),
add,
update,
remove,
Expand Down

0 comments on commit 213b366

Please sign in to comment.