File tree 1 file changed +28
-7
lines changed
1 file changed +28
-7
lines changed Original file line number Diff line number Diff line change
1
+ import { ref , nextTick } from 'vue'
1
2
import { useState } from '#imports'
2
3
import type { ToastProps } from '../types'
3
4
@@ -8,20 +9,40 @@ export interface Toast extends Omit<ToastProps, 'defaultOpen'> {
8
9
9
10
export function useToast ( ) {
10
11
const toasts = useState < Toast [ ] > ( 'toasts' , ( ) => [ ] )
12
+ const maxToasts = 5
13
+ const running = ref ( false )
14
+ const queue : Toast [ ] = [ ]
11
15
12
- function add ( toast : Partial < Toast > ) : Toast {
16
+ const generateId = ( ) => `${ Date . now ( ) } -${ Math . random ( ) . toString ( 36 ) . slice ( 2 , 9 ) } `
17
+
18
+ async function processQueue ( ) {
19
+ if ( running . value || queue . length === 0 ) {
20
+ return
21
+ }
22
+
23
+ running . value = true
24
+
25
+ while ( queue . length > 0 ) {
26
+ const toast = queue . shift ( ) !
27
+
28
+ await nextTick ( )
29
+
30
+ toasts . value = [ ...toasts . value , toast ] . slice ( - maxToasts )
31
+ }
32
+
33
+ running . value = false
34
+ }
35
+
36
+ async function add ( toast : Partial < Toast > ) : Promise < Toast > {
13
37
const body = {
14
- id : new Date ( ) . getTime ( ) . toString ( ) ,
38
+ id : generateId ( ) ,
15
39
open : true ,
16
40
...toast
17
41
}
18
42
19
- const index = toasts . value . findIndex ( ( t : Toast ) => t . id === body . id )
20
- if ( index === - 1 ) {
21
- toasts . value . push ( body )
22
- }
43
+ queue . push ( body )
23
44
24
- toasts . value = toasts . value . slice ( - 5 )
45
+ await processQueue ( )
25
46
26
47
return body
27
48
}
You can’t perform that action at this time.
0 commit comments