forked from emilkowalski/sonner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.ts
238 lines (201 loc) · 7.07 KB
/
state.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import type { ExternalToast, PromiseData, PromiseT, ToastT, ToastToDismiss, ToastTypes } from './types';
import React from 'react';
let toastsCounter = 1;
type titleT = (() => React.ReactNode) | React.ReactNode;
class Observer {
subscribers: Array<(toast: ExternalToast | ToastToDismiss) => void>;
toasts: Array<ToastT | ToastToDismiss>;
constructor() {
this.subscribers = [];
this.toasts = [];
}
// We use arrow functions to maintain the correct `this` reference
subscribe = (subscriber: (toast: ToastT | ToastToDismiss) => void) => {
this.subscribers.push(subscriber);
return () => {
const index = this.subscribers.indexOf(subscriber);
this.subscribers.splice(index, 1);
};
};
publish = (data: ToastT) => {
this.subscribers.forEach((subscriber) => subscriber(data));
};
addToast = (data: ToastT) => {
this.publish(data);
this.toasts = [...this.toasts, data];
};
create = (
data: ExternalToast & {
message?: titleT;
type?: ToastTypes;
promise?: PromiseT;
jsx?: React.ReactElement;
},
) => {
const { message, ...rest } = data;
const id = typeof data?.id === 'number' || data.id?.length > 0 ? data.id : toastsCounter++;
const alreadyExists = this.toasts.find((toast) => {
return toast.id === id;
});
const dismissible = data.dismissible === undefined ? true : data.dismissible;
if (alreadyExists) {
this.toasts = this.toasts.map((toast) => {
if (toast.id === id) {
this.publish({ ...toast, ...data, id, title: message });
return {
...toast,
...data,
id,
dismissible,
title: message,
};
}
return toast;
});
} else {
this.addToast({ title: message, ...rest, dismissible, id });
}
return id;
};
dismiss = (id?: number | string) => {
if (!id) {
this.toasts.forEach((toast) => {
this.subscribers.forEach((subscriber) => subscriber({ id: toast.id, dismiss: true }));
});
}
this.subscribers.forEach((subscriber) => subscriber({ id, dismiss: true }));
return id;
};
message = (message: titleT | React.ReactNode, data?: ExternalToast) => {
return this.create({ ...data, message });
};
error = (message: titleT | React.ReactNode, data?: ExternalToast) => {
return this.create({ ...data, message, type: 'error' });
};
success = (message: titleT | React.ReactNode, data?: ExternalToast) => {
return this.create({ ...data, type: 'success', message });
};
info = (message: titleT | React.ReactNode, data?: ExternalToast) => {
return this.create({ ...data, type: 'info', message });
};
warning = (message: titleT | React.ReactNode, data?: ExternalToast) => {
return this.create({ ...data, type: 'warning', message });
};
loading = (message: titleT | React.ReactNode, data?: ExternalToast) => {
return this.create({ ...data, type: 'loading', message });
};
promise = <ToastData>(promise: PromiseT<ToastData>, data?: PromiseData<ToastData>) => {
if (!data) {
// Nothing to show
return;
}
let id: string | number | undefined = undefined;
if (data.loading !== undefined) {
id = this.create({
...data,
promise,
type: 'loading',
message: data.loading,
description: typeof data.description !== 'function' ? data.description : undefined,
});
}
const p = promise instanceof Promise ? promise : promise();
let shouldDismiss = id !== undefined;
let result: ['resolve', ToastData] | ['reject', unknown];
const originalPromise = p
.then(async (response) => {
result = ['resolve', response];
const isReactElementResponse = React.isValidElement(response);
if (isReactElementResponse) {
shouldDismiss = false;
this.create({ id, type: 'default', message: response });
} else if (isHttpResponse(response) && !response.ok) {
shouldDismiss = false;
const message =
typeof data.error === 'function' ? await data.error(`HTTP error! status: ${response.status}`) : data.error;
const description =
typeof data.description === 'function'
? await data.description(`HTTP error! status: ${response.status}`)
: data.description;
this.create({ id, type: 'error', message, description });
} else if (data.success !== undefined) {
shouldDismiss = false;
const message = typeof data.success === 'function' ? await data.success(response) : data.success;
const description =
typeof data.description === 'function' ? await data.description(response) : data.description;
this.create({ id, type: 'success', message, description });
}
})
.catch(async (error) => {
result = ['reject', error];
if (data.error !== undefined) {
shouldDismiss = false;
const message = typeof data.error === 'function' ? await data.error(error) : data.error;
const description = typeof data.description === 'function' ? await data.description(error) : data.description;
this.create({ id, type: 'error', message, description });
}
})
.finally(() => {
if (shouldDismiss) {
// Toast is still in load state (and will be indefinitely — dismiss it)
this.dismiss(id);
id = undefined;
}
data.finally?.();
});
const unwrap = () =>
new Promise<ToastData>((resolve, reject) =>
originalPromise.then(() => (result[0] === 'reject' ? reject(result[1]) : resolve(result[1]))).catch(reject),
);
if (typeof id !== 'string' && typeof id !== 'number') {
// cannot Object.assign on undefined
return { unwrap };
} else {
return Object.assign(id, { unwrap });
}
};
custom = (jsx: (id: number | string) => React.ReactElement, data?: ExternalToast) => {
const id = data?.id || toastsCounter++;
this.create({ jsx: jsx(id), id, ...data });
return id;
};
}
export const ToastState = new Observer();
// bind this to the toast function
const toastFunction = (message: titleT, data?: ExternalToast) => {
const id = data?.id || toastsCounter++;
ToastState.addToast({
title: message,
...data,
id,
});
return id;
};
const isHttpResponse = (data: any): data is Response => {
return (
data &&
typeof data === 'object' &&
'ok' in data &&
typeof data.ok === 'boolean' &&
'status' in data &&
typeof data.status === 'number'
);
};
const basicToast = toastFunction;
const getHistory = () => ToastState.toasts;
// We use `Object.assign` to maintain the correct types as we would lose them otherwise
export const toast = Object.assign(
basicToast,
{
success: ToastState.success,
info: ToastState.info,
warning: ToastState.warning,
error: ToastState.error,
custom: ToastState.custom,
message: ToastState.message,
promise: ToastState.promise,
dismiss: ToastState.dismiss,
loading: ToastState.loading,
},
{ getHistory },
);