Serenity Operating System
1/*
2 * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/Assertions.h>
8#include <AK/TypeCasts.h>
9#include <LibJS/Runtime/AbstractOperations.h>
10#include <LibJS/Runtime/FunctionObject.h>
11#include <LibWeb/DOM/AbortSignal.h>
12#include <LibWeb/DOM/Document.h>
13#include <LibWeb/DOM/Event.h>
14#include <LibWeb/DOM/EventDispatcher.h>
15#include <LibWeb/DOM/EventTarget.h>
16#include <LibWeb/DOM/IDLEventListener.h>
17#include <LibWeb/DOM/Node.h>
18#include <LibWeb/DOM/ShadowRoot.h>
19#include <LibWeb/HTML/EventNames.h>
20#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
21#include <LibWeb/HTML/Window.h>
22#include <LibWeb/UIEvents/MouseEvent.h>
23#include <LibWeb/WebIDL/AbstractOperations.h>
24
25namespace Web::DOM {
26
27// FIXME: This shouldn't be here, as retargeting is not only used by the event dispatcher.
28// When moving this function, it needs to be generalized. https://dom.spec.whatwg.org/#retarget
29static EventTarget* retarget(EventTarget* left, EventTarget* right)
30{
31 // To retarget an object A against an object B, repeat these steps until they return an object:
32 for (;;) {
33 // 1. If one of the following is true then return A.
34 // - A is not a node
35 if (!is<Node>(left))
36 return left;
37
38 // - A’s root is not a shadow root
39 auto* left_node = verify_cast<Node>(left);
40 auto& left_root = left_node->root();
41 if (!is<ShadowRoot>(left_root))
42 return left;
43
44 // - B is a node and A’s root is a shadow-including inclusive ancestor of B
45 if (is<Node>(right) && left_root.is_shadow_including_inclusive_ancestor_of(verify_cast<Node>(*right)))
46 return left;
47
48 // 2. Set A to A’s root’s host.
49 auto& left_shadow_root = verify_cast<ShadowRoot>(left_root);
50 left = left_shadow_root.host();
51 }
52}
53
54// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
55bool EventDispatcher::inner_invoke(Event& event, Vector<JS::Handle<DOM::DOMEventListener>>& listeners, Event::Phase phase, bool invocation_target_in_shadow_tree)
56{
57 // 1. Let found be false.
58 bool found = false;
59
60 // 2. For each listener in listeners, whose removed is false:
61 for (auto& listener : listeners) {
62 if (listener->removed)
63 continue;
64
65 // 1. If event’s type attribute value is not listener’s type, then continue.
66 if (event.type() != listener->type)
67 continue;
68
69 // 2. Set found to true.
70 found = true;
71
72 // 3. If phase is "capturing" and listener’s capture is false, then continue.
73 if (phase == Event::Phase::CapturingPhase && !listener->capture)
74 continue;
75
76 // 4. If phase is "bubbling" and listener’s capture is true, then continue.
77 if (phase == Event::Phase::BubblingPhase && listener->capture)
78 continue;
79
80 // 5. If listener’s once is true, then remove listener from event’s currentTarget attribute value’s event listener list.
81 if (listener->once)
82 event.current_target()->remove_from_event_listener_list(*listener);
83
84 // 6. Let global be listener callback’s associated Realm’s global object.
85 auto& callback = listener->callback->callback();
86 auto& realm = callback.callback.shape().realm();
87 auto& global = realm.global_object();
88
89 // 7. Let currentEvent be undefined.
90 Event* current_event = nullptr;
91
92 // 8. If global is a Window object, then:
93 if (is<HTML::Window>(global)) {
94 auto& window = verify_cast<HTML::Window>(global);
95
96 // 1. Set currentEvent to global’s current event.
97 current_event = window.current_event();
98
99 // 2. If invocationTargetInShadowTree is false, then set global’s current event to event.
100 if (!invocation_target_in_shadow_tree)
101 window.set_current_event(&event);
102 }
103
104 // 9. If listener’s passive is true, then set event’s in passive listener flag.
105 if (listener->passive)
106 event.set_in_passive_listener(true);
107
108 // 10. Call a user object’s operation with listener’s callback, "handleEvent", « event », and event’s currentTarget attribute value. If this throws an exception, then:
109 // FIXME: These should be wrapped for us in call_user_object_operation, but it currently doesn't do that.
110 auto* this_value = event.current_target().ptr();
111 auto* wrapped_event = &event;
112 auto result = WebIDL::call_user_object_operation(callback, "handleEvent", this_value, wrapped_event);
113
114 // If this throws an exception, then:
115 if (result.is_error()) {
116 // 1. Report the exception.
117 HTML::report_exception(result, realm);
118
119 // FIXME: 2. Set legacyOutputDidListenersThrowFlag if given. (Only used by IndexedDB currently)
120 }
121
122 // 11. Unset event’s in passive listener flag.
123 event.set_in_passive_listener(false);
124
125 // 12. If global is a Window object, then set global’s current event to currentEvent.
126 if (is<HTML::Window>(global)) {
127 auto& window = verify_cast<HTML::Window>(global);
128 window.set_current_event(current_event);
129 }
130
131 // 13. If event’s stop immediate propagation flag is set, then return found.
132 if (event.should_stop_immediate_propagation())
133 return found;
134 }
135
136 // 3. Return found.
137 return found;
138}
139
140// https://dom.spec.whatwg.org/#concept-event-listener-invoke
141void EventDispatcher::invoke(Event::PathEntry& struct_, Event& event, Event::Phase phase)
142{
143 auto last_valid_shadow_adjusted_target = event.path().last_matching([&struct_](auto& entry) {
144 return entry.index <= struct_.index && entry.shadow_adjusted_target;
145 });
146
147 VERIFY(last_valid_shadow_adjusted_target.has_value());
148
149 // 1. Set event’s target to the shadow-adjusted target of the last struct in event’s path,
150 // that is either struct or preceding struct, whose shadow-adjusted target is non-null.
151 event.set_target(last_valid_shadow_adjusted_target.value().shadow_adjusted_target.ptr());
152
153 // 2. Set event’s relatedTarget to struct’s relatedTarget.
154 event.set_related_target(struct_.related_target.ptr());
155
156 // 3. Set event’s touch target list to struct’s touch target list.
157 event.set_touch_target_list(struct_.touch_target_list);
158
159 // 4. If event’s stop propagation flag is set, then return.
160 if (event.should_stop_propagation())
161 return;
162
163 // 5. Initialize event’s currentTarget attribute to struct’s invocation target.
164 event.set_current_target(struct_.invocation_target.ptr());
165
166 // 6. Let listeners be a clone of event’s currentTarget attribute value’s event listener list.
167 // NOTE: This avoids event listeners added after this point from being run. Note that removal still has an effect due to the removed field.
168 auto listeners = event.current_target()->event_listener_list();
169
170 // 7. Let invocationTargetInShadowTree be struct’s invocation-target-in-shadow-tree.
171 bool invocation_target_in_shadow_tree = struct_.invocation_target_in_shadow_tree;
172
173 // 8. Let found be the result of running inner invoke with event, listeners, phase, invocationTargetInShadowTree, and legacyOutputDidListenersThrowFlag if given.
174 bool found = inner_invoke(event, listeners, phase, invocation_target_in_shadow_tree);
175
176 // 9. If found is false and event’s isTrusted attribute is true, then:
177 if (!found && event.is_trusted()) {
178 // 1. Let originalEventType be event’s type attribute value.
179 auto original_event_type = event.type();
180
181 // 2. If event’s type attribute value is a match for any of the strings in the first column in the following table,
182 // set event’s type attribute value to the string in the second column on the same row as the matching string, and return otherwise.
183 if (event.type() == "animationend")
184 event.set_type("webkitAnimationEnd"sv);
185 else if (event.type() == "animationiteration")
186 event.set_type("webkitAnimationIteration"sv);
187 else if (event.type() == "animationstart")
188 event.set_type("webkitAnimationStart"sv);
189 else if (event.type() == "transitionend")
190 event.set_type("webkitTransitionEnd"sv);
191 else
192 return;
193
194 // 3. Inner invoke with event, listeners, phase, invocationTargetInShadowTree, and legacyOutputDidListenersThrowFlag if given.
195 inner_invoke(event, listeners, phase, invocation_target_in_shadow_tree);
196
197 // 4. Set event’s type attribute value to originalEventType.
198 event.set_type(original_event_type);
199 }
200}
201
202// https://dom.spec.whatwg.org/#concept-event-dispatch
203bool EventDispatcher::dispatch(JS::NonnullGCPtr<EventTarget> target, Event& event, bool legacy_target_override)
204{
205 // 1. Set event’s dispatch flag.
206 event.set_dispatched(true);
207
208 // 2. Let targetOverride be target, if legacy target override flag is not given, and target’s associated Document otherwise. [HTML]
209 // NOTE: legacy target override flag is only used by HTML and only when target is a Window object.
210 JS::GCPtr<EventTarget> target_override;
211 if (!legacy_target_override) {
212 target_override = target;
213 } else {
214 target_override = &verify_cast<HTML::Window>(*target).associated_document();
215 }
216
217 // 3. Let activationTarget be null.
218 JS::GCPtr<EventTarget> activation_target;
219
220 // 4. Let relatedTarget be the result of retargeting event’s relatedTarget against target.
221 JS::GCPtr<EventTarget> related_target = retarget(event.related_target(), target);
222
223 bool clear_targets = false;
224 // 5. If target is not relatedTarget or target is event’s relatedTarget, then:
225 if (related_target != target || event.related_target() == target) {
226 // 1. Let touchTargets be a new list.
227 Event::TouchTargetList touch_targets;
228
229 // 2. For each touchTarget of event’s touch target list, append the result of retargeting touchTarget against target to touchTargets.
230 for (auto& touch_target : event.touch_target_list()) {
231 touch_targets.append(retarget(touch_target, target));
232 }
233
234 // 3. Append to an event path with event, target, targetOverride, relatedTarget, touchTargets, and false.
235 event.append_to_path(*target, target_override, related_target, touch_targets, false);
236
237 // 4. Let isActivationEvent be true, if event is a MouseEvent object and event’s type attribute is "click"; otherwise false.
238 bool is_activation_event = is<UIEvents::MouseEvent>(event) && event.type() == HTML::EventNames::click;
239
240 // 5. If isActivationEvent is true and target has activation behavior, then set activationTarget to target.
241 if (is_activation_event && target->activation_behavior)
242 activation_target = target;
243
244 // FIXME: 6. Let slottable be target, if target is a slottable and is assigned, and null otherwise.
245
246 // 7. Let slot-in-closed-tree be false
247 bool slot_in_closed_tree = false;
248
249 // 8. Let parent be the result of invoking target’s get the parent with event.
250 auto* parent = target->get_parent(event);
251
252 // 9. While parent is non-null:
253 while (parent) {
254 // FIXME: 1. If slottable is non-null:
255 // 1. Assert: parent is a slot.
256 // 2. Set slottable to null.
257 // 3. If parent’s root is a shadow root whose mode is "closed", then set slot-in-closed-tree to true.
258 // FIXME: 2. If parent is a slottable and is assigned, then set slottable to parent.
259
260 // 3. Let relatedTarget be the result of retargeting event’s relatedTarget against parent.
261 related_target = retarget(event.related_target(), parent);
262
263 // 4. Let touchTargets be a new list.
264 touch_targets.clear();
265
266 // 5. For each touchTarget of event’s touch target list, append the result of retargeting touchTarget against parent to touchTargets.
267 for (auto& touch_target : event.touch_target_list()) {
268 touch_targets.append(retarget(touch_target, parent));
269 }
270
271 // 6. If parent is a Window object, or parent is a node and target’s root is a shadow-including inclusive ancestor of parent, then:
272 if (is<HTML::Window>(parent)
273 || (is<Node>(parent) && verify_cast<Node>(*target).root().is_shadow_including_inclusive_ancestor_of(verify_cast<Node>(*parent)))) {
274 // 1. If isActivationEvent is true, event’s bubbles attribute is true, activationTarget is null, and parent has activation behavior, then set activationTarget to parent.
275 if (is_activation_event && event.bubbles() && !activation_target && parent->activation_behavior)
276 activation_target = parent;
277
278 // 2. Append to an event path with event, parent, null, relatedTarget, touchTargets, and slot-in-closed-tree.
279 event.append_to_path(*parent, nullptr, related_target, touch_targets, slot_in_closed_tree);
280
281 }
282 // 7. Otherwise, if parent is relatedTarget, then set parent to null.
283 else if (related_target.ptr() == parent) {
284 parent = nullptr;
285 }
286 // 8. Otherwise, set target to parent and then:
287 else {
288 target = *parent;
289
290 // 1. If isActivationEvent is true, activationTarget is null, and target has activation behavior, then set activationTarget to target.
291 if (is_activation_event && !activation_target && target->activation_behavior)
292 activation_target = target;
293
294 // 2. Append to an event path with event, parent, target, relatedTarget, touchTargets, and slot-in-closed-tree.
295 event.append_to_path(*parent, target, related_target, touch_targets, slot_in_closed_tree);
296 }
297
298 // 9. If parent is non-null, then set parent to the result of invoking parent’s get the parent with event.
299 if (parent) {
300 parent = parent->get_parent(event);
301 }
302
303 // 10. Set slot-in-closed-tree to false.
304 slot_in_closed_tree = false;
305 }
306
307 // 10. Let clearTargetsStruct be the last struct in event’s path whose shadow-adjusted target is non-null.
308 auto clear_targets_struct = event.path().last_matching([](auto& entry) {
309 return entry.shadow_adjusted_target;
310 });
311
312 VERIFY(clear_targets_struct.has_value());
313
314 // 11. Let clearTargets be true if clearTargetsStruct’s shadow-adjusted target, clearTargetsStruct’s relatedTarget,
315 // or an EventTarget object in clearTargetsStruct’s touch target list is a node and its root is a shadow root; otherwise false.
316 if (is<Node>(clear_targets_struct.value().shadow_adjusted_target.ptr())) {
317 auto& shadow_adjusted_target_node = verify_cast<Node>(*clear_targets_struct.value().shadow_adjusted_target);
318 if (is<ShadowRoot>(shadow_adjusted_target_node.root()))
319 clear_targets = true;
320 }
321
322 if (!clear_targets && is<Node>(clear_targets_struct.value().related_target.ptr())) {
323 auto& related_target_node = verify_cast<Node>(*clear_targets_struct.value().related_target);
324 if (is<ShadowRoot>(related_target_node.root()))
325 clear_targets = true;
326 }
327
328 if (!clear_targets) {
329 for (auto touch_target : clear_targets_struct.value().touch_target_list) {
330 if (is<Node>(*touch_target.ptr())) {
331 auto& touch_target_node = verify_cast<Node>(*touch_target.ptr());
332 if (is<ShadowRoot>(touch_target_node.root())) {
333 clear_targets = true;
334 break;
335 }
336 }
337 }
338 }
339
340 // 12. If activationTarget is non-null and activationTarget has legacy-pre-activation behavior, then run activationTarget’s legacy-pre-activation behavior.
341 if (activation_target)
342 activation_target->legacy_pre_activation_behavior();
343
344 // 13. For each struct in event’s path, in reverse order:
345 for (auto& entry : event.path().in_reverse()) {
346 // 1. If struct’s shadow-adjusted target is non-null, then set event’s eventPhase attribute to AT_TARGET.
347 if (entry.shadow_adjusted_target)
348 event.set_phase(Event::Phase::AtTarget);
349 // 2. Otherwise, set event’s eventPhase attribute to CAPTURING_PHASE.
350 else
351 event.set_phase(Event::Phase::CapturingPhase);
352
353 // 3. Invoke with struct, event, "capturing", and legacyOutputDidListenersThrowFlag if given.
354 invoke(entry, event, Event::Phase::CapturingPhase);
355 }
356
357 // 14. For each struct in event’s path:
358 for (auto& entry : event.path()) {
359 // 1. If struct’s shadow-adjusted target is non-null, then set event’s eventPhase attribute to AT_TARGET.
360 if (entry.shadow_adjusted_target) {
361 event.set_phase(Event::Phase::AtTarget);
362 }
363 // 2. Otherwise:
364 else {
365 // 1. If event’s bubbles attribute is false, then continue.
366 if (!event.bubbles())
367 continue;
368
369 // 2. Set event’s eventPhase attribute to BUBBLING_PHASE.
370 event.set_phase(Event::Phase::BubblingPhase);
371 }
372
373 // 3. Invoke with struct, event, "bubbling", and legacyOutputDidListenersThrowFlag if given.
374 invoke(entry, event, Event::Phase::BubblingPhase);
375 }
376 }
377
378 // 6. Set event’s eventPhase attribute to NONE.
379 event.set_phase(Event::Phase::None);
380
381 // 7. Set event’s currentTarget attribute to null.
382 event.set_current_target(nullptr);
383
384 // 8. Set event’s path to the empty list.
385 event.clear_path();
386
387 // 9. Unset event’s dispatch flag, stop propagation flag, and stop immediate propagation flag.
388 event.set_dispatched(false);
389 event.set_stop_propagation(false);
390 event.set_stop_immediate_propagation(false);
391
392 // 10. If clearTargets, then:
393 if (clear_targets) {
394 // 1. Set event’s target to null.
395 event.set_target(nullptr);
396
397 // 2. Set event’s relatedTarget to null.
398 event.set_related_target(nullptr);
399
400 // 3. Set event’s touch target list to the empty list.
401 event.clear_touch_target_list();
402 }
403
404 // 11. If activationTarget is non-null, then:
405 if (activation_target) {
406 // 1. If event’s canceled flag is unset, then run activationTarget’s activation behavior with event.
407 if (!event.cancelled()) {
408 activation_target->activation_behavior(event);
409 activation_target->legacy_cancelled_activation_behavior_was_not_called();
410 }
411 // 2. Otherwise, if activationTarget has legacy-canceled-activation behavior, then run activationTarget’s legacy-canceled-activation behavior.
412 else {
413 activation_target->legacy_cancelled_activation_behavior();
414 }
415 }
416
417 // 12. Return false if event’s canceled flag is set; otherwise true.
418 return !event.cancelled();
419}
420
421}