-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathnotifications.ts
109 lines (99 loc) · 2.43 KB
/
notifications.ts
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { writable } from "svelte/store"
const NOTIFICATION_TIMEOUT = 3000
interface Notification {
id: string
type: string
message: string
icon: string
dismissable: boolean
action: (() => void) | null
actionMessage: string | null
wide: boolean
dismissTimeout: number
}
export const createNotificationStore = () => {
const timeoutIds = new Set<ReturnType<typeof setTimeout>>()
const _notifications = writable<Notification[]>([], () => {
return () => {
// clear all the timers
timeoutIds.forEach(timeoutId => {
clearTimeout(timeoutId)
})
_notifications.set([])
}
})
let block = false
const blockNotifications = (timeout = 1000) => {
block = true
setTimeout(() => (block = false), timeout)
}
const send = (
message: string,
{
type = "default",
icon = "",
autoDismiss = true,
action = null,
actionMessage = null,
wide = false,
dismissTimeout = NOTIFICATION_TIMEOUT,
}: {
type?: string
icon?: string
autoDismiss?: boolean
action?: (() => void) | null
actionMessage?: string | null
wide?: boolean
dismissTimeout?: number
} = {}
) => {
if (block) {
return
}
let _id = id()
_notifications.update(state => {
return [
...state,
{
id: _id,
type,
message,
icon,
dismissable: !autoDismiss,
action,
actionMessage,
wide,
dismissTimeout,
},
]
})
if (autoDismiss) {
const timeoutId = setTimeout(() => {
dismissNotification(_id)
}, dismissTimeout)
timeoutIds.add(timeoutId)
}
}
const dismissNotification = (id: string) => {
_notifications.update(state => {
return state.filter(n => n.id !== id)
})
}
const { subscribe } = _notifications
return {
subscribe,
send,
info: (msg: string) => send(msg, { type: "info", icon: "Info" }),
error: (msg: string) =>
send(msg, { type: "error", icon: "Alert", autoDismiss: false }),
warning: (msg: string) => send(msg, { type: "warning", icon: "Alert" }),
success: (msg: string) =>
send(msg, { type: "success", icon: "CheckmarkCircle" }),
blockNotifications,
dismiss: dismissNotification,
}
}
function id(): string {
return "_" + Math.random().toString(36).slice(2, 9)
}
export const notifications = createNotificationStore()