Skip to content

Commit 1bd1221

Browse files
committed
feat: add useVueSonner
get history of toasts
1 parent 6dd1510 commit 1bd1221

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

packages/hooks.ts

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { ref, watchEffect } from 'vue'
2+
import type { ToastT } from './types'
3+
import { ToastState } from './state'
24

3-
export const useIsDocumentHidden = () => {
5+
export function useIsDocumentHidden() {
46
const isDocumentHidden = ref(false)
57

68
watchEffect(() => {
@@ -12,6 +14,36 @@ export const useIsDocumentHidden = () => {
1214
})
1315

1416
return {
15-
isDocumentHidden
17+
isDocumentHidden,
1618
}
1719
}
20+
21+
export function useVueSonner() {
22+
const activeToasts = ref<ToastT[]>([])
23+
24+
watchEffect((onInvalidate) => {
25+
const unsubscribe = ToastState.subscribe((toast) => {
26+
if ('dismiss' in toast && toast.dismiss) {
27+
return activeToasts.value.filter((t) => t.id !== toast.id);
28+
}
29+
30+
const existingToastIndex = activeToasts.value.findIndex((t) => t.id === toast.id);
31+
if (existingToastIndex !== -1) {
32+
const updatedToasts = [...activeToasts.value];
33+
updatedToasts[existingToastIndex] = { ...updatedToasts[existingToastIndex], ...toast };
34+
35+
activeToasts.value = updatedToasts
36+
} else {
37+
activeToasts.value = [toast, ...activeToasts.value]
38+
}
39+
})
40+
41+
onInvalidate(() => {
42+
unsubscribe()
43+
})
44+
})
45+
46+
return {
47+
activeToasts
48+
}
49+
}

0 commit comments

Comments
 (0)