-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
214 lines (190 loc) · 6.43 KB
/
index.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
// tslint:disable:max-classes-per-file
export const isCancelledPromiseError = (err: Error) => {
return CancelledPromiseError.isCancelledPromiseError(err);
};
const isPromise = (p: any): p is Promise<any> => {
return p instanceof Promise;
};
export interface ICancelablePromise<T> extends Promise<T> {
cancel: () => void;
}
const errorSymbol = Symbol();
class CancelledPromiseError extends Error {
public static isCancelledPromiseError(err: any): err is CancelledPromiseError {
return err[errorSymbol] === true;
}
private [errorSymbol] = true;
constructor(message: string = "Promise was cancelled") {
super(message);
}
}
export class CancelableEvents {
public static isCancelledPromiseError = (err: Error) => {
return CancelledPromiseError.isCancelledPromiseError(err);
}
private isDead: boolean = false;
private timeouts: Set<number> = new Set();
private intervals: Set<number> = new Set();
private cancelableEvents: Set<() => void> = new Set();
/**
* Call to invalidate all listeners
* After calling this method, the instance is cancelled and can't add new listeners
*/
public cancelAll() {
Array.from(this.timeouts).forEach((c) => {
this.createCancelTimeoutCB(c)();
});
Array.from(this.intervals).forEach((c) => {
this.createCancelIntervalCb(c)();
});
Array.from(this.cancelableEvents).forEach((c) => c());
this.isDead = true;
}
/**
*
* @param handler
* @param timeout
* @param args
* Same as window.setTimeout
*/
public setTimeout(handler: (...args: any[]) => void, timeout: number = 0, ...args: any[]) {
this.assertIsDead();
const timeoutId: number = setTimeout(this.onTimeoutCB, timeout, handler) as any;
this.timeouts.add(timeoutId);
const cancel = this.createCancelTimeoutCB(timeoutId);
return { cancel };
}
/**
*
* @param handler
* @param timer
* @param args
* Same as window.setInterval
*/
public setInterval(handler: (...args: any[]) => void, timer: number = 0, ...args: any[]) {
this.assertIsDead();
const intervalId: number = setInterval(handler, timer, ...args) as any;
this.intervals.add(intervalId); // avoid nodeJs.timer and window.
const cancel = this.createCancelIntervalCb(intervalId);
return { cancel };
}
/**
*
* @param item object with cancel method
* @param callableKey key of the object, value must be function, this function will be called when cancelling
*/
public addCustomCancelable<T>(item: T, callableKey: keyof T) {
this.assertIsDead();
const cb = item[callableKey];
if (!isFunction(cb)) {
throw new Error(`key ${callableKey} is not a function but ${typeof item[callableKey]}`);
}
const cancel = () => {
cb.call(item);
this.cancelableEvents.delete(cancel);
};
this.cancelableEvents.add(cancel);
return { cancel };
}
/**
*
* @param type
* @param listener
* same as window.addEventListener
*/
public addWindowEventListener<K extends keyof WindowEventMap>(type: K, listener: (ev: WindowEventMap[K]) => any) {
this.assertIsDead();
const cb = (ev: WindowEventMap[K]) => {
return listener(ev);
};
const cancel = () => {
window.removeEventListener(type, cb);
this.cancelableEvents.delete(cancel);
};
this.cancelableEvents.add(cancel);
window.addEventListener(type, cb);
return { cancel };
}
/**
*
* @param type
* @param listener
* Same as document.addEventListener
*/
// tslint:disable-next-line:max-line-length
public addDocumentEventListener<K extends keyof DocumentEventMap>(type: K, listener: (ev: DocumentEventMap[K]) => any) {
this.assertIsDead();
const cb = (ev: DocumentEventMap[K]) => {
return listener(ev);
};
const cancel = () => {
document.removeEventListener(type, cb);
this.cancelableEvents.delete(cancel);
};
this.cancelableEvents.add(cancel);
document.addEventListener(type, cb);
return { cancel };
}
/**
*
* @param handler
* @param args
* Add promise, handler should actually return a promise
*/
public promise<T>(handler: ((...args: any[]) => Promise<T>) | Promise<T>, ...args: any[]): ICancelablePromise<T> {
this.assertIsDead();
let isCanceled = false;
let isFulfilled = false;
// tslint:disable-next-line:variable-name
let _reject: (err: Error) => void;
const cancel = () => {
isCanceled = true;
this.cancelableEvents.delete(cancel);
if (!isFulfilled && _reject) {
isFulfilled = true;
_reject(new CancelledPromiseError());
}
};
this.cancelableEvents.add(cancel);
const promise = new Promise<T>(async (resolve, reject) => {
_reject = reject;
try {
const res: T = await (isPromise(handler) ? handler : handler(...args));
if (isFulfilled) {
return;
}
// basically, this line should never happen...
if (isCanceled) {
reject(new CancelledPromiseError());
return;
}
resolve(res);
} catch (err) {
reject(err);
} finally {
isFulfilled = true;
}
});
(promise as ICancelablePromise<T>).cancel = cancel;
return (promise as ICancelablePromise<T>);
}
private onTimeoutCB = (handler: (...args: any[]) => void, ...args: any[]) => {
handler(...args);
}
private createCancelTimeoutCB = (timeoutId: number) => () => {
clearTimeout(timeoutId);
this.timeouts.delete(timeoutId);
}
private createCancelIntervalCb = (intervalId: number) => () => {
clearInterval(intervalId);
this.intervals.delete(intervalId);
}
private assertIsDead() {
if (this.isDead) {
throw new Error("Can't add listener to cancelled instance");
}
}
}
const isFunction = (t: any): t is () => void => {
return "function" === typeof t;
};