forked from Dogfalo/materialize
-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathtoasts.ts
303 lines (277 loc) · 8.28 KB
/
toasts.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { BaseOptions } from "./component";
export interface ToastOptions extends BaseOptions {
/**
* The content of the Toast.
* @default ""
*/
text: string;
/**
* Element Id for the tooltip.
* @default ""
*/
toastId?: string;
/**
* Length in ms the Toast stays before dismissal.
* @default 4000
*/
displayLength: number;
/**
* Transition in duration in milliseconds.
* @default 300
*/
inDuration: number;
/**
* Transition out duration in milliseconds.
* @default 375
*/
outDuration: number;
/**
* Classes to be added to the toast element.
* @default ""
*/
classes: string;
/**
* Callback function called when toast is dismissed.
* @default null
*/
completeCallback: () => void;
/**
* The percentage of the toast's width it takes fora drag
* to dismiss a Toast.
* @default 0.8
*/
activationPercent: number;
}
let _defaults: ToastOptions = {
text: '',
displayLength: 4000,
inDuration: 300,
outDuration: 375,
classes: '',
completeCallback: null,
activationPercent: 0.8
};
export class Toast {
/** The toast element. */
el: HTMLElement;
/**
* The remaining amount of time in ms that the toast
* will stay before dismissal.
*/
timeRemaining: number;
/**
* Describes the current pan state of the Toast.
*/
panning: boolean;
options: ToastOptions;
message: string;
counterInterval: NodeJS.Timeout;
wasSwiped: boolean;
startingXPos: number;
xPos: number;
time: number;
deltaX: number;
velocityX: number;
static _toasts: Toast[];
static _container: any;
static _draggedToast: Toast;
constructor(options: Partial<ToastOptions>) {
this.options = {
...Toast.defaults,
...options
};
this.message = this.options.text;
this.panning = false;
this.timeRemaining = this.options.displayLength;
if (Toast._toasts.length === 0) {
Toast._createContainer();
}
// Create new toast
Toast._toasts.push(this);
let toastElement = this._createToast();
(toastElement as any).M_Toast = this;
this.el = toastElement;
this._animateIn();
this._setTimer();
}
static get defaults(): ToastOptions {
return _defaults;
}
static getInstance(el: HTMLElement): Toast {
return (el as any).M_Toast;
}
static _createContainer() {
const container = document.createElement('div');
container.setAttribute('id', 'toast-container');
// Add event handler
container.addEventListener('touchstart', Toast._onDragStart);
container.addEventListener('touchmove', Toast._onDragMove);
container.addEventListener('touchend', Toast._onDragEnd);
container.addEventListener('mousedown', Toast._onDragStart);
document.addEventListener('mousemove', Toast._onDragMove);
document.addEventListener('mouseup', Toast._onDragEnd);
document.body.appendChild(container);
Toast._container = container;
}
static _removeContainer() {
document.removeEventListener('mousemove', Toast._onDragMove);
document.removeEventListener('mouseup', Toast._onDragEnd);
Toast._container.remove();
Toast._container = null;
}
static _onDragStart(e: TouchEvent | MouseEvent) {
if (e.target && (<HTMLElement>e.target).closest('.toast')) {
const toastElem = (<HTMLElement>e.target).closest('.toast');
const toast: Toast = (toastElem as any).M_Toast;
toast.panning = true;
Toast._draggedToast = toast;
toast.el.classList.add('panning');
toast.el.style.transition = '';
toast.startingXPos = Toast._xPos(e);
toast.time = Date.now();
toast.xPos = Toast._xPos(e);
}
}
static _onDragMove(e: TouchEvent | MouseEvent) {
if (!!Toast._draggedToast) {
e.preventDefault();
const toast = Toast._draggedToast;
toast.deltaX = Math.abs(toast.xPos - Toast._xPos(e));
toast.xPos = Toast._xPos(e);
toast.velocityX = toast.deltaX / (Date.now() - toast.time);
toast.time = Date.now();
const totalDeltaX = toast.xPos - toast.startingXPos;
const activationDistance = toast.el.offsetWidth * toast.options.activationPercent;
toast.el.style.transform = `translateX(${totalDeltaX}px)`;
toast.el.style.opacity = (1 - Math.abs(totalDeltaX / activationDistance)).toString();
}
}
static _onDragEnd() {
if (!!Toast._draggedToast) {
let toast = Toast._draggedToast;
toast.panning = false;
toast.el.classList.remove('panning');
let totalDeltaX = toast.xPos - toast.startingXPos;
let activationDistance = toast.el.offsetWidth * toast.options.activationPercent;
let shouldBeDismissed = Math.abs(totalDeltaX) > activationDistance || toast.velocityX > 1;
// Remove toast
if (shouldBeDismissed) {
toast.wasSwiped = true;
toast.dismiss();
// Animate toast back to original position
}
else {
toast.el.style.transition = 'transform .2s, opacity .2s';
toast.el.style.transform = '';
toast.el.style.opacity = '';
}
Toast._draggedToast = null;
}
}
static _xPos(e: TouchEvent | MouseEvent) {
if (e.type.startsWith("touch") && (e as TouchEvent).targetTouches.length >= 1) {
return (e as TouchEvent).targetTouches[0].clientX;
}
// mouse event
return (e as MouseEvent).clientX;
}
/**
* dismiss all toasts.
*/
static dismissAll() {
for (let toastIndex in Toast._toasts) {
Toast._toasts[toastIndex].dismiss();
}
}
_createToast() {
let toast: HTMLElement = this.options.toastId
? document.getElementById(this.options.toastId)
: document.createElement('div');
if (toast instanceof HTMLTemplateElement) {
const node = (toast as HTMLTemplateElement).content.cloneNode(true);
toast = ((node as HTMLElement).firstElementChild as HTMLElement);
}
toast.classList.add('toast');
toast.setAttribute('role', 'alert');
toast.setAttribute('aria-live', 'assertive');
toast.setAttribute('aria-atomic', 'true');
// Add custom classes onto toast
if (this.options.classes.length > 0) {
toast.classList.add(...this.options.classes.split(' '));
}
if (this.message) toast.innerText = this.message;
Toast._container.appendChild(toast);
return toast;
}
_animateIn() {
// Animate toast in
this.el.style.display = "";
this.el.style.opacity = '0';
// easeOutCubic
this.el.style.transition = `
top ${this.options.inDuration}ms ease,
opacity ${this.options.inDuration}ms ease
`;
setTimeout(() => {
this.el.style.top = '0';
this.el.style.opacity = '1';
}, 1);
}
/**
* Create setInterval which automatically removes toast when timeRemaining >= 0
* has been reached.
*/
_setTimer() {
if (this.timeRemaining !== Infinity) {
this.counterInterval = setInterval(() => {
// If toast is not being dragged, decrease its time remaining
if (!this.panning) {
this.timeRemaining -= 20;
}
// Animate toast out
if (this.timeRemaining <= 0) {
this.dismiss();
}
}, 20);
}
}
/**
* Dismiss toast with animation.
*/
dismiss() {
window.clearInterval(this.counterInterval);
let activationDistance = this.el.offsetWidth * this.options.activationPercent;
if (this.wasSwiped) {
this.el.style.transition = 'transform .05s, opacity .05s';
this.el.style.transform = `translateX(${activationDistance}px)`;
this.el.style.opacity = '0';
}
// easeOutExpo
this.el.style.transition = `
margin ${this.options.outDuration}ms ease,
opacity ${this.options.outDuration}ms ease`;
setTimeout(() => {
this.el.style.opacity = '0';
this.el.style.marginTop = '-40px';
}, 1);
setTimeout(() => {
// Call the optional callback
if (typeof this.options.completeCallback === 'function') {
this.options.completeCallback();
}
// Remove toast from DOM
if (this.el.id != this.options.toastId) {
this.el.remove();
Toast._toasts.splice(Toast._toasts.indexOf(this), 1);
if (Toast._toasts.length === 0) {
Toast._removeContainer();
}
}
}, this.options.outDuration);
}
static {
Toast._toasts = [];
Toast._container = null;
Toast._draggedToast = null;
}
}