-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathevent-target.cpp
More file actions
599 lines (489 loc) · 19.1 KB
/
event-target.cpp
File metadata and controls
599 lines (489 loc) · 19.1 KB
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
#include "event-target.h"
#include "encode.h"
#include "event.h"
#include "../dom-exception.h"
#include "js/GCPolicyAPI.h"
#include "mozilla/Assertions.h"
namespace {
// https://dom.spec.whatwg.org/#concept-flatten-options
bool flatten_opts(JSContext *cx, JS::HandleValue opts, bool *rval) {
// To flatten options, run these steps:
// - If options is a boolean, then return options.
if (opts.isBoolean()) {
*rval = opts.toBoolean();
return true;
}
// Otherwise:
// - Return options["capture"].
if (opts.isObject()) {
JS::RootedObject obj(cx, &opts.toObject());
JS::RootedValue val(cx);
if (!JS_GetProperty(cx, obj, "capture", &val)) {
return false;
}
*rval = JS::ToBoolean(val);
}
return true;
}
// https://dom.spec.whatwg.org/#event-flatten-more
bool flatten_more_opts(JSContext *cx, JS::HandleValue opts, bool *capture, bool *once,
JS::MutableHandleValue passive, JS::MutableHandleValue signal) {
// To flatten more options, run these steps:
// - Let capture be the result of flattening options.
*capture = false;
if (!flatten_opts(cx, opts, capture)) {
return false;
}
// - Let once be false.
*once = false;
// - Let passive and signal be null.
passive.setNull();
signal.setNull();
if (!opts.isObject()) {
return true;
}
// - If options is a dictionary:
JS::RootedObject obj(cx, &opts.toObject());
JS::RootedValue val(cx);
// - Set once to options["once"].
if (!JS_GetProperty(cx, obj, "once", &val)) {
return false;
}
*once = JS::ToBoolean(val);
// - If options["passive"] exists, then set passive to options["passive"].
if (!JS_GetProperty(cx, obj, "passive", &val)) {
return false;
}
if (!val.isUndefined()) {
passive.setBoolean(JS::ToBoolean(val));
}
// - If options["signal"] exists, then set signal to options["signal"].
if (!JS_GetProperty(cx, obj, "signal", &val)) {
return false;
}
if (val.isObject()) { // TODO: check if is instance of AbortSignal
signal.set(val);
}
// - Return capture, passive, once, and signal.
return true;
}
// https://dom.spec.whatwg.org/#default-passive-value
bool default_passive_value() {
// Return true if all of the following are true:
// - type is one of "touchstart", "touchmove", "wheel", or "mousewheel". [TOUCH-EVENTS]
// [UIEVENTS]
// - eventTarget is a Window object, or is a node whose node document is eventTarget, or is a
// node
// whose node document's document element is eventTarget, or is a node whose node document's
// body element is eventTarget. [HTML]
// Return false.
return false;
}
} // namespace
namespace JS {
template <typename T> struct GCPolicy<RefPtr<T>> {
static void trace(JSTracer *trc, RefPtr<T> *tp, const char *name) {
if (T *target = tp->get()) {
GCPolicy<T>::trace(trc, target, name);
}
}
static bool needsSweep(RefPtr<T> *tp) {
if (T *target = tp->get()) {
return GCPolicy<T>::needsSweep(target);
}
return false;
}
static bool isValid(const RefPtr<T> &t) {
if (T *target = t.get()) {
return GCPolicy<T>::isValid(*target);
}
return true;
}
};
} // namespace JS
namespace builtins {
namespace web {
namespace event {
using EventFlag = Event::EventFlag;
using dom_exception::DOMException;
const JSFunctionSpec EventTarget::static_methods[] = {
JS_FS_END,
};
const JSPropertySpec EventTarget::static_properties[] = {
JS_PS_END,
};
const JSFunctionSpec EventTarget::methods[] = {
JS_FN("addEventListener", EventTarget::addEventListener, 0, JSPROP_ENUMERATE),
JS_FN("removeEventListener", EventTarget::removeEventListener, 0, JSPROP_ENUMERATE),
JS_FN("dispatchEvent", EventTarget::dispatchEvent, 0, JSPROP_ENUMERATE),
JS_FS_END,
};
const JSPropertySpec EventTarget::properties[] = {
JS_PS_END,
};
EventTarget::ListenerList *EventTarget::listeners(JSObject *self) {
MOZ_ASSERT(is_instance(self));
auto list = static_cast<ListenerList *>(
JS::GetReservedSlot(self, static_cast<size_t>(EventTarget::Slots::Listeners)).toPrivate());
MOZ_ASSERT(list);
return list;
}
bool EventTarget::addEventListener(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER(2);
RootedValue type(cx, args.get(0));
RootedValue callback(cx, args.get(1));
RootedValue opts(cx, args.get(2));
args.rval().setUndefined();
return add_listener(cx, self, type, callback, opts);
}
bool EventTarget::removeEventListener(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER(2);
RootedValue type(cx, args.get(0));
RootedValue callback(cx, args.get(1));
RootedValue opts(cx, args.get(2));
args.rval().setUndefined();
return remove_listener(cx, self, type, callback, opts);
}
bool EventTarget::dispatchEvent(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER(1);
RootedValue event(cx, args.get(0));
return dispatch_event(cx, self, event, args.rval());
}
// https://dom.spec.whatwg.org/#add-an-event-listener
bool EventTarget::add_listener(JSContext *cx, HandleObject self, HandleValue type_val,
HandleValue callback_val, HandleValue opts_val) {
MOZ_ASSERT(is_instance(self));
// 1. Let capture, passive, once, and signal be the result of flattening more options.
bool capture = false, once = false, passive = false;
RootedValue passive_val(cx);
RootedValue signal_val(cx);
if (!flatten_more_opts(cx, opts_val, &capture, &once, &passive_val, &signal_val)) {
return false;
}
// 2. Add an event listener with this and an event listener whose type is type,
// callback is callback, capture is capture, passive is passive, once is once, and signal is
// signal.
// - If eventTarget is a ServiceWorkerGlobalScope object, its service worker's script resource's
// has
// ever been evaluated flag is set, and listener's type matches the type attribute value of any
// of the service worker events, then report a warning to the console that this might not give
// the expected results.
// N/A
// - If listener's signal is not null and is aborted, then return.
// TODO: add AbortSignal
// - If listener's callback is null, then return.
if (callback_val.isNullOrUndefined()) {
return true;
}
if (!callback_val.isObject()) {
return api::throw_error(cx, api::Errors::TypeError, "addEventListener", "callback",
"be an object");
}
// - If listener's passive is null, then set it to the default passive value given listener's type
// and eventTarget.
passive = passive_val.isNullOrUndefined() ? default_passive_value() : passive_val.toBoolean();
// - If eventTarget's event listener list does not contain an event listener whose type is
// listener's
// type, callback is listener's callback, and capture is listener's capture, then append listener
// to eventTarget's event listener list.
auto encoded = core::encode(cx, type_val);
if (!encoded) {
return false;
}
auto type = std::string_view(encoded);
auto list = listeners(self);
auto it = std::find_if(list->begin(), list->end(), [&](const auto &listener) {
return type == listener->type && callback_val == listener->callback.get() &&
capture == listener->capture;
});
if (it == list->end()) {
auto listener = mozilla::MakeRefPtr<EventListener>();
listener->callback = callback_val;
listener->signal = signal_val;
listener->type = type;
listener->passive = passive;
listener->capture = capture;
listener->once = once;
listener->removed = false;
list->append(listener);
} else if((*it)->removed) {
// if existing listener was marked for removal, then move it to the end of the list
// and update its removed flag. This is done to ensure the order of listeners. We only
// update listener's properties that are not check for listener equality.
(*it)->signal = signal_val;
(*it)->passive = passive;
(*it)->once = once;
(*it)->removed = false;
list->erase(it);
list->append(*it);
}
// - If listener's signal is not null, then add the following abort steps to it:
// Remove an event listener with eventTarget and listener.
// TODO: add AbortSignal
return true;
}
// https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener
bool EventTarget::remove_listener(JSContext *cx, HandleObject self, HandleValue type_val,
HandleValue callback_val, HandleValue opts_val) {
MOZ_ASSERT(is_instance(self));
bool capture = false;
if (!flatten_opts(cx, opts_val, &capture)) {
return false;
}
auto encoded = core::encode(cx, type_val);
if (!encoded) {
return false;
}
auto type = std::string_view(encoded);
auto list = listeners(self);
auto it = std::find_if(list->begin(), list->end(), [&](const auto &listener) {
return type == listener->type && callback_val == listener->callback.get() &&
capture == listener->capture;
});
if (it != list->end()) {
(*it)->removed = true;
list->erase(it);
}
return true;
}
// https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent
bool EventTarget::dispatch_event(JSContext *cx, HandleObject self, HandleValue event_val,
MutableHandleValue rval) {
MOZ_ASSERT(is_instance(self));
if (!Event::is_instance(event_val)) {
return api::throw_error(cx, api::Errors::TypeError, "EventTarget.dispatch", "event",
"be an Event");
}
RootedObject event(cx, &event_val.toObject());
// 1. If event's dispatch flag is set, or if its initialized flag is not set,
// then throw an "InvalidStateError" DOMException.
if (Event::has_flag(event, EventFlag::Dispatch) ||
!Event::has_flag(event, EventFlag::Initialized)) {
return DOMException::raise(cx, "EventTarget#dispatchEvent invalid Event state",
"InvalidStateError");
}
// 2. Initialize event's isTrusted attribute to false.
Event::set_flag(event, EventFlag::Trusted, false);
// 3. Return the result of dispatching event to this.
if (!dispatch(cx, self, event, nullptr, rval)) {
return false;
}
return true;
}
// https://dom.spec.whatwg.org/#concept-event-dispatch
//
// StarlingMonkey currently doesn't support Node objects (i.e. every check with `isNode()` returns
// false), which means we don't need to build a full event propagation path that walks parent nodes,
// deals with shadow DOM retargeting, or handles activation behaviors. In a simplified version we
// assume that the event only ever targets the object on which it was dispatched.
bool EventTarget::dispatch(JSContext *cx, HandleObject self, HandleObject event,
HandleObject target_override, MutableHandleValue rval) {
// 1. Set event's dispatch flag.
Event::set_flag(event, EventFlag::Dispatch, true);
// 2. Let targetOverride be target, if legacy target override flag is not given, and target's
// associated Document otherwise.
RootedObject target(cx, target_override ? target_override : self);
// 3. Let activationTarget be null.
// N/A
// 4. Let relatedTarget be the result of retargeting event's relatedTarget against target.
// N/A
// Retargeting will always result in related_target being the target if Node is not defined:
// https://dom.spec.whatwg.org/#retarget
// 5. Let clearTargets be false.
// N/A
// 6. If target is not relatedTarget or target is event's relatedTarget
// In simplified version this is always true, because the result of retargeting self
// against event's related target always returns self. This means that all the substeps
// within step 6 of this algorithm effectively implement the same functionality as the
// `invoke_listeners` function.
if (!invoke_listeners(cx, target, event)) {
return false;
}
// 7. Set event's eventPhase attribute to NONE.
Event::set_phase(event, Event::Phase::NONE);
// 8. Set event's currentTarget attribute to null.
Event::set_current_target(event, nullptr);
// 9. Set event's path to the empty list.
// - Implicitly done...
// 10. Unset event's dispatch flag, stop propagation flag, and stop immediate propagation flag.
Event::set_flag(event, EventFlag::Dispatch, false);
Event::set_flag(event, EventFlag::StopPropagation, false);
Event::set_flag(event, EventFlag::StopImmediatePropagation, false);
// 11. If clearTargets is true:
Event::set_related_target(event, nullptr);
// 12. If activationTarget is non-null:
// N/A
// 13. Return false if event's canceled flag is set; otherwise true.
rval.setBoolean(!Event::has_flag(event, EventFlag::Canceled));
return true;
}
// https://dom.spec.whatwg.org/#concept-event-listener-invoke
bool EventTarget::invoke_listeners(JSContext *cx, HandleObject target, HandleObject event) {
MOZ_ASSERT(is_instance(target));
// 1. Set event's target to the shadow-adjusted target of the last struct in event's path,
// that is either struct or preceding struct, whose shadow-adjusted target is non-null.
Event::set_phase(event, Event::Phase::AT_TARGET);
Event::set_target(event, target);
// 2. Set event's relatedTarget to struct's relatedTarget.
Event::set_related_target(event, target);
// 3. Set event's touch target list to struct's touch target list.
// We only use a single target here as it would appear in a Even#path[0];
// - shadow adjusted target == target
// - relatedTarget == target
// 4. If event's stop propagation flag is set, then return.
if (Event::has_flag(event, EventFlag::StopPropagation)) {
return true;
}
// 5. Initialize event's currentTarget attribute to struct's invocation target.
Event::set_current_target(event, target);
// 6. Let listeners be a clone of event's currentTarget attribute value's event listener list.
auto list = listeners(target);
JS::RootedVector<ListenerRef> list_clone(cx);
if (!list_clone.reserve(list->length())) {
return false;
}
for (auto &listener : *list) {
list_clone.infallibleAppend(listener);
}
// 7. Let invocationTargetInShadowTree be struct's invocation-target-in-shadow-tree.
// N/A
// 8. Let found be the result of running inner invoke with event, listeners, phase,
auto found = false;
if (!inner_invoke(cx, event, list_clone, &found)) {
return false;
}
// 9. If found is false and event's isTrusted attribute is true:
// N/A
return true;
}
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
bool EventTarget::inner_invoke(JSContext *cx, HandleObject event,
JS::HandleVector<ListenerRef> list, bool *found) {
RootedString type_str(cx, Event::type(event));
auto event_type = core::encode(cx, type_str);
if (!event_type) {
return false;
}
auto type_sv = std::string_view(event_type);
// 1. Let found be false.
*found = false;
bool listeners_removed = false;
// 2. For each listener of listeners, whose removed is false:
for (auto &listener : list) {
if (listener->removed) {
continue;
}
// 1. If event's type attribute value is not listener's type, then continue.
if (listener->type != type_sv) {
continue;
}
// 2. Set found to true.
*found = true;
// 3. If phase is "capturing" and listener's capture is false, then continue.
// 4. If phase is "bubbling" and listener's capture is true, then continue.
// N/A
// 5. If listener's once is true, then remove an event listener given event's
// currentTarget attribute value and listener.
if (listener->once) {
// Removing the listener from the list is deferred until the end of the loop.
listener->removed = true;
listeners_removed = true;
}
// 6. Let global be listener callback's associated realm's global object.
// 7. Let currentEvent be undefined.
// 8. If global is a Window object:
// 1. Set currentEvent to global's current event.
// 2. If invocationTargetInShadowTree is false, then set global's current event to event.
// N/A
// 9. If listener's passive is true, then set event's in passive listener flag.
if (listener->passive) {
Event::set_flag(event, EventFlag::InPassiveListener, true);
}
// 10. If global is a Window object, then record timing info for event listener given event and
// listener. N/A
//
// 11. Call a user object's operation with listener's callback, "handleEvent", event,
// and event's currentTarget attribute value.
auto engine = api::Engine::get(cx);
RootedValue callback_val(cx, listener->callback);
RootedObject callback_obj(cx, &callback_val.toObject());
RootedValue rval(cx);
RootedValueArray<1> args(cx);
args[0].setObject(*event);
if (JS::IsCallable(callback_obj)) {
auto global = engine->global();
JS::Call(cx, global, callback_val, args, &rval);
} else {
RootedValue handle_fn(cx);
if (!JS_GetProperty(cx, callback_obj, "handleEvent", &handle_fn)) {
return false;
}
JS::Call(cx, callback_val, handle_fn, args, &rval);
}
if (JS_IsExceptionPending(cx)) {
// TODO: report an exception as in spec:
// https://html.spec.whatwg.org/multipage/webappapis.html#report-an-exception
// https://github.com/bytecodealliance/StarlingMonkey/issues/239
auto msg = "Exception in event listener for " + listener->type;
engine->dump_pending_exception(msg.c_str());
JS_ClearPendingException(cx);
}
// 12. Unset event's in passive listener flag.
Event::set_flag(event, Event::EventFlag::InPassiveListener, false);
// 13. If global is a Window object, then set global's current event to currentEvent.
// N/A
// 14. If event's stop immediate propagation flag is set, then break.
if (Event::has_flag(event, EventFlag::StopImmediatePropagation)) {
return true;
}
}
if (listeners_removed) {
auto current_target = Event::current_target(event);
MOZ_ASSERT(is_instance(current_target));
auto target_list = listeners(current_target);
MOZ_ASSERT(target_list);
target_list->eraseIf([](const auto &listener) { return listener->removed; });
}
return true;
}
JSObject *EventTarget::create(JSContext *cx) {
JSObject *self = JS_NewObjectWithGivenProto(cx, &class_, proto_obj);
if (!self) {
return nullptr;
}
SetReservedSlot(self, Slots::Listeners, JS::PrivateValue(new ListenerList));
return self;
}
bool EventTarget::constructor(JSContext *cx, unsigned argc, JS::Value *vp) {
CTOR_HEADER("EventTarget", 0);
RootedObject self(cx, JS_NewObjectForConstructor(cx, &class_, args));
if (!self) {
return false;
}
SetReservedSlot(self, Slots::Listeners, JS::PrivateValue(new ListenerList));
args.rval().setObject(*self);
return true;
}
void EventTarget::finalize(JS::GCContext *gcx, JSObject *self) {
MOZ_ASSERT(is_instance(self));
auto list = listeners(self);
if (list) {
delete list;
}
}
void EventTarget::trace(JSTracer *trc, JSObject *self) {
MOZ_ASSERT(is_instance(self));
const JS::Value val = JS::GetReservedSlot(self, static_cast<size_t>(Slots::Listeners));
if (val.isNullOrUndefined()) {
// Nothing to trace
return;
}
auto list = listeners(self);
list->trace(trc);
}
bool EventTarget::init_class(JSContext *cx, JS::HandleObject global) {
return init_class_impl(cx, global);
}
} // namespace event
} // namespace web
} // namespace builtins