-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathToast.ts
52 lines (39 loc) · 1.07 KB
/
Toast.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
import { createSignal } from 'solid-js';
import type { Accessor } from 'solid-js';
type ToastState = {
fadeMs: number;
show: boolean;
messages: string[];
};
type Toast = [Accessor<ToastState>, (text: string) => void];
function createToast(persistMs: number, fadeMs: number): Toast {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let show = false;
const messages: string[] = [];
const [toast, setToast] = createSignal<ToastState>(makeState());
return [toast, display];
// ---
function makeState() {
return { fadeMs, show, messages };
}
function reset(): void {
show = false;
messages.length = 0;
timeoutId = undefined;
setToast(makeState());
}
function display(text: string): void {
messages.push(text);
show = true;
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(fadeOut, persistMs);
setToast(makeState());
}
function fadeOut() {
show = false;
timeoutId = setTimeout(reset, fadeMs);
setToast(makeState());
}
}
export { createToast };
export type { Toast, ToastState };