/
ContainerNode.cpp
1243 lines (1023 loc) · 48.8 KB
/
ContainerNode.cpp
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 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004-2018 Apple Inc. All rights reserved.
*
* 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 "ContainerNode.h"
#include "AXObjectCache.h"
#include "AllDescendantsCollection.h"
#include "ChildChangeInvalidation.h"
#include "ChildListMutationScope.h"
#include "ClassCollection.h"
#include "CommonAtomStrings.h"
#include "CommonVM.h"
#include "ContainerNodeAlgorithms.h"
#include "Editor.h"
#include "ElementChildIteratorInlines.h"
#include "ElementRareData.h"
#include "ElementTraversal.h"
#include "EventNames.h"
#include "FloatRect.h"
#include "GenericCachedHTMLCollection.h"
#include "HTMLFormControlsCollection.h"
#include "HTMLOptionsCollection.h"
#include "HTMLSlotElement.h"
#include "HTMLTableRowsCollection.h"
#include "InspectorInstrumentation.h"
#include "JSNodeCustom.h"
#include "LabelsNodeList.h"
#include "LocalFrameView.h"
#include "MutationEvent.h"
#include "NodeRareData.h"
#include "NodeRenderStyle.h"
#include "RadioNodeList.h"
#include "RenderBox.h"
#include "RenderTheme.h"
#include "RenderTreeUpdater.h"
#include "RenderWidget.h"
#include "SVGDocumentExtensions.h"
#include "SVGElementTypeHelpers.h"
#include "SVGNames.h"
#include "SVGUseElement.h"
#include "ScriptDisallowedScope.h"
#include "SelectorQuery.h"
#include "SlotAssignment.h"
#include "StaticNodeList.h"
#include "TemplateContentDocumentFragment.h"
#include <algorithm>
#include <variant>
#include <wtf/IsoMallocInlines.h>
namespace WebCore {
WTF_MAKE_ISO_ALLOCATED_IMPL(ContainerNode);
struct SameSizeAsContainerNode : public Node {
void* firstChild;
void* lastChild;
};
static_assert(sizeof(ContainerNode) == sizeof(SameSizeAsContainerNode), "ContainerNode should stay small");
static void dispatchChildInsertionEvents(Node&);
static void dispatchChildRemovalEvents(Ref<Node>&);
unsigned ScriptDisallowedScope::s_count = 0;
#if ASSERT_ENABLED
ScriptDisallowedScope::EventAllowedScope* ScriptDisallowedScope::EventAllowedScope::s_currentScope = nullptr;
#endif
ALWAYS_INLINE auto ContainerNode::removeAllChildrenWithScriptAssertion(ChildChange::Source source, NodeVector& children, DeferChildrenChanged deferChildrenChanged) -> DidRemoveElements
{
ASSERT(children.isEmpty());
collectChildNodes(*this, children);
if (UNLIKELY(isDocumentFragmentForInnerOuterHTML())) {
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
RELEASE_ASSERT(!connectedSubframeCount() && !hasRareData() && !wrapper());
bool hadElementChild = false;
while (RefPtr child = m_firstChild) {
hadElementChild |= is<Element>(*child);
removeBetween(nullptr, child->protectedNextSibling().get(), *child);
}
document().incDOMTreeVersion();
return hadElementChild ? DidRemoveElements::Yes : DidRemoveElements::No;
}
if (source == ChildChange::Source::API) {
ChildListMutationScope mutation(*this);
for (auto& child : children) {
mutation.willRemoveChild(child.get());
child->notifyMutationObserversNodeWillDetach();
dispatchChildRemovalEvents(child);
}
} else {
ASSERT(source == ChildChange::Source::Parser);
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
if (UNLIKELY(document().hasMutationObserversOfType(MutationObserverOptionType::ChildList))) {
ChildListMutationScope mutation(*this);
for (auto& child : children)
mutation.willRemoveChild(child.get());
}
}
disconnectSubframesIfNeeded(*this, SubframeDisconnectPolicy::DescendantsOnly);
ContainerNode::ChildChange childChange { ChildChange::Type::AllChildrenRemoved, nullptr, nullptr, nullptr, source, ContainerNode::ChildChange::AffectsElements::Unknown };
bool hadElementChild = false;
WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
{
Style::ChildChangeInvalidation styleInvalidation(*this, childChange);
if (UNLIKELY(isShadowRoot() || isInShadowTree()))
containingShadowRoot()->willRemoveAllChildren(*this);
RefAllowingPartiallyDestroyed<Document> { document() }->nodeChildrenWillBeRemoved(*this);
while (RefPtr child = m_firstChild) {
if (is<Element>(*child))
hadElementChild = true;
removeBetween(nullptr, child->protectedNextSibling().get(), *child);
auto subtreeObservability = notifyChildNodeRemoved(*this, *child);
if (source == ChildChange::Source::API && subtreeObservability == RemovedSubtreeObservability::MaybeObservableByRefPtr)
willCreatePossiblyOrphanedTreeByRemoval(*child);
}
childChange.affectsElements = hadElementChild ? ContainerNode::ChildChange::AffectsElements::Yes : ContainerNode::ChildChange::AffectsElements::No;
}
ASSERT_WITH_SECURITY_IMPLICATION(!document().selection().selection().isOrphan());
if (deferChildrenChanged == DeferChildrenChanged::No)
childrenChanged(childChange);
return hadElementChild ? DidRemoveElements::Yes : DidRemoveElements::No;
}
static ContainerNode::ChildChange makeChildChangeForRemoval(Node& childToRemove, ContainerNode::ChildChange::Source source)
{
auto changeType = [&] {
if (is<Element>(childToRemove))
return ContainerNode::ChildChange::Type::ElementRemoved;
if (is<Text>(childToRemove))
return ContainerNode::ChildChange::Type::TextRemoved;
return ContainerNode::ChildChange::Type::NonContentsChildRemoved;
}();
return {
changeType,
dynamicDowncast<Element>(childToRemove),
ElementTraversal::previousSibling(childToRemove),
ElementTraversal::nextSibling(childToRemove),
source,
changeType == ContainerNode::ChildChange::Type::ElementRemoved ? ContainerNode::ChildChange::AffectsElements::Yes : ContainerNode::ChildChange::AffectsElements::No
};
}
ALWAYS_INLINE bool ContainerNode::removeNodeWithScriptAssertion(Node& childToRemove, ChildChange::Source source)
{
Ref protectedChildToRemove { childToRemove };
ASSERT_WITH_SECURITY_IMPLICATION(childToRemove.parentNode() == this);
{
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
ChildListMutationScope(*this).willRemoveChild(childToRemove);
}
if (source == ChildChange::Source::API) {
childToRemove.notifyMutationObserversNodeWillDetach();
if (!document().shouldNotFireMutationEvents()) {
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(ScriptDisallowedScope::InMainThread::isEventDispatchAllowedInSubtree(childToRemove));
dispatchChildRemovalEvents(protectedChildToRemove);
}
if (childToRemove.parentNode() != this)
return false;
}
if (source == ChildChange::Source::Parser) {
// FIXME: Merge these two code paths. It's a bug in the parser not to update connectedSubframeCount in time.
disconnectSubframesIfNeeded(*this, SubframeDisconnectPolicy::DescendantsOnly);
} else {
ASSERT(source == ChildChange::Source::API);
if (auto containerChild = dynamicDowncast<ContainerNode>(childToRemove))
disconnectSubframesIfNeeded(*containerChild, SubframeDisconnectPolicy::RootAndDescendants);
}
if (childToRemove.parentNode() != this)
return false;
auto childChange = makeChildChangeForRemoval(childToRemove, source);
RemovedSubtreeObservability subtreeObservability;
{
WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
Style::ChildChangeInvalidation styleInvalidation(*this, childChange);
if (UNLIKELY(isShadowRoot() || isInShadowTree()))
containingShadowRoot()->resolveSlotsBeforeNodeInsertionOrRemoval();
RefAllowingPartiallyDestroyed<Document> { document() }->nodeWillBeRemoved(childToRemove);
ASSERT_WITH_SECURITY_IMPLICATION(childToRemove.parentNode() == this);
ASSERT(!childToRemove.isDocumentFragment());
RefPtr previousSibling = childToRemove.previousSibling();
RefPtr nextSibling = childToRemove.nextSibling();
removeBetween(previousSibling.get(), nextSibling.get(), childToRemove);
subtreeObservability = notifyChildNodeRemoved(*this, childToRemove);
}
if (source == ChildChange::Source::API && subtreeObservability == RemovedSubtreeObservability::MaybeObservableByRefPtr)
willCreatePossiblyOrphanedTreeByRemoval(childToRemove);
ASSERT_WITH_SECURITY_IMPLICATION(!document().selection().selection().isOrphan());
// FIXME: Move childrenChanged into ScriptDisallowedScope block.
childrenChanged(childChange);
return true;
}
enum class ReplacedAllChildren { No, YesIncludingElements, YesNotIncludingElements };
static ContainerNode::ChildChange makeChildChangeForInsertion(ContainerNode& containerNode, Node& child, Node* beforeChild, ContainerNode::ChildChange::Source source, ReplacedAllChildren replacedAllChildren)
{
if (replacedAllChildren != ReplacedAllChildren::No)
return { ContainerNode::ChildChange::Type::AllChildrenReplaced, nullptr, nullptr, nullptr, source, replacedAllChildren == ReplacedAllChildren::YesIncludingElements ? ContainerNode::ChildChange::AffectsElements::Yes : ContainerNode::ChildChange::AffectsElements::No };
auto changeType = [&] {
if (is<Element>(child))
return ContainerNode::ChildChange::Type::ElementInserted;
if (is<Text>(child))
return ContainerNode::ChildChange::Type::TextInserted;
return ContainerNode::ChildChange::Type::NonContentsChildInserted;
}();
auto* beforeChildElement = dynamicDowncast<Element>(beforeChild);
return {
changeType,
dynamicDowncast<Element>(child),
beforeChild ? ElementTraversal::previousSibling(*beforeChild) : ElementTraversal::lastChild(containerNode),
!beforeChild || beforeChildElement ? beforeChildElement : ElementTraversal::nextSibling(*beforeChild),
source,
changeType == ContainerNode::ChildChange::Type::ElementInserted ? ContainerNode::ChildChange::AffectsElements::Yes : ContainerNode::ChildChange::AffectsElements::No
};
}
enum class ClonedChildIncludesElements { No, Yes };
static ContainerNode::ChildChange makeChildChangeForCloneInsertion(ClonedChildIncludesElements clonedChildIncludesElements)
{
return { ContainerNode::ChildChange::Type::AllChildrenReplaced, nullptr, nullptr, nullptr, ContainerNode::ChildChange::Source::Clone,
clonedChildIncludesElements == ClonedChildIncludesElements::Yes ? ContainerNode::ChildChange::AffectsElements::Yes : ContainerNode::ChildChange::AffectsElements::No };
}
template<typename DOMInsertionWork>
static ALWAYS_INLINE void executeNodeInsertionWithScriptAssertion(ContainerNode& containerNode, Node& child, Node* beforeChild,
ContainerNode::ChildChange::Source source, ReplacedAllChildren replacedAllChildren, DOMInsertionWork doNodeInsertion)
{
auto childChange = makeChildChangeForInsertion(containerNode, child, beforeChild, source, replacedAllChildren);
NodeVector postInsertionNotificationTargets;
{
WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
Style::ChildChangeInvalidation styleInvalidation(containerNode, childChange);
if (UNLIKELY(containerNode.isShadowRoot() || containerNode.isInShadowTree()))
containerNode.containingShadowRoot()->resolveSlotsBeforeNodeInsertionOrRemoval();
doNodeInsertion();
ChildListMutationScope(containerNode).childAdded(child);
notifyChildNodeInserted(containerNode, child, postInsertionNotificationTargets);
}
// FIXME: Move childrenChanged into ScriptDisallowedScope block.
containerNode.childrenChanged(childChange);
ASSERT(ScriptDisallowedScope::InMainThread::isEventDispatchAllowedInSubtree(child));
for (auto& target : postInsertionNotificationTargets)
target->didFinishInsertingNode();
if (source == ContainerNode::ChildChange::Source::API)
dispatchChildInsertionEvents(child);
}
template<typename DOMInsertionWork>
static ALWAYS_INLINE void executeParserNodeInsertionIntoIsolatedTreeWithoutNotifyingParent(ContainerNode& containerNode, Node& child, DOMInsertionWork doNodeInsertion)
{
NodeVector postInsertionNotificationTargets;
{
WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
ASSERT(!containerNode.inRenderedDocument());
if (UNLIKELY(containerNode.isShadowRoot() || containerNode.isInShadowTree()))
containerNode.containingShadowRoot()->resolveSlotsBeforeNodeInsertionOrRemoval();
doNodeInsertion();
ChildListMutationScope(containerNode).childAdded(child);
notifyChildNodeInserted(containerNode, child, postInsertionNotificationTargets);
}
ASSERT(postInsertionNotificationTargets.isEmpty());
containerNode.setHasHeldBackChildrenChanged();
}
ExceptionOr<void> ContainerNode::removeSelfOrChildNodesForInsertion(Node& child, NodeVector& nodesForInsertion)
{
if (auto fragment = dynamicDowncast<DocumentFragment>(child)) {
if (!fragment->hasChildNodes())
return { };
ASSERT(nodesForInsertion.isEmpty());
fragment->removeAllChildrenWithScriptAssertion(ContainerNode::ChildChange::Source::API, nodesForInsertion);
fragment->rebuildSVGExtensionsElementsIfNecessary();
fragment->dispatchSubtreeModifiedEvent();
return { };
}
nodesForInsertion.append(child);
RefPtr oldParent = child.parentNode();
if (!oldParent)
return { };
return oldParent->removeChild(child);
}
// FIXME: This function must get a new name.
// It removes all children, not just a category called "detached children".
// So this name is terribly confusing.
void ContainerNode::removeDetachedChildren()
{
if (connectedSubframeCount()) {
for (RefPtr child = firstChild(); child; child = child->nextSibling())
child->updateAncestorConnectedSubframeCountForRemoval();
}
// FIXME: We should be able to ASSERT(!attached()) here: https://bugs.webkit.org/show_bug.cgi?id=107801
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
removeDetachedChildrenInContainer(*this);
}
static inline bool hasDisplayContents(Element *element)
{
return element && element->hasDisplayContents();
}
static inline void destroyRenderTreeIfNeeded(Node& child)
{
auto childAsElement = dynamicDowncast<Element>(child);
if (!child.renderer() && !hasDisplayContents(childAsElement))
return;
if (childAsElement)
RenderTreeUpdater::tearDownRenderers(*childAsElement);
else if (auto text = dynamicDowncast<Text>(child))
RenderTreeUpdater::tearDownRenderer(*text);
}
void ContainerNode::takeAllChildrenFrom(ContainerNode* oldParent)
{
ASSERT(oldParent);
NodeVector children;
oldParent->removeAllChildrenWithScriptAssertion(ChildChange::Source::Parser, children);
for (auto& child : children) {
if (child->parentNode()) // Previous parserAppendChild may have mutated DOM.
continue;
ASSERT(!ensurePreInsertionValidity(child, nullptr).hasException());
child->setTreeScopeRecursively(treeScope());
parserAppendChild(child);
}
}
ContainerNode::~ContainerNode()
{
if (!isDocumentNode())
willBeDeletedFrom(RefAllowingPartiallyDestroyed<Document> { document() });
removeDetachedChildren();
}
static inline bool isChildTypeAllowed(ContainerNode& newParent, Node& child)
{
if (!child.isDocumentFragment())
return newParent.childTypeAllowed(child.nodeType());
for (RefPtr node = child.firstChild(); node; node = node->nextSibling()) {
if (!newParent.childTypeAllowed(node->nodeType()))
return false;
}
return true;
}
static bool containsIncludingHostElements(const Node& possibleAncestor, const Node& node)
{
RefPtr<const Node> currentNode = &node;
do {
if (currentNode == &possibleAncestor)
return true;
RefPtr<const ContainerNode> parent = currentNode->parentNode();
if (!parent) {
if (auto* shadowRoot = dynamicDowncast<ShadowRoot>(*currentNode))
parent = shadowRoot->host();
else if (auto* fragment = dynamicDowncast<TemplateContentDocumentFragment>(*currentNode))
parent = fragment->host();
}
currentNode = WTFMove(parent);
} while (currentNode);
return false;
}
enum class ShouldValidateChildParent : bool { No, Yes };
static inline ExceptionOr<void> checkAcceptChild(ContainerNode& newParent, Node& newChild, const Node* refChild, Document::AcceptChildOperation operation, ShouldValidateChildParent shouldValidateChildParent)
{
if (containsIncludingHostElements(newChild, newParent))
return Exception { ExceptionCode::HierarchyRequestError };
// Use common case fast path if possible.
if ((newChild.isElementNode() || newChild.isTextNode()) && newParent.isElementNode()) {
ASSERT(!newParent.isDocumentTypeNode());
ASSERT(isChildTypeAllowed(newParent, newChild));
if (shouldValidateChildParent == ShouldValidateChildParent::Yes && refChild && refChild->parentNode() != &newParent)
return Exception { ExceptionCode::NotFoundError };
return { };
}
// This should never happen, but also protect release builds from tree corruption.
ASSERT(!newChild.isPseudoElement());
if (newChild.isPseudoElement())
return Exception { ExceptionCode::HierarchyRequestError };
if (shouldValidateChildParent == ShouldValidateChildParent::Yes && refChild && refChild->parentNode() != &newParent)
return Exception { ExceptionCode::NotFoundError };
if (auto newParentDocument = dynamicDowncast<Document>(newParent)) {
if (!newParentDocument->canAcceptChild(newChild, refChild, operation))
return Exception { ExceptionCode::HierarchyRequestError };
} else if (!isChildTypeAllowed(newParent, newChild))
return Exception { ExceptionCode::HierarchyRequestError };
return { };
}
static inline ExceptionOr<void> checkAcceptChildGuaranteedNodeTypes(ContainerNode& newParent, Node& newChild)
{
ASSERT(!newParent.isDocumentTypeNode());
ASSERT(isChildTypeAllowed(newParent, newChild));
if (containsIncludingHostElements(newChild, newParent))
return Exception { ExceptionCode::HierarchyRequestError };
return { };
}
// https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
ExceptionOr<void> ContainerNode::ensurePreInsertionValidity(Node& newChild, Node* refChild)
{
return checkAcceptChild(*this, newChild, refChild, Document::AcceptChildOperation::InsertOrAdd, ShouldValidateChildParent::Yes);
}
// https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity when node is a new DocumentFragment created in "converting nodes into a node"
ExceptionOr<void> ContainerNode::ensurePreInsertionValidityForPhantomDocumentFragment(NodeVector& newChildren, Node* refChild)
{
if (UNLIKELY(is<Document>(*this))) {
bool hasSeenElement = false;
for (auto& child : newChildren) {
if (!is<Element>(child))
continue;
if (hasSeenElement)
return Exception { ExceptionCode::HierarchyRequestError };
hasSeenElement = true;
}
}
for (auto& child : newChildren) {
if (auto result = checkAcceptChild(*this, child, refChild, Document::AcceptChildOperation::InsertOrAdd, ShouldValidateChildParent::Yes); result.hasException())
return result;
}
return { };
}
// https://dom.spec.whatwg.org/#concept-node-replace
static inline ExceptionOr<void> checkPreReplacementValidity(ContainerNode& newParent, Node& newChild, Node& oldChild, ShouldValidateChildParent shouldValidateChildParent)
{
return checkAcceptChild(newParent, newChild, &oldChild, Document::AcceptChildOperation::Replace, shouldValidateChildParent);
}
ExceptionOr<void> ContainerNode::insertBefore(Node& newChild, RefPtr<Node>&& refChild)
{
// Check that this node is not "floating".
// If it is, it can be deleted as a side effect of sending mutation events.
ASSERT(refCount() || parentOrShadowHostNode());
// Make sure adding the new child is OK.
auto validityCheckResult = ensurePreInsertionValidity(newChild, refChild.get());
if (validityCheckResult.hasException())
return validityCheckResult.releaseException();
if (refChild == &newChild)
refChild = newChild.nextSibling();
// insertBefore(node, null) is equivalent to appendChild(node)
if (!refChild)
return appendChildWithoutPreInsertionValidityCheck(newChild);
Ref<ContainerNode> protectedThis(*this);
Ref next = refChild.releaseNonNull();
NodeVector targets;
auto removeResult = removeSelfOrChildNodesForInsertion(newChild, targets);
if (removeResult.hasException())
return removeResult.releaseException();
if (targets.isEmpty())
return { };
// We need this extra check because removeSelfOrChildNodesForInsertion() can fire mutation events.
for (auto& child : targets) {
auto checkAcceptResult = checkAcceptChildGuaranteedNodeTypes(*this, child);
if (checkAcceptResult.hasException())
return checkAcceptResult.releaseException();
}
InspectorInstrumentation::willInsertDOMNode(protectedDocument(), *this);
ChildListMutationScope mutation(*this);
for (auto& child : targets) {
// Due to arbitrary code running in response to a DOM mutation event it's
// possible that "next" is no longer a child of "this".
// It's also possible that "child" has been inserted elsewhere.
// In either of those cases, we'll just stop.
if (next->parentNode() != this)
break;
if (child->parentNode())
break;
executeNodeInsertionWithScriptAssertion(*this, child.get(), next.ptr(), ChildChange::Source::API, ReplacedAllChildren::No, [&] {
child->setTreeScopeRecursively(treeScope());
insertBeforeCommon(next, child);
});
}
dispatchSubtreeModifiedEvent();
return { };
}
void ContainerNode::insertBeforeCommon(Node& nextChild, Node& newChild)
{
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
ASSERT(!newChild.parentNode()); // Use insertBefore if you need to handle reparenting (and want DOM mutation events).
ASSERT(!newChild.nextSibling());
ASSERT(!newChild.previousSibling());
ASSERT(!newChild.isShadowRoot());
RefPtr previousSibling = nextChild.previousSibling();
ASSERT(m_lastChild != previousSibling);
nextChild.setPreviousSibling(&newChild);
if (previousSibling) {
ASSERT(m_firstChild != &nextChild);
ASSERT(previousSibling->nextSibling() == &nextChild);
previousSibling->setNextSibling(&newChild);
} else {
ASSERT(m_firstChild == &nextChild);
m_firstChild = &newChild;
}
newChild.setParentNode(this);
newChild.setPreviousSibling(previousSibling.get());
newChild.setNextSibling(&nextChild);
}
void ContainerNode::appendChildCommon(Node& child)
{
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
child.setParentNode(this);
if (auto lastChild = protectedLastChild()) {
child.setPreviousSibling(lastChild.get());
lastChild->setNextSibling(&child);
} else
m_firstChild = &child;
m_lastChild = &child;
}
void ContainerNode::parserInsertBefore(Node& newChild, Node& nextChild)
{
ASSERT(nextChild.parentNode() == this);
ASSERT(!newChild.isDocumentFragment());
ASSERT(!hasTagName(HTMLNames::templateTag));
if (nextChild.previousSibling() == &newChild || &nextChild == &newChild) // nothing to do
return;
executeNodeInsertionWithScriptAssertion(*this, newChild, &nextChild, ChildChange::Source::Parser, ReplacedAllChildren::No, [&] {
if (&document() != &newChild.document())
document().adoptNode(newChild);
insertBeforeCommon(nextChild, newChild);
newChild.setTreeScopeRecursively(treeScope());
newChild.updateAncestorConnectedSubframeCountForInsertion();
});
}
ExceptionOr<void> ContainerNode::replaceChild(Node& newChild, Node& oldChild)
{
// Check that this node is not "floating".
// If it is, it can be deleted as a side effect of sending mutation events.
ASSERT(refCount() || parentOrShadowHostNode());
Ref protectedThis { *this };
// Make sure replacing the old child with the new is ok
auto validityResult = checkPreReplacementValidity(*this, newChild, oldChild, ShouldValidateChildParent::Yes);
if (validityResult.hasException())
return validityResult.releaseException();
RefPtr refChild = oldChild.nextSibling();
if (refChild.get() == &newChild)
refChild = refChild->nextSibling();
NodeVector targets;
{
ChildListMutationScope mutation(*this);
auto collectResult = removeSelfOrChildNodesForInsertion(newChild, targets);
if (collectResult.hasException())
return collectResult.releaseException();
}
// Do this one more time because removeSelfOrChildNodesForInsertion() fires a MutationEvent.
for (auto& child : targets) {
validityResult = checkPreReplacementValidity(*this, child, oldChild, ShouldValidateChildParent::No);
if (validityResult.hasException())
return validityResult.releaseException();
}
// Remove the node we're replacing.
Ref protectOldChild { oldChild };
ChildListMutationScope mutation(*this);
// If oldChild == newChild then oldChild no longer has a parent at this point.
if (oldChild.parentNode()) {
auto removeResult = removeChild(oldChild);
if (removeResult.hasException())
return removeResult.releaseException();
// Does this one more time because removeChild() fires a MutationEvent.
for (auto& child : targets) {
validityResult = checkPreReplacementValidity(*this, child, oldChild, ShouldValidateChildParent::No);
if (validityResult.hasException())
return validityResult.releaseException();
}
}
InspectorInstrumentation::willInsertDOMNode(protectedDocument(), *this);
// Add the new child(ren).
for (auto& child : targets) {
// Due to arbitrary code running in response to a DOM mutation event it's
// possible that "refChild" is no longer a child of "this".
// It's also possible that "child" has been inserted elsewhere.
// In either of those cases, we'll just stop.
if (refChild && refChild->parentNode() != this)
break;
if (child->parentNode())
break;
executeNodeInsertionWithScriptAssertion(*this, child.get(), refChild.get(), ChildChange::Source::API, ReplacedAllChildren::No, [&] {
child->setTreeScopeRecursively(treeScope());
if (refChild)
insertBeforeCommon(*refChild, child.get());
else
appendChildCommon(child);
});
}
dispatchSubtreeModifiedEvent();
return { };
}
void ContainerNode::disconnectDescendantFrames()
{
disconnectSubframesIfNeeded(*this, SubframeDisconnectPolicy::RootAndDescendants);
}
ExceptionOr<void> ContainerNode::removeChild(Node& oldChild)
{
// Check that this node is not "floating".
// If it is, it can be deleted as a side effect of sending mutation events.
ASSERT(refCount() || parentOrShadowHostNode());
Ref protectedThis { *this };
Ref protectedOldChild { oldChild };
// NotFoundError: Raised if oldChild is not a child of this node.
if (oldChild.parentNode() != this)
return Exception { ExceptionCode::NotFoundError };
if (!removeNodeWithScriptAssertion(oldChild, ChildChange::Source::API))
return Exception { ExceptionCode::NotFoundError };
rebuildSVGExtensionsElementsIfNecessary();
dispatchSubtreeModifiedEvent();
auto* element = dynamicDowncast<Element>(oldChild);
if (element && (element->lastRememberedLogicalWidth() || element->lastRememberedLogicalHeight())) {
// The disconnected element could be unobserved because of other properties, here we need to make sure it is observed,
// so that deliver could be triggered and it would clear lastRememberedSize.
document().observeForContainIntrinsicSize(*element);
document().resetObservationSizeForContainIntrinsicSize(*element);
}
return { };
}
void ContainerNode::removeBetween(Node* previousChild, Node* nextChild, Node& oldChild)
{
InspectorInstrumentation::didRemoveDOMNode(RefAllowingPartiallyDestroyed<Document> { oldChild.document() }, oldChild);
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
ASSERT(oldChild.parentNode() == this);
destroyRenderTreeIfNeeded(oldChild);
if (UNLIKELY(hasShadowRootContainingSlots()))
shadowRoot()->willRemoveAssignedNode(oldChild);
if (nextChild) {
nextChild->setPreviousSibling(previousChild);
oldChild.setNextSibling(nullptr);
} else {
ASSERT(m_lastChild == &oldChild);
m_lastChild = previousChild;
}
if (previousChild) {
previousChild->setNextSibling(nextChild);
oldChild.setPreviousSibling(nullptr);
} else {
ASSERT(m_firstChild == &oldChild);
m_firstChild = nextChild;
}
ASSERT(m_firstChild != &oldChild);
ASSERT(m_lastChild != &oldChild);
ASSERT(!oldChild.previousSibling());
ASSERT(!oldChild.nextSibling());
oldChild.setParentNode(nullptr);
oldChild.setTreeScopeRecursively(document());
}
void ContainerNode::parserRemoveChild(Node& oldChild)
{
removeNodeWithScriptAssertion(oldChild, ChildChange::Source::Parser);
}
// https://dom.spec.whatwg.org/#concept-node-replace-all
void ContainerNode::replaceAll(Node* node)
{
if (!node) {
ChildListMutationScope mutation(*this);
removeChildren();
return;
}
// FIXME: The code below is roughly correct for a new text node with no parent, but needs enhancement to work properly for more complex cases.
if (!hasChildNodes()) {
appendChildWithoutPreInsertionValidityCheck(*node);
return;
}
Ref protectedThis { *this };
ChildListMutationScope mutation(*this);
NodeVector removedChildren;
auto didRemoveElements = removeAllChildrenWithScriptAssertion(ChildChange::Source::API, removedChildren, DeferChildrenChanged::Yes);
auto replacedAllChildren = is<Element>(*node) || didRemoveElements == DidRemoveElements::Yes ? ReplacedAllChildren::YesIncludingElements : ReplacedAllChildren::YesNotIncludingElements;
executeNodeInsertionWithScriptAssertion(*this, *node, nullptr, ChildChange::Source::API, replacedAllChildren, [&] {
InspectorInstrumentation::willInsertDOMNode(protectedDocument(), *this);
node->setTreeScopeRecursively(treeScope());
appendChildCommon(*node);
});
rebuildSVGExtensionsElementsIfNecessary();
dispatchSubtreeModifiedEvent();
}
// https://dom.spec.whatwg.org/#string-replace-all
void ContainerNode::stringReplaceAll(String&& string)
{
replaceAll(string.isEmpty() ? nullptr : document().createTextNode(WTFMove(string)).ptr());
}
inline void ContainerNode::rebuildSVGExtensionsElementsIfNecessary()
{
RefAllowingPartiallyDestroyed<Document> document = this->document();
if (document->svgExtensions() && !is<SVGUseElement>(shadowHost()))
document->accessSVGExtensions().rebuildElements();
}
// this differs from other remove functions because it forcibly removes all the children,
// regardless of read-only status or event exceptions, e.g.
void ContainerNode::removeChildren()
{
if (!m_firstChild)
return;
Ref protectedThis { *this };
NodeVector removedChildren;
removeAllChildrenWithScriptAssertion(ChildChange::Source::API, removedChildren);
rebuildSVGExtensionsElementsIfNecessary();
dispatchSubtreeModifiedEvent();
}
ExceptionOr<void> ContainerNode::appendChild(Node& newChild)
{
// Check that this node is not "floating".
// If it is, it can be deleted as a side effect of sending mutation events.
ASSERT(refCount() || parentOrShadowHostNode());
// Make sure adding the new child is ok
auto validityCheckResult = ensurePreInsertionValidity(newChild, nullptr);
if (validityCheckResult.hasException())
return validityCheckResult.releaseException();
return appendChildWithoutPreInsertionValidityCheck(newChild);
}
ExceptionOr<void> ContainerNode::appendChildWithoutPreInsertionValidityCheck(Node& newChild)
{
Ref protectedThis { *this };
NodeVector targets;
auto removeResult = removeSelfOrChildNodesForInsertion(newChild, targets);
if (removeResult.hasException())
return removeResult.releaseException();
if (targets.isEmpty())
return { };
// We need this extra check because removeSelfOrChildNodesForInsertion() can fire mutation events.
for (auto& child : targets) {
auto nodeTypeResult = checkAcceptChildGuaranteedNodeTypes(*this, child);
if (nodeTypeResult.hasException())
return nodeTypeResult.releaseException();
}
InspectorInstrumentation::willInsertDOMNode(protectedDocument(), *this);
// Now actually add the child(ren)
ChildListMutationScope mutation(*this);
for (auto& child : targets) {
// If the child has a parent again, just stop what we're doing, because
// that means someone is doing something with DOM mutation -- can't re-parent
// a child that already has a parent.
if (child->parentNode())
break;
// Append child to the end of the list
executeNodeInsertionWithScriptAssertion(*this, child.get(), nullptr, ChildChange::Source::API, ReplacedAllChildren::No, [&] {
child->setTreeScopeRecursively(treeScope());
appendChildCommon(child);
});
}
dispatchSubtreeModifiedEvent();
return { };
}
ExceptionOr<void> ContainerNode::insertChildrenBeforeWithoutPreInsertionValidityCheck(NodeVector&& newChildren, Node* nextChild)
{
for (auto& child : newChildren) {
if (RefPtr oldParent = child->parentNode()) {
if (nextChild == child.ptr())
nextChild = child->nextSibling();
if (auto result = oldParent->removeChild(child); result.hasException())
return result.releaseException();
}
}
// We need this extra check because removeChild() above can fire mutation events.
for (auto& child : newChildren) {
auto nodeTypeResult = checkAcceptChildGuaranteedNodeTypes(*this, child);
if (nodeTypeResult.hasException())
return nodeTypeResult.releaseException();
}
InspectorInstrumentation::willInsertDOMNode(protectedDocument(), *this);
ChildListMutationScope mutation(*this);
for (auto& child : newChildren) {
if (nextChild && nextChild->parentNode() != this) // Event listeners moved nextChild elsewhere.
break;
if (child->parentNode()) // Event listeners inserted this child elsewhere.
break;
executeNodeInsertionWithScriptAssertion(*this, child.get(), nextChild, ChildChange::Source::API, ReplacedAllChildren::No, [&] {
child->setTreeScopeRecursively(treeScope());
if (nextChild)
insertBeforeCommon(*nextChild, child.get());
else
appendChildCommon(child);
});
}
dispatchSubtreeModifiedEvent();
return { };
}
void ContainerNode::parserAppendChild(Node& newChild)
{
ASSERT(!newChild.parentNode()); // Use appendChild if you need to handle reparenting (and want DOM mutation events).
ASSERT(!newChild.isDocumentFragment());
ASSERT(!hasTagName(HTMLNames::templateTag));
executeNodeInsertionWithScriptAssertion(*this, newChild, nullptr, ChildChange::Source::Parser, ReplacedAllChildren::No, [&] {
if (&document() != &newChild.document())
document().adoptNode(newChild);
appendChildCommon(newChild);
newChild.setTreeScopeRecursively(treeScope());
newChild.updateAncestorConnectedSubframeCountForInsertion();
});
}
void ContainerNode::parserAppendChildIntoIsolatedTree(Node& newChild)
{
ASSERT(!inRenderedDocument());
ASSERT(!newChild.traverseToRootNode().wrapper());
ASSERT(!newChild.parentNode()); // Use appendChild if you need to handle reparenting (and want DOM mutation events).
ASSERT(is<Element>(*this) || is<DocumentFragment>(*this)); // Only Element calls parserNotifyChildrenChanged
ASSERT(is<DocumentFragment>(*this) || !isParsingChildrenFinished());
ASSERT(!newChild.isDocumentFragment());
ASSERT(!hasTagName(HTMLNames::templateTag));
RELEASE_ASSERT(&newChild.document() == &document());
executeParserNodeInsertionIntoIsolatedTreeWithoutNotifyingParent(*this, newChild, [&] {
appendChildCommon(newChild);
newChild.setTreeScopeRecursively(treeScope());
newChild.updateAncestorConnectedSubframeCountForInsertion();
});
}
void ContainerNode::parserNotifyChildrenChanged()
{
ASSERT(!inRenderedDocument());
ASSERT(!traverseToRootNode().wrapper());
ASSERT(is<Element>(*this));
ASSERT(hasHeldBackChildrenChanged());
clearHasHeldBackChildrenChanged();
childrenChanged(ChildChange { ContainerNode::ChildChange::Type::AllChildrenReplaced, nullptr, nullptr, nullptr, ChildChange::Source::Parser,
firstElementChild() ? ChildChange::AffectsElements::Yes : ChildChange::AffectsElements::No });
}
ExceptionOr<void> ContainerNode::appendChild(ChildChange::Source source, Node& newChild)
{
if (source == ChildChange::Source::Parser) {
parserAppendChild(newChild);
return { };
}
return appendChild(newChild);
}
void ContainerNode::childrenChanged(const ChildChange& change)
{
RefAllowingPartiallyDestroyed<Document> document = this->document();
document->incDOMTreeVersion();
if (change.affectsElements == ChildChange::AffectsElements::Yes)
document->invalidateAccessKeyCache();
// FIXME: Unclear why it's always safe to skip this when parser is adding children.
// FIXME: Seems like it's equally safe to skip for TextInserted and TextRemoved as for TextChanged.
// FIXME: Should use switch for change type so we remember to update when adding new types.
if (change.source == ChildChange::Source::API && change.type != ChildChange::Type::TextChanged)
document->updateRangesAfterChildrenChanged(*this);