-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathElement.cpp
More file actions
6987 lines (5837 loc) · 256 KB
/
Element.cpp
File metadata and controls
6987 lines (5837 loc) · 256 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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Peter Kelly (pmk@post.com)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* (C) 2007 David Smith (catfish.man@gmail.com)
* Copyright (C) 2004-2025 Apple Inc. All rights reserved.
* (C) 2007 Eric Seidel (eric@webkit.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "Element.h"
#include "AXObjectCache.h"
#include "AriaNotifyOptions.h"
#include "Attr.h"
#include "AttributeChangeInvalidation.h"
#include "CheckVisibilityOptions.h"
#include "ChildChangeInvalidation.h"
#include "ChildListMutationScope.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "ClassChangeInvalidation.h"
#include "ComposedTreeAncestorIterator.h"
#include "ComposedTreeIterator.h"
#include "ComputedStylePropertyMapReadOnly.h"
#include "ContainerNodeAlgorithms.h"
#include "ContainerNodeInlines.h"
#include "ContentVisibilityDocumentState.h"
#include "CustomElementReactionQueue.h"
#include "CustomElementRegistry.h"
#include "CustomStateSet.h"
#include "DOMRect.h"
#include "DOMRectList.h"
#include "DOMTokenList.h"
#include "DocumentFullscreen.h"
#include "DocumentInlines.h"
#include "DocumentQuirks.h"
#include "DocumentSharedObjectPool.h"
#include "DocumentView.h"
#include "EditingInlines.h"
#include "ElementAncestorIteratorInlines.h"
#include "ElementAnimationRareData.h"
#include "ElementChildIteratorInlines.h"
#include "ElementRareData.h"
#include "ElementTextDirection.h"
#include "EventDispatcher.h"
#include "EventHandler.h"
#include "EventNames.h"
#include "FocusController.h"
#include "FocusEvent.h"
#include "FormAssociatedCustomElement.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "FullscreenOptions.h"
#include "GetAnimationsOptions.h"
#include "GetHTMLOptions.h"
#include "HTMLBDIElement.h"
#include "HTMLBodyElement.h"
#include "HTMLCanvasElement.h"
#include "HTMLDialogElement.h"
#include "HTMLDocument.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLHtmlElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLLabelElement.h"
#include "HTMLNameCollection.h"
#include "HTMLObjectElement.h"
#include "HTMLOptGroupElement.h"
#include "HTMLOptionElement.h"
#include "HTMLParserIdioms.h"
#include "HTMLScriptElement.h"
#include "HTMLSelectElement.h"
#include "HTMLTemplateElement.h"
#include "HTMLTextAreaElement.h"
#include "IdChangeInvalidation.h"
#include "IdTargetObserverRegistry.h"
#include "InputType.h"
#include "InspectorInstrumentation.h"
#include "JSCustomElementRegistry.h"
#include "JSDOMPromiseDeferred.h"
#include "JSLazyEventListener.h"
#include "KeyboardEvent.h"
#include "KeyframeAnimationOptions.h"
#include "KeyframeEffect.h"
#include "LargestContentfulPaintData.h"
#include "LocalDOMWindow.h"
#include "LocalFrame.h"
#include "LocalFrameView.h"
#include "Logging.h"
#include "MutationObserverInterestGroup.h"
#include "MutationRecord.h"
#include "NameValidation.h"
#include "NodeInlines.h"
#include "NodeName.h"
#include "NodeRenderStyle.h"
#include "PlatformMouseEvent.h"
#include "PlatformWheelEvent.h"
#include "PointerCaptureController.h"
#include "PointerEvent.h"
#include "PointerLockController.h"
#include "PointerLockOptions.h"
#include "PopoverData.h"
#include "PseudoClassChangeInvalidation.h"
#include "RenderBoxInlines.h"
#include "RenderElementInlines.h"
#include "RenderElementStyleInlines.h"
#include "RenderFragmentedFlow.h"
#include "RenderLayer.h"
#include "RenderLayerBacking.h"
#include "RenderLayerCompositor.h"
#include "RenderLayerScrollableArea.h"
#include "RenderListBox.h"
#include "RenderObjectInlines.h"
#include "RenderSVGModelObject.h"
#include "RenderStyle+SettersInlines.h"
#include "RenderTextControlSingleLine.h"
#include "RenderTheme.h"
#include "RenderTreeUpdater.h"
#include "RenderView.h"
#include "RenderWidgetInlines.h"
#include "ResolvedStyle.h"
#include "SVGDocumentExtensions.h"
#include "SVGElementTypeHelpers.h"
#include "SVGNames.h"
#include "SVGSVGElement.h"
#include "SVGScriptElement.h"
#include "ScriptDisallowedScope.h"
#include "ScrollIntoViewOptions.h"
#include "ScrollLatchingController.h"
#include "ScrollToOptions.h"
#include "SecurityPolicyViolationEvent.h"
#include "SelectorQuery.h"
#include "SerializedNode.h"
#include "Settings.h"
#include "ShadowRootInit.h"
#include "SimulatedClick.h"
#include "SlotAssignment.h"
#include "StyleableInlines.h"
#include "StyleInvalidator.h"
#include "StylePrimitiveNumericTypes+Evaluation.h"
#include "StyleProperties.h"
#include "StyleResolver.h"
#include "StyleScope.h"
#include "StyleTreeResolver.h"
#include "StyleZoomPrimitivesInlines.h"
#include "TextIterator.h"
#include "TouchAction.h"
#include "TrustedType.h"
#include "TypedElementDescendantIteratorInlines.h"
#include "VisibilityAdjustment.h"
#include "VoidCallback.h"
#include "WebAnimation.h"
#include "WebAnimationTypes.h"
#include "WheelEvent.h"
#include "XLinkNames.h"
#include "XMLNSNames.h"
#include "XMLNames.h"
#include "markup.h"
#include <JavaScriptCore/JSCJSValue.h>
#include <JavaScriptCore/JSONObject.h>
#include <ranges>
#include <wtf/NeverDestroyed.h>
#include <wtf/Scope.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/CString.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/TextStream.h>
#if PLATFORM(COCOA)
#include <wtf/cocoa/RuntimeApplicationChecksCocoa.h>
#endif
#if PLATFORM(IOS_FAMILY)
#import <pal/system/ios/UserInterfaceIdiom.h>
#endif
namespace WebCore {
WTF_MAKE_TZONE_ALLOCATED_IMPL(Element);
struct SameSizeAsElement : public ContainerNode {
QualifiedName tagName;
void* elementData;
void* shadowRoot;
};
static_assert(sizeof(Element) == sizeof(SameSizeAsElement), "Element should stay small");
using namespace HTMLNames;
using namespace XMLNames;
static HashMap<WeakRef<Element, WeakPtrImplWithEventTargetData>, Vector<Ref<Attr>>>& NODELETE attrNodeListMap()
{
static NeverDestroyed<HashMap<WeakRef<Element, WeakPtrImplWithEventTargetData>, Vector<Ref<Attr>>>> map;
return map;
}
static Vector<Ref<Attr>>* NODELETE attrNodeListForElement(Element& element)
{
if (!element.hasSyntheticAttrChildNodes())
return nullptr;
ASSERT(attrNodeListMap().contains(element));
return &attrNodeListMap().find(element)->value;
}
static Vector<Ref<Attr>>& ensureAttrNodeListForElement(Element& element)
{
if (element.hasSyntheticAttrChildNodes()) {
ASSERT(attrNodeListMap().contains(element));
return attrNodeListMap().find(element)->value;
}
ASSERT(!attrNodeListMap().contains(element));
element.setHasSyntheticAttrChildNodes(true);
return attrNodeListMap().add(element, Vector<Ref<Attr>>()).iterator->value;
}
static void removeAttrNodeListForElement(Element& element)
{
ASSERT(element.hasSyntheticAttrChildNodes());
ASSERT(attrNodeListMap().contains(element));
attrNodeListMap().remove(element);
element.setHasSyntheticAttrChildNodes(false);
}
static Attr* NODELETE findAttrNodeInList(Vector<Ref<Attr>>& attrNodeList, const QualifiedName& name)
{
for (auto& node : attrNodeList) {
if (node->qualifiedName().matches(name))
return node.ptr();
}
return nullptr;
}
// Insertion steps from https://html.spec.whatwg.org/multipage/interaction.html#the-autofocus-attribute
static bool shouldAutofocus(const Element& element)
{
Ref document = element.document();
RefPtr page = document->page();
if (!page || page->autofocusProcessed())
return false;
if (!element.hasAttributeWithoutSynchronization(HTMLNames::autofocusAttr))
return false;
if (!element.isInDocumentTree() || !document->hasBrowsingContext())
return false;
if (document->isSandboxed(SandboxFlag::AutomaticFeatures)) {
// FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
document->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Blocked autofocusing on a form control because the form's frame is sandboxed and the 'allow-scripts' permission is not set."_s);
return false;
}
// Make sure all navigable ancestors are of the same origin.
bool allAncestorsAreSameOrigin = [&] {
RefPtr<Frame> currentFrame = document->frame();
RefPtr<Document> currentDocument = document.ptr();
while (currentFrame) {
if (!currentDocument || !document->topOrigin().isSameOriginDomain(currentDocument->securityOrigin()))
return false;
RefPtr parentFrame = currentFrame->tree().parent();
if (!parentFrame)
return currentFrame->isMainFrame();
// If the parent frame is not local then it is definitely a different origin.
RefPtr localParent = dynamicDowncast<LocalFrame>(parentFrame.get());
if (!localParent)
return false;
currentFrame = WTF::move(parentFrame);
currentDocument = localParent->document();
}
return true;
}();
if (!allAncestorsAreSameOrigin)
document->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Blocked autofocusing on a form control in a cross-origin subframe."_s);
return allAncestorsAreSameOrigin;
}
Ref<Element> Element::create(const QualifiedName& tagName, Document& document)
{
return adoptRef(*new Element(tagName, document, { }));
}
Element::Element(const QualifiedName& tagName, Document& document, OptionSet<TypeFlag> typeFlags)
: ContainerNode(document, NodeType::Element, typeFlags | TypeFlag::IsElement)
, m_tagName(tagName)
{
}
Element::~Element()
{
ASSERT(!beforePseudoElement());
ASSERT(!afterPseudoElement());
ASSERT(!is<HTMLImageElement>(*this) || !intersectionObserverDataIfExists());
disconnectFromIntersectionObservers();
disconnectFromResizeObservers();
removeShadowRoot();
if (hasSyntheticAttrChildNodes())
detachAllAttrNodesFromElement();
}
inline ElementRareData& Element::ensureElementRareData()
{
return static_cast<ElementRareData&>(ensureRareData());
}
void Element::setTabIndexExplicitly(std::optional<int> tabIndex)
{
if (!tabIndex) {
setTabIndexState(TabIndexState::NotSet);
return;
}
setTabIndexState([this, value = tabIndex.value()]() {
switch (value) {
case 0:
return TabIndexState::Zero;
case -1:
return TabIndexState::NegativeOne;
default:
ensureElementRareData().setUnusualTabIndex(value);
return TabIndexState::InRareData;
}
}());
}
std::optional<int> Element::tabIndexSetExplicitly() const
{
switch (tabIndexState()) {
case TabIndexState::NotSet:
return std::nullopt;
case TabIndexState::Zero:
return 0;
case TabIndexState::NegativeOne:
return -1;
case TabIndexState::InRareData:
ASSERT(hasRareData());
return elementRareData()->unusualTabIndex();
}
ASSERT_NOT_REACHED();
return std::nullopt;
}
int Element::defaultTabIndex() const
{
return -1;
}
bool Element::isNonceable() const
{
// https://www.w3.org/TR/CSP3/#is-element-nonceable
if (elementRareData()->nonce().isNull())
return false;
if (hasDuplicateAttribute())
return false;
if (hasAttributes() && isAnyOf<HTMLScriptElement, SVGScriptElement>(*this)) {
static constexpr auto scriptString = "<script"_s;
static constexpr auto styleString = "<style"_s;
for (auto& attribute : attributes()) {
auto name = attribute.localNameLowercase();
auto value = attribute.value();
if (name.contains(scriptString)
|| name.contains(styleString)
|| value.containsIgnoringASCIICase(scriptString)
|| value.containsIgnoringASCIICase(styleString))
return false;
}
}
return true;
}
const AtomString& Element::nonce() const
{
if (hasRareData() && isNonceable())
return elementRareData()->nonce();
return emptyAtom();
}
void Element::setNonce(const AtomString& newValue)
{
if (newValue == emptyAtom() && !hasRareData())
return;
ensureElementRareData().setNonce(newValue);
}
void Element::hideNonceSlow()
{
// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#nonce-attributes
ASSERT(isConnected());
ASSERT(hasAttributeWithoutSynchronization(nonceAttr));
if (!document().contentSecurityPolicy()->isHeaderDelivered())
return;
// Retain previous IDL nonce.
AtomString currentNonce = nonce();
setAttribute(nonceAttr, emptyAtom());
setNonce(currentNonce);
}
bool Element::supportsFocus() const
{
return !!tabIndexSetExplicitly();
}
int Element::tabIndexForBindings() const
{
return valueOrCompute(tabIndexSetExplicitly(), [&] { return defaultTabIndex(); });
}
void Element::setTabIndexForBindings(int value)
{
setIntegralAttribute(tabindexAttr, value);
}
bool Element::isKeyboardFocusable(const FocusEventData&) const
{
if (!isFocusable() || shouldBeIgnoredInSequentialFocusNavigation() || tabIndexSetExplicitly().value_or(0) < 0)
return false;
if (auto* root = shadowRoot()) {
if (root->delegatesFocus())
return false;
}
// Popovers with invokers delegate focus.
if (RefPtr popover = dynamicDowncast<HTMLElement>(*this)) {
if (popover->isPopoverShowing() && popover->popoverData()->invoker())
return false;
}
return true;
}
bool Element::isMouseFocusable() const
{
return isFocusable();
}
bool Element::shouldUseInputMethod()
{
return computeEditability(UserSelectAllTreatment::NotEditable, ShouldUpdateStyle::Update) != Editability::ReadOnly;
}
static bool NODELETE isForceEvent(const PlatformMouseEvent& platformEvent)
{
return platformEvent.type() == PlatformEvent::Type::MouseForceChanged || platformEvent.type() == PlatformEvent::Type::MouseForceDown || platformEvent.type() == PlatformEvent::Type::MouseForceUp;
}
static bool isCompatibilityMouseEvent(const MouseEvent& mouseEvent)
{
// https://www.w3.org/TR/pointerevents/#compatibility-mapping-with-mouse-events
const auto& type = mouseEvent.type();
auto& eventNames = WebCore::eventNames();
return !isAnyClick(mouseEvent) && type != eventNames.mouseoverEvent && type != eventNames.mouseoutEvent && type != eventNames.mouseenterEvent && type != eventNames.mouseleaveEvent;
}
enum class ShouldIgnoreMouseEvent : bool { No, Yes };
static ShouldIgnoreMouseEvent dispatchPointerEventIfNeeded(Element& element, const MouseEvent& mouseEvent, const PlatformMouseEvent& platformEvent, bool& didNotSwallowEvent)
{
if (RefPtr page = element.document().page()) {
auto& pointerCaptureController = page->pointerCaptureController();
#if ENABLE(TOUCH_EVENTS)
if (platformEvent.pointerId() != mousePointerID && !isAnyClick(mouseEvent) && pointerCaptureController.preventsCompatibilityMouseEventsForIdentifier(platformEvent.pointerId()))
return ShouldIgnoreMouseEvent::Yes;
#else
UNUSED_PARAM(platformEvent);
#endif
if (platformEvent.syntheticClickType() != SyntheticClickType::NoTap && !isAnyClick(mouseEvent) && mouseEvent.type() != eventNames().contextmenuEvent)
return ShouldIgnoreMouseEvent::No;
if (RefPtr pointerEvent = pointerCaptureController.pointerEventForMouseEvent(mouseEvent, platformEvent.pointerId(), platformEvent.pointerType())) {
pointerCaptureController.dispatchEvent(*pointerEvent, &element);
if (isCompatibilityMouseEvent(mouseEvent) && pointerCaptureController.preventsCompatibilityMouseEventsForIdentifier(pointerEvent->pointerId()))
return ShouldIgnoreMouseEvent::Yes;
if (pointerEvent->defaultPrevented() || pointerEvent->defaultHandled()) {
didNotSwallowEvent = false;
if (pointerEvent->type() == eventNames().pointerdownEvent)
return ShouldIgnoreMouseEvent::Yes;
}
}
}
return ShouldIgnoreMouseEvent::No;
}
Element::DispatchMouseEventResult Element::dispatchMouseEvent(const PlatformMouseEvent& platformEvent, const AtomString& eventType, int detail, Element* relatedTarget, IsSyntheticClick isSyntheticClick)
{
auto eventIsDefaultPrevented = Element::EventIsDefaultPrevented::No;
if (isForceEvent(platformEvent) && !document().hasListenerTypeForEventType(platformEvent.type()))
return { Element::EventIsDispatched::No, eventIsDefaultPrevented };
Vector<Ref<MouseEvent>> childMouseEvents;
for (const auto& childPlatformEvent : platformEvent.coalescedEvents()) {
Ref childMouseEvent = MouseEvent::create(eventType, document().windowProxy(), childPlatformEvent, { }, { }, detail, relatedTarget);
childMouseEvents.append(WTF::move(childMouseEvent));
}
Vector<Ref<MouseEvent>> predictedEvents;
for (const auto& childPlatformEvent : platformEvent.predictedEvents()) {
Ref childMouseEvent = MouseEvent::create(eventType, document().windowProxy(), childPlatformEvent, { }, { }, detail, relatedTarget);
predictedEvents.append(WTF::move(childMouseEvent));
}
Ref mouseEvent = MouseEvent::create(eventType, document().windowProxy(), platformEvent, childMouseEvents, predictedEvents, detail, relatedTarget);
if (mouseEvent->type().isEmpty())
return { Element::EventIsDispatched::Yes, eventIsDefaultPrevented }; // Shouldn't happen.
Ref protectedThis { *this };
bool didNotSwallowEvent = true;
if (dispatchPointerEventIfNeeded(*this, mouseEvent, platformEvent, didNotSwallowEvent) == ShouldIgnoreMouseEvent::Yes)
return { Element::EventIsDispatched::No, eventIsDefaultPrevented };
auto isParentProcessAFullWebBrowser = false;
#if PLATFORM(IOS_FAMILY)
if (RefPtr frame = document().frame())
isParentProcessAFullWebBrowser = frame->loader().client().isParentProcessAFullWebBrowser();
#elif PLATFORM(MAC)
isParentProcessAFullWebBrowser = WTF::MacApplication::isSafari();
#endif
if (Quirks::StorageAccessResult::ShouldCancelEvent == protect(document())->quirks().triggerOptionalStorageAccessQuirk(*this, platformEvent, eventType, detail, relatedTarget, isParentProcessAFullWebBrowser, isSyntheticClick))
return { Element::EventIsDispatched::No, eventIsDefaultPrevented };
bool shouldNotDispatchMouseEvent = isAnyClick(mouseEvent) || mouseEvent->type() == eventNames().contextmenuEvent;
if (!shouldNotDispatchMouseEvent) {
ASSERT(!mouseEvent->target() || mouseEvent->target() != relatedTarget);
dispatchEvent(mouseEvent);
if (mouseEvent->defaultPrevented())
eventIsDefaultPrevented = Element::EventIsDefaultPrevented::Yes;
if (mouseEvent->defaultPrevented() || mouseEvent->defaultHandled())
didNotSwallowEvent = false;
}
// The document should not receive dblclick for non-primary buttons.
if (mouseEvent->type() == eventNames().clickEvent && mouseEvent->detail() == 2) {
// Special case: If it's a double click event, we also send the dblclick event. This is not part
// of the DOM specs, but is used for compatibility with the ondblclick="" attribute. This is treated
// as a separate event in other DOM-compliant browsers like Firefox, and so we do the same.
// FIXME: Is it okay that mouseEvent may have been mutated by scripts via initMouseEvent in dispatchEvent above?
Ref doubleClickEvent = MouseEvent::create(eventNames().dblclickEvent,
mouseEvent->bubbles() ? Event::CanBubble::Yes : Event::CanBubble::No,
mouseEvent->cancelable() ? Event::IsCancelable::Yes : Event::IsCancelable::No,
Event::IsComposed::Yes,
MonotonicTime::now(),
mouseEvent->view(), mouseEvent->detail(),
mouseEvent->screenX(), mouseEvent->screenY(), mouseEvent->clientX(), mouseEvent->clientY(),
mouseEvent->modifierKeys(), mouseEvent->button(), mouseEvent->buttons(), mouseEvent->syntheticClickType(), relatedTarget);
if (mouseEvent->defaultHandled())
doubleClickEvent->setDefaultHandled();
dispatchEvent(doubleClickEvent);
if (doubleClickEvent->defaultHandled() || doubleClickEvent->defaultPrevented())
return { Element::EventIsDispatched::No, eventIsDefaultPrevented };
}
return { didNotSwallowEvent ? Element::EventIsDispatched::Yes : Element::EventIsDispatched::No, eventIsDefaultPrevented };
}
bool Element::dispatchWheelEvent(const PlatformWheelEvent& platformEvent, OptionSet<EventHandling>& processing, Event::IsCancelable isCancelable)
{
Ref event = WheelEvent::create(platformEvent, document().windowProxy(), isCancelable);
// Events with no deltas are important because they convey platform information about scroll gestures
// and momentum beginning or ending. However, those events should not be sent to the DOM since some
// websites will break. They need to be dispatched because dispatching them will call into the default
// event handler, and our platform code will correctly handle the phase changes. Calling stopPropagation()
// will prevent the event from being sent to the DOM, but will still call the default event handler.
// FIXME: Move this logic into WheelEvent::create.
if (platformEvent.delta().isZero())
event->stopPropagation();
else
processing.add(EventHandling::DispatchedToDOM);
dispatchEvent(event);
LOG_WITH_STREAM(Scrolling, stream << "Element " << *this << " dispatchWheelEvent: (cancelable " << event->cancelable() << ") defaultPrevented " << event->defaultPrevented() << " defaultHandled " << event->defaultHandled());
if (event->defaultPrevented())
processing.add(EventHandling::DefaultPrevented);
if (event->defaultHandled())
processing.add(EventHandling::DefaultHandled);
return !event->defaultPrevented() && !event->defaultHandled();
}
bool Element::dispatchKeyEvent(const PlatformKeyboardEvent& platformEvent)
{
Ref event = KeyboardEvent::create(platformEvent, document().windowProxy());
if (RefPtr frame = document().frame()) {
if (frame->eventHandler().accessibilityPreventsEventPropagation(event))
event->stopPropagation();
}
dispatchEvent(event);
return !event->defaultPrevented() && !event->defaultHandled();
}
bool Element::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions, SimulatedClickVisualOptions visualOptions)
{
return simulateClick(*this, underlyingEvent, eventOptions, visualOptions, SimulatedClickSource::UserAgent);
}
Ref<Node> Element::cloneNodeInternal(Document& document, CloningOperation type, CustomElementRegistry* fallbackRegistry) const
{
switch (type) {
case CloningOperation::SelfOnly:
case CloningOperation::SelfWithTemplateContent: {
Ref clone = cloneElementWithoutChildren(document, fallbackRegistry);
ScriptDisallowedScope::EventAllowedScope eventAllowedScope { clone };
cloneShadowTreeIfPossible(clone);
return clone;
}
case CloningOperation::Everything:
break;
}
return cloneElementWithChildren(document, fallbackRegistry);
}
template<typename ShadowRoot>
std::optional<ShadowRoot> Element::serializeShadowRoot() const
{
RefPtr oldShadowRoot = this->shadowRoot();
if (!oldShadowRoot || !oldShadowRoot->isClonable())
return std::nullopt;
return std::get<ShadowRoot>(oldShadowRoot->serializeNode(Node::CloningOperation::SelfWithTemplateContent).data);
}
template std::optional<SerializedNode::ShadowRoot> Element::serializeShadowRoot() const;
template<typename Attribute>
Vector<Attribute> Element::serializeAttributes() const
{
return this->elementData() ? WTF::map(this->attributes(), [] (const auto& attribute) {
return Attribute { { attribute.name() }, attribute.value() };
}) : Vector<Attribute>();
}
template Vector<SerializedNode::Element::Attribute> Element::serializeAttributes() const;
SerializedNode Element::serializeNode(CloningOperation type) const
{
Vector<SerializedNode> children;
switch (type) {
case CloningOperation::SelfOnly:
case CloningOperation::SelfWithTemplateContent:
break;
case CloningOperation::Everything:
children = serializeChildNodes();
break;
}
return { SerializedNode::Element {
{ WTF::move(children) },
{ tagQName() },
serializeAttributes<SerializedNode::Element::Attribute>(),
serializeShadowRoot<SerializedNode::ShadowRoot>()
} };
}
void Element::cloneShadowTreeIfPossible(Element& newHost) const
{
RefPtr oldShadowRoot = this->shadowRoot();
if (!oldShadowRoot || !oldShadowRoot->isClonable())
return;
Ref clonedShadowRoot = [&] {
Ref clone = oldShadowRoot->cloneNodeInternal(newHost.document(), Node::CloningOperation::SelfWithTemplateContent, nullptr);
return downcast<ShadowRoot>(WTF::move(clone));
}();
if (oldShadowRoot->usesNullCustomElementRegistry())
clonedShadowRoot->setUsesNullCustomElementRegistry(); // Set this flag for Element::insertionSteps.
else {
clonedShadowRoot->clearUsesNullCustomElementRegistry(); // Unset flag potentially set by DocumentFragment constructor
if (RefPtr registry = oldShadowRoot->customElementRegistry()) {
if (!registry->isScoped())
registry = newHost.document().effectiveGlobalCustomElementRegistry();
clonedShadowRoot->setCustomElementRegistry(WTF::move(registry));
}
}
newHost.addShadowRoot(clonedShadowRoot.copyRef());
oldShadowRoot->cloneChildNodes(newHost.document(), nullptr, clonedShadowRoot);
}
Ref<Element> Element::cloneElementWithChildren(Document& document, CustomElementRegistry* fallbackRegistry) const
{
Ref clone = cloneElementWithoutChildren(document, fallbackRegistry);
ScriptDisallowedScope::EventAllowedScope eventAllowedScope { clone };
cloneShadowTreeIfPossible(clone);
cloneChildNodes(document, fallbackRegistry, clone);
return clone;
}
Ref<Element> Element::cloneElementWithoutChildren(Document& document, CustomElementRegistry* fallbackRegistry) const
{
RefPtr registry = CustomElementRegistry::registryForElement(*this);
if (!registry)
registry = fallbackRegistry;
if (registry && !registry->isScoped())
registry = document.effectiveGlobalCustomElementRegistry();
Ref clone = cloneElementWithoutAttributesAndChildren(document, registry.get());
// This will catch HTML elements in the wrong namespace that are not correctly copied.
// This is a sanity check as HTML overloads some of the DOM methods.
ASSERT(isHTMLElement() == clone->isHTMLElement());
clone->cloneDataFromElement(*this);
if (usesNullCustomElementRegistry() && !registry)
clone->setUsesNullCustomElementRegistry();
return clone;
}
Ref<Element> Element::cloneElementWithoutAttributesAndChildren(Document& document, CustomElementRegistry* registry) const
{
return document.createElement(tagQName(), false, registry);
}
Ref<Attr> Element::detachAttribute(unsigned index)
{
ASSERT(elementData());
const Attribute& attribute = elementData()->attributeAt(index);
RefPtr attrNode = attrIfExists(attribute.name());
if (attrNode)
detachAttrNodeFromElementWithValue(attrNode.get(), attribute.value());
else
attrNode = Attr::create(protect(document()), attribute.name(), attribute.value());
removeAttributeInternal(index, InSynchronizationOfLazyAttribute::No);
return attrNode.releaseNonNull();
}
bool Element::removeAttribute(const QualifiedName& name)
{
if (!elementData())
return false;
unsigned index = elementData()->findAttributeIndexByName(name);
if (index == ElementData::attributeNotFound)
return false;
removeAttributeInternal(index, InSynchronizationOfLazyAttribute::No);
return true;
}
void Element::setBooleanAttribute(const QualifiedName& name, bool value)
{
if (value)
setAttributeWithoutSynchronization(name, emptyAtom());
else
removeAttribute(name);
}
NamedNodeMap& Element::attributesMap() const
{
ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
if (NamedNodeMap* attributeMap = rareData.attributeMap())
return *attributeMap;
rareData.setAttributeMap(makeUniqueWithoutRefCountedCheck<NamedNodeMap>(const_cast<Element&>(*this)));
return *rareData.attributeMap();
}
bool Element::hasAttribute(const QualifiedName& name) const
{
if (!elementData())
return false;
synchronizeAttribute(name);
return elementData()->findAttributeByName(name);
}
void Element::synchronizeAllAttributes() const
{
if (!elementData())
return;
if (elementData()->styleAttributeIsDirty()) {
ASSERT(isStyledElement());
static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
}
if (auto* svgElement = dynamicDowncast<SVGElement>(*this))
const_cast<SVGElement&>(*svgElement).synchronizeAllAttributes();
}
ALWAYS_INLINE void Element::synchronizeAttribute(const QualifiedName& name) const
{
if (!elementData())
return;
if (name == styleAttr && elementData()->styleAttributeIsDirty()) [[unlikely]] {
ASSERT_WITH_SECURITY_IMPLICATION(isStyledElement());
static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
return;
}
if (auto* svgElement = dynamicDowncast<SVGElement>(*this))
const_cast<SVGElement&>(*svgElement).synchronizeAttribute(name);
}
static ALWAYS_INLINE bool isStyleAttribute(const Element& element, const AtomString& attributeLocalName)
{
if (shouldIgnoreAttributeCase(element))
return equalLettersIgnoringASCIICase(attributeLocalName, "style"_s);
return attributeLocalName == styleAttr->localName();
}
ALWAYS_INLINE void Element::synchronizeAttribute(const AtomString& localName) const
{
// This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
// e.g when called from DOM API.
if (!elementData())
return;
if (elementData()->styleAttributeIsDirty() && isStyleAttribute(*this, localName)) {
ASSERT_WITH_SECURITY_IMPLICATION(isStyledElement());
static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
return;
}
if (auto* svgElement = dynamicDowncast<SVGElement>(*this))
const_cast<SVGElement&>(*svgElement).synchronizeAttribute(QualifiedName(nullAtom(), localName, nullAtom()));
}
const AtomString& Element::getAttribute(const QualifiedName& name) const
{
if (auto* attribute = getAttributeInternal(name))
return attribute->value();
return nullAtom();
}
AtomString Element::getAttributeForBindings(const QualifiedName& name, ResolveURLs resolveURLs) const
{
auto* attribute = getAttributeInternal(name);
if (!attribute)
return nullAtom();
if (!attributeContainsURL(*attribute))
return attribute->value();
switch (resolveURLs) {
case ResolveURLs::Yes:
case ResolveURLs::YesExcludingURLsForPrivacy:
case ResolveURLs::NoExcludingURLsForPrivacy:
return AtomString(completeURLsInAttributeValue(URL(), *attribute, resolveURLs));
case ResolveURLs::No:
break;
}
return attribute->value();
}
Vector<String> Element::getAttributeNames() const
{
if (!hasAttributes())
return { };
auto attributes = this->attributes();
return WTF::map(attributes, [](auto& attribute) {
return attribute.name().toString();
});
}
bool Element::hasFocusableStyle() const
{
auto isFocusableStyle = [](const RenderStyle* style) {
return style && style->display().doesGenerateBox()
&& style->visibility() == Visibility::Visible && !style->effectiveInert()
&& (style->usedContentVisibility() != ContentVisibility::Hidden || style->contentVisibility() != ContentVisibility::Visible);
};
if (renderStyle())
return isFocusableStyle(renderStyle());
// Compute style in yet unstyled subtree without resolving full style.
CheckedPtr style = const_cast<Element&>(*this).resolveComputedStyle(ResolveComputedStyleMode::RenderedOnly);
return isFocusableStyle(style.get());
}
bool Element::isFocusable() const
{
if (!isConnected() || !supportsFocus())
return false;
if (!renderer()) {
// Elements in canvas fallback content are not rendered, but they are allowed to be
// focusable as long as their canvas is displayed and visible.
RefPtr canvas = ancestorsOfType<HTMLCanvasElement>(*this).first();
if (canvas && !canvas->hasFocusableStyle())
return false;
}
return hasFocusableStyle();
}
bool Element::isUserActionElementInActiveChain() const
{
ASSERT(isUserActionElement());
return document().userActionElements().isInActiveChain(*this);
}
bool Element::isUserActionElementActive() const
{
ASSERT(isUserActionElement());
return document().userActionElements().isActive(*this);
}
bool Element::isUserActionElementFocused() const
{
ASSERT(isUserActionElement());
return document().userActionElements().isFocused(*this);
}
bool Element::isUserActionElementHovered() const
{
ASSERT(isUserActionElement());
return document().userActionElements().isHovered(*this);
}
bool Element::isUserActionElementDragged() const
{
ASSERT(isUserActionElement());
return document().userActionElements().isBeingDragged(*this);
}
bool Element::isUserActionElementHasFocusVisible() const
{
ASSERT(isUserActionElement());
return document().userActionElements().hasFocusVisible(*this);
}
FormListedElement* Element::asFormListedElement()
{
return nullptr;
}
ValidatedFormListedElement* Element::asValidatedFormListedElement()
{
return nullptr;
}
#if ENABLE(ATTACHMENT_ELEMENT)
AttachmentAssociatedElement* Element::asAttachmentAssociatedElement()
{
return nullptr;
}
#endif
bool Element::isUserActionElementHasFocusWithin() const
{
ASSERT(isUserActionElement());
return document().userActionElements().hasFocusWithin(*this);
}
void Element::setActive(bool value, Style::InvalidationScope invalidationScope)
{
if (value == active())
return;
{
Style::PseudoClassChangeInvalidation styleInvalidation(*this, CSSSelector::PseudoClass::Active, value, invalidationScope);
document().userActionElements().setActive(*this, value);
}
CheckedPtr renderer = this->renderer();
if (!renderer)
return;
if (!isDisabledFormControl() && renderer->style().hasUsedAppearance())