forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevent_target.js
454 lines (378 loc) · 11.7 KB
/
event_target.js
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
'use strict';
const {
ArrayFrom,
Error,
Map,
Object,
Set,
Symbol,
NumberIsNaN,
} = primordials;
const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_EVENT_RECURSION,
ERR_OUT_OF_RANGE,
ERR_MISSING_ARGS
}
} = require('internal/errors');
const perf_hooks = require('perf_hooks');
const { customInspectSymbol } = require('internal/util');
const { inspect } = require('util');
const kEvents = Symbol('kEvents');
const kStop = Symbol('kStop');
const kTarget = Symbol('kTarget');
const kNewListener = Symbol('kNewListener');
const kRemoveListener = Symbol('kRemoveListener');
class Event {
#type = undefined;
#defaultPrevented = false;
#cancelable = false;
#timestamp = perf_hooks.performance.now();
// None of these are currently used in the Node.js implementation
// of EventTarget because there is no concept of bubbling or
// composition. We preserve their values in Event but they are
// non-ops and do not carry any semantics in Node.js
#bubbles = false;
#composed = false;
#propagationStopped = false;
constructor(type, options) {
if (arguments.length === 0) {
throw new ERR_MISSING_ARGS('type');
}
if (options != null && typeof options !== 'object')
throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
const { cancelable, bubbles, composed } = { ...options };
this.#cancelable = !!cancelable;
this.#bubbles = !!bubbles;
this.#composed = !!composed;
this.#type = `${type}`;
this.#propagationStopped = false;
// isTrusted is special (LegacyUnforgeable)
Object.defineProperty(this, 'isTrusted', {
get() { return false; },
set(ignoredValue) { return false; },
enumerable: true,
configurable: false
});
this[kTarget] = null;
}
[customInspectSymbol](depth, options) {
const name = this.constructor.name;
if (depth < 0)
return name;
const opts = Object.assign({}, options, {
dept: options.depth === null ? null : options.depth - 1
});
return `${name} ${inspect({
type: this.#type,
defaultPrevented: this.#defaultPrevented,
cancelable: this.#cancelable,
timeStamp: this.#timestamp,
}, opts)}`;
}
stopImmediatePropagation() {
this[kStop] = true;
}
preventDefault() {
this.#defaultPrevented = true;
}
get target() { return this[kTarget]; }
get currentTarget() { return this[kTarget]; }
get srcElement() { return this[kTarget]; }
get type() { return this.#type; }
get cancelable() { return this.#cancelable; }
get defaultPrevented() { return this.#cancelable && this.#defaultPrevented; }
get timeStamp() { return this.#timestamp; }
// The following are non-op and unused properties/methods from Web API Event.
// These are not supported in Node.js and are provided purely for
// API completeness.
composedPath() { return this[kTarget] ? [this[kTarget]] : []; }
get returnValue() { return !this.defaultPrevented; }
get bubbles() { return this.#bubbles; }
get composed() { return this.#composed; }
get eventPhase() {
return this[kTarget] ? 2 : 0; // Equivalent to AT_TARGET or NONE
}
get cancelBubble() { return this.#propagationStopped; }
set cancelBubble(value) {
if (value) {
this.stopPropagation();
}
}
stopPropagation() {
this.#propagationStopped = true;
}
get [Symbol.toStringTag]() { return 'Event'; }
}
// The listeners for an EventTarget are maintained as a linked list.
// Unfortunately, the way EventTarget is defined, listeners are accounted
// using the tuple [handler,capture], and even if we don't actually make
// use of capture or bubbling, in order to be spec compliant we have to
// take on the additional complexity of supporting it. Fortunately, using
// the linked list makes dispatching faster, even if adding/removing is
// slower.
class Listener {
next;
previous;
listener;
callback;
once;
capture;
passive;
constructor(previous, listener, once, capture, passive) {
if (previous !== undefined)
previous.next = this;
this.previous = previous;
this.listener = listener;
this.once = once;
this.capture = capture;
this.passive = passive;
this.callback =
typeof listener === 'function' ?
listener :
listener.handleEvent.bind(listener);
}
same(listener, capture) {
return this.listener === listener && this.capture === capture;
}
remove() {
if (this.previous !== undefined)
this.previous.next = this.next;
if (this.next !== undefined)
this.next.previous = this.previous;
}
}
class EventTarget {
[kEvents] = new Map();
#emitting = new Set();
[kNewListener](size, type, listener, once, capture, passive) {}
[kRemoveListener](size, type, listener, capture) {}
addEventListener(type, listener, options = {}) {
validateListener(listener);
type = String(type);
const {
once,
capture,
passive
} = validateEventListenerOptions(options);
let root = this[kEvents].get(type);
if (root === undefined) {
root = { size: 1, next: undefined };
// This is the first handler in our linked list.
new Listener(root, listener, once, capture, passive);
this[kNewListener](root.size, type, listener, once, capture, passive);
this[kEvents].set(type, root);
return;
}
let handler = root.next;
let previous;
// We have to walk the linked list to see if we have a match
while (handler !== undefined && !handler.same(listener, capture)) {
previous = handler;
handler = handler.next;
}
if (handler !== undefined) { // Duplicate! Ignore
return;
}
new Listener(previous, listener, once, capture, passive);
root.size++;
this[kNewListener](root.size, type, listener, once, capture, passive);
}
removeEventListener(type, listener, options = {}) {
validateListener(listener);
type = String(type);
const { capture } = validateEventListenerOptions(options);
const root = this[kEvents].get(type);
if (root === undefined || root.next === undefined)
return;
let handler = root.next;
while (handler !== undefined) {
if (handler.same(listener, capture)) {
handler.remove();
root.size--;
if (root.size === 0)
this[kEvents].delete(type);
this[kRemoveListener](root.size, type, listener, capture);
break;
}
handler = handler.next;
}
}
dispatchEvent(event) {
if (!(event instanceof Event)) {
throw new ERR_INVALID_ARG_TYPE('event', 'Event', event);
}
if (this.#emitting.has(event.type) ||
event[kTarget] !== null) {
throw new ERR_EVENT_RECURSION(event.type);
}
const root = this[kEvents].get(event.type);
if (root === undefined || root.next === undefined)
return true;
event[kTarget] = this;
this.#emitting.add(event.type);
let handler = root.next;
let next;
while (handler !== undefined &&
(handler.passive || event[kStop] !== true)) {
// Cache the next item in case this iteration removes the current one
next = handler.next;
if (handler.once) {
handler.remove();
root.size--;
}
try {
const result = handler.callback.call(this, event);
if (result !== undefined && result !== null)
addCatch(this, result, event);
} catch (err) {
emitUnhandledRejectionOrErr(this, err, event);
}
handler = next;
}
this.#emitting.delete(event.type);
event[kTarget] = undefined;
return event.defaultPrevented === true ? false : true;
}
[customInspectSymbol](depth, options) {
const name = this.constructor.name;
if (depth < 0)
return name;
const opts = Object.assign({}, options, {
dept: options.depth === null ? null : options.depth - 1
});
return `${name} ${inspect({}, opts)}`;
}
get [Symbol.toStringTag]() { return 'EventTarget'; }
}
Object.defineProperties(EventTarget.prototype, {
addEventListener: { enumerable: true },
removeEventListener: { enumerable: true },
dispatchEvent: { enumerable: true }
});
class NodeEventTarget extends EventTarget {
static defaultMaxListeners = 10;
#maxListeners = NodeEventTarget.defaultMaxListeners;
#maxListenersWarned = false;
[kNewListener](size, type, listener, once, capture, passive) {
if (this.#maxListeners > 0 &&
size > this.#maxListeners &&
!this.#maxListenersWarned) {
this.#maxListenersWarned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
const w = new Error('Possible EventTarget memory leak detected. ' +
`${size} ${type} listeners ` +
`added to ${inspect(this, { depth: -1 })}. Use ` +
'setMaxListeners() to increase limit');
w.name = 'MaxListenersExceededWarning';
w.target = this;
w.type = type;
w.count = size;
process.emitWarning(w);
}
}
setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n);
}
this.#maxListeners = n;
return this;
}
getMaxListeners() {
return this.#maxListeners;
}
eventNames() {
return ArrayFrom(this[kEvents].keys());
}
listenerCount(type) {
const root = this[kEvents].get(String(type));
return root !== undefined ? root.size : 0;
}
off(type, listener, options) {
this.removeEventListener(type, listener, options);
return this;
}
removeListener(type, listener, options) {
this.removeEventListener(type, listener, options);
return this;
}
on(type, listener) {
this.addEventListener(type, listener);
return this;
}
addListener(type, listener) {
this.addEventListener(type, listener);
return this;
}
once(type, listener) {
this.addEventListener(type, listener, { once: true });
return this;
}
removeAllListeners(type) {
if (type !== undefined) {
this[kEvents].delete(String(type));
} else {
this[kEvents].clear();
}
}
}
Object.defineProperties(NodeEventTarget.prototype, {
setMaxListeners: { enumerable: true },
getMaxListeners: { enumerable: true },
eventNames: { enumerable: true },
listenerCount: { enumerable: true },
off: { enumerable: true },
removeListener: { enumerable: true },
on: { enumerable: true },
addListener: { enumerable: true },
once: { enumerable: true },
removeAllListeners: { enumerable: true },
});
// EventTarget API
function validateListener(listener) {
if (typeof listener === 'function' ||
(listener != null &&
typeof listener === 'object' &&
typeof listener.handleEvent === 'function')) {
return;
}
throw new ERR_INVALID_ARG_TYPE('listener', 'EventListener', listener);
}
function validateEventListenerOptions(options) {
if (typeof options === 'boolean') {
options = { capture: options };
}
if (options == null || typeof options !== 'object')
throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
const {
once = false,
capture = false,
passive = false,
} = options;
return {
once: !!once,
capture: !!capture,
passive: !!passive,
};
}
function addCatch(that, promise, event) {
const then = promise.then;
if (typeof then === 'function') {
then.call(promise, undefined, function(err) {
// The callback is called with nextTick to avoid a follow-up
// rejection from this promise.
process.nextTick(emitUnhandledRejectionOrErr, that, err, event);
});
}
}
function emitUnhandledRejectionOrErr(that, err, event) {
process.emit('error', err, event);
}
// EventEmitter-ish API:
module.exports = {
Event,
EventTarget,
NodeEventTarget,
};