aboutsummaryrefslogtreecommitdiff
path: root/components/toast.tsx
blob: 3a72ae12cdeb202c0a9425c1674de4a788cc4b0e (plain)
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
import { createContext, ReactNode, useState } from 'react';

import CloseIcon from '@material-ui/icons/Close';

function ToastArea(props: {
	children?: ReactNode;
	rerender?: boolean;
}) {
	return <div
		id='ToastArea'
		className='posfix abscenterh'
	>
		{props.children}
	</div>;
}

function Toast(props: {
	text?: string;
	description?: string;
	icon?: ReactNode;
	children?: ReactNode;
	type?: 'normal' | 'confirmation' | 'error';
}) {
	var [visible, setVisibility] = useState(true);

	setTimeout(() => setVisibility(false), 10e3);

	return visible && <div className={'round-t drop-1 toast ' + props.type}>
		{props.children
			|| <div
				className={'inner pad-m posrel '
					+ (props.description ? 'hasDescription' : '') + ' '
					+ (props.icon ? 'hasIcon' : '')}
			>
				<div className='icon posabs abscenterv'>
					{props.icon}
				</div>
				<div className='content nosel posabs abscenterv'>
					<h2>{props.text}</h2>
					<p>{props.description}</p>
				</div>
				<div
					className='closeIcon posabs abscenterv'
					onClick={() => setVisibility(false)}
				>
					<CloseIcon />
				</div>
			</div>}
	</div>;
}

export type toastSettings = {
	message: string;
	description?: string;
	type: 'confirmation' | 'normal' | 'error';
	icon?: ReactNode;
};
export type toastType = (settings: toastSettings) => void;
export var ToastContext = createContext<{ toast?: toastType; }>({});
var toasts: Array<JSX.Element> = [];

export function ToastContextWrapper(props: { children?: ReactNode; }) {
	var [dummyState, rerender] = useState(false);

	return <ToastContext.Provider
		value={{
			toast: options => {
				toasts.push(
					<Toast
						type={options.type}
						text={options.message}
						description={options.description}
						icon={options.icon}
					/>,
				);
				rerender(!dummyState);
			},
		}}
	>
		{props.children}
		<ToastArea rerender={dummyState}>
			{toasts}
		</ToastArea>
	</ToastContext.Provider>;
}