forked from LadybirdBrowser/ladybird
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode.cpp
More file actions
3532 lines (2994 loc) · 156 KB
/
Copy pathNode.cpp
File metadata and controls
3532 lines (2994 loc) · 156 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) 2018-2024, Andreas Kling <andreas@ladybird.org>
* Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
* Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
* Copyright (c) 2024-2025, Jelle Raaijmakers <jelle@ladybird.org>
* Copyright (c) 2025, Shannon Booth <shannon@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/HashTable.h>
#include <AK/JsonObjectSerializer.h>
#include <AK/NeverDestroyed.h>
#include <AK/StringBuilder.h>
#include <AK/Utf16StringBuilder.h>
#include <LibGC/DeferGC.h>
#include <LibGC/WeakHashMap.h>
#include <LibJS/Runtime/ExternalMemory.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibWeb/Animations/Animation.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/Node.h>
#include <LibWeb/CSS/ComputedProperties.h>
#include <LibWeb/CSS/Invalidation/NodeInvalidator.h>
#include <LibWeb/CSS/Invalidation/StructuralMutationInvalidator.h>
#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
#include <LibWeb/DOM/AccessibilityTreeNode.h>
#include <LibWeb/DOM/Attr.h>
#include <LibWeb/DOM/CDATASection.h>
#include <LibWeb/DOM/CharacterData.h>
#include <LibWeb/DOM/Comment.h>
#include <LibWeb/DOM/DocumentFragment.h>
#include <LibWeb/DOM/DocumentType.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/ElementFactory.h>
#include <LibWeb/DOM/Event.h>
#include <LibWeb/DOM/EventDispatcher.h>
#include <LibWeb/DOM/IDLEventListener.h>
#include <LibWeb/DOM/LiveNodeList.h>
#include <LibWeb/DOM/MutationType.h>
#include <LibWeb/DOM/NamedNodeMap.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/NodeIterator.h>
#include <LibWeb/DOM/ProcessingInstruction.h>
#include <LibWeb/DOM/Range.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/DOM/StaticNodeList.h>
#include <LibWeb/DOM/XMLDocument.h>
#include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
#include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
#include <LibWeb/HTML/HTMLAnchorElement.h>
#include <LibWeb/HTML/HTMLDocument.h>
#include <LibWeb/HTML/HTMLFieldSetElement.h>
#include <LibWeb/HTML/HTMLImageElement.h>
#include <LibWeb/HTML/HTMLInputElement.h>
#include <LibWeb/HTML/HTMLLegendElement.h>
#include <LibWeb/HTML/HTMLScriptElement.h>
#include <LibWeb/HTML/HTMLSelectElement.h>
#include <LibWeb/HTML/HTMLSlotElement.h>
#include <LibWeb/HTML/HTMLStyleElement.h>
#include <LibWeb/HTML/HTMLTableElement.h>
#include <LibWeb/HTML/HTMLTextAreaElement.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/NavigableContainer.h>
#include <LibWeb/HTML/Parser/HTMLParser.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/XMLSerializer.h>
#include <LibWeb/Infra/CharacterTypes.h>
#include <LibWeb/InvalidateDisplayList.h>
#include <LibWeb/Layout/Node.h>
#include <LibWeb/Layout/TextNode.h>
#include <LibWeb/Layout/TextOffsetMapping.h>
#include <LibWeb/MathML/MathMLElement.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Painting/Paintable.h>
#include <LibWeb/SVG/SVGElement.h>
#include <LibWeb/SVG/SVGTitleElement.h>
#include <LibWeb/XLink/AttributeNames.h>
namespace Web::DOM {
static UniqueNodeID s_next_unique_id;
static GC::WeakHashMap<UniqueNodeID, Node>& node_directory()
{
static NeverDestroyed<GC::WeakHashMap<UniqueNodeID, Node>> directory;
return *directory;
}
static UniqueNodeID allocate_unique_id(Node& node)
{
auto id = s_next_unique_id;
++s_next_unique_id;
node_directory().set(id, node);
return id;
}
static void deallocate_unique_id(UniqueNodeID node_id)
{
if (!node_directory().remove(node_id))
VERIFY_NOT_REACHED();
}
Node* Node::from_unique_id(UniqueNodeID unique_id)
{
return node_directory().get(unique_id);
}
Node::Node(JS::Realm& realm, Document& document, NodeType type)
: EventTarget(realm)
, m_document(&document)
, m_type(type)
, m_unique_id(allocate_unique_id(*this))
{
// A Document is its own shadow-including root, so it is always connected.
if (type == NodeType::DOCUMENT_NODE)
m_is_connected = true;
}
Node::Node(Document& document, NodeType type)
: Node(document.realm(), document, type)
{
}
Node::~Node() = default;
void Node::finalize()
{
Base::finalize();
deallocate_unique_id(m_unique_id);
}
void Node::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
TreeNode::visit_edges(visitor);
visitor.visit(m_document);
visitor.visit(m_child_nodes);
if (m_registered_observer_list) {
visitor.visit(*m_registered_observer_list);
}
}
size_t Node::external_memory_size() const
{
auto size = Base::external_memory_size();
if (m_registered_observer_list)
size = JS::saturating_add_external_memory_size(size, JS::vector_external_memory_size(*m_registered_observer_list));
return size;
}
// https://dom.spec.whatwg.org/#dom-node-baseuri
String Node::base_uri() const
{
// Return this’s node document’s document base URL, serialized.
return document().base_url().to_string();
}
HTML::HTMLAnchorElement const* Node::enclosing_link_element() const
{
for (auto* node = this; node; node = node->parent()) {
auto const* anchor_element = as_if<HTML::HTMLAnchorElement>(*node);
if (!anchor_element)
continue;
if (anchor_element->has_attribute(HTML::AttributeNames::href))
return anchor_element;
}
return nullptr;
}
HTML::HTMLElement const* Node::enclosing_html_element() const
{
return first_ancestor_of_type<HTML::HTMLElement>();
}
HTML::HTMLElement const* Node::enclosing_html_element_with_attribute(Utf16FlyString const& attribute) const
{
for (auto* node = this; node; node = node->parent()) {
if (auto* html_element = as_if<HTML::HTMLElement>(*node); html_element && html_element->has_attribute(attribute))
return html_element;
}
return nullptr;
}
Optional<Utf16String> Node::alternative_text() const
{
return {};
}
// https://dom.spec.whatwg.org/#concept-descendant-text-content
Utf16String Node::descendant_text_content() const
{
Utf16StringBuilder builder;
for_each_in_subtree_of_type<Text>([&](auto& text_node) {
builder.append(text_node.data());
return TraversalDecision::Continue;
});
return builder.to_string();
}
// https://dom.spec.whatwg.org/#dom-node-textcontent
Optional<Utf16String> Node::text_content() const
{
// The textContent getter steps are to return the following, switching on the interface this implements:
// If DocumentFragment or Element, return the descendant text content of this.
if (is<DocumentFragment>(this) || is<Element>(this))
return descendant_text_content();
// If CharacterData, return this’s data.
if (auto const* character_data = as_if<CharacterData>(*this))
return character_data->data();
// If Attr node, return this's value.
if (auto const* attribute = as_if<Attr>(*this))
return attribute->value();
// Otherwise, return null
return {};
}
// https://dom.spec.whatwg.org/#ref-for-dom-node-textcontent%E2%91%A0
WebIDL::ExceptionOr<void> Node::set_text_content(Optional<Utf16String> const& maybe_content)
{
// The textContent setter steps are to, if the given value is null, act as if it was the empty string instead,
// and then do as described below, switching on the interface this implements:
auto content = maybe_content.value_or({});
// If DocumentFragment or Element, string replace all with the given value within this.
if (is<DocumentFragment>(this) || is<Element>(this)) {
// OPTIMIZATION: Replacing nothing with nothing is a no-op. Avoid all invalidation in this case.
if (!first_child() && content.is_empty()) {
return {};
}
string_replace_all(content);
}
// If CharacterData, replace data with node this, offset 0, count this’s length, and data the given value.
else if (auto* character_data = as_if<CharacterData>(*this)) {
TRY(character_data->replace_data(0, character_data->length_in_utf16_code_units(), content));
}
// If Attr, set an existing attribute value with this and the given value.
else if (auto* attribute = as_if<Attr>(*this)) {
TRY(attribute->set_value(content));
}
// Otherwise, do nothing.
if (is_connected()) {
invalidate_style(StyleInvalidationReason::NodeSetTextContent);
set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::NodeSetTextContent);
}
document().bump_dom_tree_version();
return {};
}
// https://dom.spec.whatwg.org/#dom-node-normalize
WebIDL::ExceptionOr<void> Node::normalize()
{
auto contiguous_exclusive_text_nodes_excluding_self = [](Node& node) {
// https://dom.spec.whatwg.org/#contiguous-exclusive-text-nodes
// The contiguous exclusive Text nodes of a node node are node, node’s previous sibling exclusive Text node, if any,
// and its contiguous exclusive Text nodes, and node’s next sibling exclusive Text node, if any,
// and its contiguous exclusive Text nodes, avoiding any duplicates.
// NOTE: The callers of this method require node itself to be excluded.
Vector<Text*> nodes;
auto* current_node = node.previous_sibling();
while (current_node && current_node->is_exclusive_text()) {
nodes.append(static_cast<Text*>(current_node));
current_node = current_node->previous_sibling();
}
// Reverse the order of the nodes so that they are in tree order.
nodes.reverse();
current_node = node.next_sibling();
while (current_node && current_node->is_exclusive_text()) {
nodes.append(static_cast<Text*>(current_node));
current_node = current_node->next_sibling();
}
return nodes;
};
// The normalize() method steps are to run these steps for each descendant exclusive Text node node of this
Vector<Text&> descendant_exclusive_text_nodes;
for_each_in_inclusive_subtree_of_type<Text>([&](Text const& node) {
if (!node.is_cdata_section())
descendant_exclusive_text_nodes.append(const_cast<Text&>(node));
return TraversalDecision::Continue;
});
for (auto& node : descendant_exclusive_text_nodes) {
// 1. Let length be node’s length.
auto& character_data = static_cast<CharacterData&>(node);
auto length = character_data.length_in_utf16_code_units();
// 2. If length is zero, then remove node and continue with the next exclusive Text node, if any.
if (length == 0) {
if (node.parent())
node.remove();
continue;
}
// 3. Let data be the concatenation of the data of node’s contiguous exclusive Text nodes (excluding itself), in tree order.
Utf16StringBuilder data;
for (auto const& text_node : contiguous_exclusive_text_nodes_excluding_self(node))
data.append(text_node->data());
// 4. Replace data with node node, offset length, count 0, and data data.
TRY(character_data.replace_data(length, 0, data.to_string()));
// 5. Let currentNode be node’s next sibling.
auto* current_node = node.next_sibling();
// 6. While currentNode is an exclusive Text node:
while (current_node && current_node->is_exclusive_text()) {
// 1. For each live range whose start node is currentNode, add length to its start offset and set its start
// node to node.
for (auto& range : Range::live_ranges()) {
if (range->start_container() == current_node) {
range->increase_start_offset(length);
range->set_start_node(node);
}
}
// 2. For each live range whose end node is currentNode, add length to its end offset and set its end node
// to node.
for (auto& range : Range::live_ranges()) {
if (range->end_container() == current_node) {
range->increase_end_offset(length);
range->set_end_node(node);
}
}
// 3. For each live range whose start node is currentNode’s parent and start offset is currentNode’s index,
// set its start node to node and its start offset to length.
for (auto& range : Range::live_ranges()) {
if (range->start_container() == current_node->parent() && range->start_offset() == current_node->index()) {
range->set_start_node(node);
range->set_start_offset(length);
}
}
// 4. For each live range whose end node is currentNode’s parent and end offset is currentNode’s index, set
// its end node to node and its end offset to length.
for (auto& range : Range::live_ranges()) {
if (range->end_container() == current_node->parent() && range->end_offset() == current_node->index()) {
range->set_end_node(node);
range->set_end_offset(length);
}
}
// 5. Add currentNode’s length to length.
length += static_cast<Text&>(*current_node).length();
// 6. Set currentNode to its next sibling.
current_node = current_node->next_sibling();
}
// 7. Remove node’s contiguous exclusive Text nodes (excluding itself), in tree order.
for (auto const& text_node : contiguous_exclusive_text_nodes_excluding_self(node))
text_node->remove();
}
return {};
}
// https://dom.spec.whatwg.org/#dom-node-nodevalue
Optional<Utf16String> Node::node_value() const
{
// The nodeValue getter steps are to return the following, switching on the interface this implements:
// If Attr, return this’s value.
if (auto* attr = as_if<Attr>(this)) {
return attr->value();
}
// If CharacterData, return this’s data.
if (auto* character_data = as_if<CharacterData>(this)) {
return character_data->data();
}
// Otherwise, return null.
return {};
}
// https://dom.spec.whatwg.org/#ref-for-dom-node-nodevalue%E2%91%A0
WebIDL::ExceptionOr<void> Node::set_node_value(Optional<Utf16String> const& maybe_value)
{
// The nodeValue setter steps are to, if the given value is null, act as if it was the empty string instead,
// and then do as described below, switching on the interface this implements:
auto value = maybe_value.value_or({});
// If Attr, set an existing attribute value with this and the given value.
if (auto* attr = as_if<Attr>(this)) {
TRY(attr->set_value(value));
} else if (auto* character_data = as_if<CharacterData>(this)) {
// If CharacterData, replace data with node this, offset 0, count this’s length, and data the given value.
character_data->set_data(value);
}
// Otherwise, do nothing.
return {};
}
// https://html.spec.whatwg.org/multipage/document-sequences.html#node-navigable
GC::Ptr<HTML::LocalNavigable> Node::navigable() const
{
// To get the node navigable of a node node, return the navigable whose active document is node's node document,
// or null if there is no such navigable.
return document().navigable();
}
CSS::StyleScope& Node::style_scope()
{
auto& root = this->root();
if (auto* shadow_root = as_if<ShadowRoot>(root)) {
if (shadow_root->uses_document_style_sheets())
return document().style_scope();
return shadow_root->style_scope();
}
return document().style_scope();
}
void Node::for_each_style_scope_which_may_observe_the_node(Function<void(CSS::StyleScope&)> const& callback)
{
HashTable<CSS::StyleScope*> visited_scopes;
auto visit = [&](CSS::StyleScope& scope) {
if (visited_scopes.set(&scope) != AK::HashSetResult::InsertedNewEntry)
return;
callback(scope);
};
visit(style_scope());
if (auto* element = as_if<Element>(*this)) {
if (auto shadow_root = element->shadow_root())
visit(shadow_root->style_scope());
}
for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
visit(ancestor->style_scope());
if (auto* element = as_if<Element>(*ancestor)) {
if (auto shadow_root = element->shadow_root())
visit(shadow_root->style_scope());
}
}
}
void Node::invalidate_style(StyleInvalidationReason reason)
{
CSS::Invalidation::invalidate_node_style(*this, reason);
}
void Node::invalidate_style(StyleInvalidationReason reason, Vector<CSS::InvalidationSet::Property> const& properties, StyleInvalidationOptions options)
{
CSS::Invalidation::invalidate_node_style_for_properties(*this, reason, properties, options);
}
Utf16String Node::child_text_content() const
{
auto const* parent_node = as_if<ParentNode>(*this);
if (!parent_node)
return {};
Utf16StringBuilder builder;
parent_node->for_each_child_of_type<Text>([&](auto const& child) {
if (auto content = child.text_content(); content.has_value())
builder.append(*content);
return IterationDecision::Continue;
});
return builder.to_string();
}
// https://dom.spec.whatwg.org/#concept-shadow-including-root
Node& Node::shadow_including_root()
{
// The shadow-including root of an object is its root’s host’s shadow-including root,
// if the object’s root is a shadow root; otherwise its root.
auto& node_root = root();
if (auto* shadow_root = as_if<ShadowRoot>(node_root)) {
if (auto* host = shadow_root->host(); host)
return host->shadow_including_root();
}
return node_root;
}
// https://dom.spec.whatwg.org/#concept-closed-shadow-hidden
bool Node::is_closed_shadow_hidden_from(Node const& b) const
{
// A node A is closed-shadow-hidden from a node B if all of the following conditions are true:
auto const& a_root = root();
// - A’s root is a shadow root.
if (!a_root.is_shadow_root())
return false;
// - A’s root is not a shadow-including inclusive ancestor of B.
if (a_root.is_shadow_including_inclusive_ancestor_of(b))
return false;
// - A’s root is a shadow root whose mode is "closed" or A’s root’s host is closed-shadow-hidden from B.
if (a_root.is_shadow_root() && static_cast<ShadowRoot const&>(a_root).mode() == Bindings::ShadowRootMode::Closed)
return true;
if (a_root.is_document_fragment() && static_cast<DocumentFragment const&>(a_root).host()->is_closed_shadow_hidden_from(b))
return true;
return false;
}
// https://html.spec.whatwg.org/multipage/infrastructure.html#browsing-context-connected
bool Node::is_browsing_context_connected() const
{
// A node is browsing-context connected when it is connected and its shadow-including root's browsing context is non-null.
return is_connected() && shadow_including_root().document().browsing_context();
}
// https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
WebIDL::ExceptionOr<void> Node::ensure_pre_insert_validity(JS::Realm& realm, GC::Ref<Node> node, GC::Ptr<Node> child, ChildrenToExclude children_to_exclude) const
{
// 1. If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
return WebIDL::HierarchyRequestError::create(realm, "Can only insert into a document, document fragment or element"_utf16);
// 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
if (node->is_host_including_inclusive_ancestor_of(*this))
return WebIDL::HierarchyRequestError::create(realm, "New node is an ancestor of this node"_utf16);
// 3. If child is non-null and its parent is not parent, then throw a "NotFoundError" DOMException.
if (child && child->parent() != this)
return WebIDL::NotFoundError::create(realm, "This node is not the parent of the given child"_utf16);
// FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
// 4. If node is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<CharacterData>(*node))
return WebIDL::HierarchyRequestError::create(realm, "Invalid node type for insertion"_utf16);
auto children_to_exclude_contains = [&](Node const& candidate) {
switch (children_to_exclude) {
case ChildrenToExclude::None:
return false;
case ChildrenToExclude::Child:
return child.ptr() == &candidate;
case ChildrenToExclude::AllChildren:
return candidate.parent() == this;
}
VERIFY_NOT_REACHED();
};
auto has_element_child_not_excluded = [&] {
bool has_element_child = false;
for_each_child([&](auto const& child) {
if (is<Element>(child) && !children_to_exclude_contains(child)) {
has_element_child = true;
return IterationDecision::Break;
}
return IterationDecision::Continue;
});
return has_element_child;
};
auto has_doctype_child_not_excluded = [&] {
bool has_doctype_child = false;
for_each_child([&](auto const& child) {
if (is<DocumentType>(child) && !children_to_exclude_contains(child)) {
has_doctype_child = true;
return IterationDecision::Break;
}
return IterationDecision::Continue;
});
return has_doctype_child;
};
// 5. If parent is not a document:
if (!is<Document>(*this)) {
// 1. If node is a doctype, then throw a "HierarchyRequestError" DOMException.
if (is<DocumentType>(*node))
return WebIDL::HierarchyRequestError::create(realm, "Invalid node type for insertion"_utf16);
// 2. Return.
return {};
}
// 6. If node is a Text node, then throw a "HierarchyRequestError" DOMException.
if (is<Text>(*node))
return WebIDL::HierarchyRequestError::create(realm, "Invalid node type for insertion"_utf16);
// 7. If node is a CharacterData node, then return.
if (is<CharacterData>(*node))
return {};
// 8. If node is a DocumentFragment node:
if (auto const* document_fragment = as_if<DocumentFragment>(*node)) {
// 1. If node has more than one element child or has a Text node child, then throw a "HierarchyRequestError" DOMException.
auto node_element_child_count = document_fragment->child_element_count();
if (node_element_child_count > 1 || node->has_child_of_type<Text>())
return WebIDL::HierarchyRequestError::create(realm, "Invalid node type for insertion"_utf16);
// 2. If node has no element child, then return.
if (node_element_child_count == 0)
return {};
}
// 9. If node is a DocumentFragment or Element node:
if (is<DocumentFragment>(*node) || is<Element>(*node)) {
// 1. If any of the following are true:
// * parent has an element child that childrenToExclude does not contain;
// * child is non-null and a doctype is following child; or
// * child is a doctype that childrenToExclude does not contain,
// then throw a "HierarchyRequestError" DOMException.
if (has_element_child_not_excluded()
|| (child && child->has_following_node_of_type_in_tree_order<DocumentType>())
|| (is<DocumentType>(child.ptr()) && !children_to_exclude_contains(*child))) {
return WebIDL::HierarchyRequestError::create(realm, "Invalid node type for insertion"_utf16);
}
// 2. Return.
return {};
}
// 10. Assert: node is a doctype.
VERIFY(is<DocumentType>(*node));
// 11. If any of the following are true:
// * parent has a doctype child that childrenToExclude does not contain;
// * child is non-null and an element is preceding child; or
// * child is null and parent has an element child that childrenToExclude does not contain,
// then throw a "HierarchyRequestError" DOMException.
if (has_doctype_child_not_excluded()
|| (child && child->has_preceding_node_of_type_in_tree_order<Element>())
|| (!child && has_element_child_not_excluded())) {
return WebIDL::HierarchyRequestError::create(realm, "Invalid node type for insertion"_utf16);
}
return {};
}
// https://dom.spec.whatwg.org/#concept-node-insert
void Node::insert_before(GC::Ref<Node> node, GC::Ptr<Node> child, bool suppress_observers)
{
// 1. Let nodes be node’s children, if node is a DocumentFragment node; otherwise « node ».
Vector<GC::Root<Node>> nodes;
if (is<DocumentFragment>(*node))
nodes = node->children_as_vector();
else
nodes.append(GC::make_root(*node));
// 2. Let count be nodes’s size.
auto count = nodes.size();
// 3. If count is 0, then return.
if (count == 0)
return;
// 4. If node is a DocumentFragment node:
if (is<DocumentFragment>(*node)) {
// 1. Remove its children with suppressObservers set to true.
node->remove_all_children(true);
// 2. Queue a tree mutation record for node with « », nodes, null, and null.
// NOTE: This step intentionally does not pay attention to suppressObservers.
node->queue_tree_mutation_record({}, nodes, nullptr, nullptr);
}
// 5. If child is non-null:
if (child) {
// 1. For each live range whose start node is parent and start offset is greater than child’s index:
// increase its start offset by count.
for (auto& range : Range::live_ranges()) {
if (range->start_container() == this && range->start_offset() > child->index())
range->increase_start_offset(count);
}
// 2. For each live range whose end node is parent and end offset is greater than child’s index:
// increase its end offset by count.
for (auto& range : Range::live_ranges()) {
if (range->end_container() == this && range->end_offset() > child->index())
range->increase_end_offset(count);
}
}
// 6. Let previousSibling be child’s previous sibling or parent’s last child if child is null.
GC::Ptr<Node> previous_sibling;
if (child)
previous_sibling = child->previous_sibling();
else
previous_sibling = last_child();
// 7. For each node in nodes, in tree order:
// FIXME: In tree order
for (auto& node_to_insert : nodes) {
// 1. Adopt node into parent’s node document.
document().adopt_node(*node_to_insert);
// 2. If child is null, then append node to parent’s children.
if (!child)
append_child_impl(*node_to_insert);
// 3. Otherwise, insert node into parent’s children before child’s index.
else
insert_before_impl(*node_to_insert, child);
// 4. If parent is a shadow host whose shadow root’s slot assignment is "named" and node is a slottable, then
// assign a slot for node.
if (auto* element = as_if<DOM::Element>(*this)) {
auto is_named_shadow_host = element->is_shadow_host()
&& element->shadow_root()->slot_assignment() == Bindings::SlotAssignmentMode::Named;
if (is_named_shadow_host && node_to_insert->is_slottable())
assign_a_slot(node_to_insert->as_slottable());
}
// 5. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run
// signal a slot change for parent.
if (auto* this_slot_element = as_if<HTML::HTMLSlotElement>(*this); this_slot_element && root().is_shadow_root()) {
if (this_slot_element->assigned_nodes_internal().is_empty())
signal_a_slot_change(*this_slot_element);
}
// AD-HOC: Register any slot elements in the inserted subtree with the shadow root’s slot registry
// before running assign_slottables_for_a_tree, so the registry is up-to-date.
if (auto* shadow_root = as_if<ShadowRoot>(node_to_insert->root())) {
node_to_insert->for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](auto& slot) {
shadow_root->register_slot(slot);
return TraversalDecision::Continue;
});
}
// 6. Run assign slottables for a tree with node’s root.
assign_slottables_for_a_tree(node_to_insert->root());
node_to_insert->invalidate_style(StyleInvalidationReason::NodeInsertBefore);
// 7. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
node_to_insert->for_each_shadow_including_inclusive_descendant([&](Node& inclusive_descendant) {
// 1. Run the insertion steps with inclusiveDescendant.
inclusive_descendant.inserted();
// 2. If inclusiveDescendant is not connected, then continue.
if (!inclusive_descendant.is_connected())
return TraversalDecision::Continue;
// 3. If inclusiveDescendant is an element and inclusiveDescendant’s custom element registry is non-null:
if (auto* element = as_if<Element>(inclusive_descendant); element && element->custom_element_registry()) {
// 1. If inclusiveDescendant’s custom element registry’s is scoped is true, then append
// inclusiveDescendant’s node document to inclusiveDescendant’s custom element registry’s scoped
// document set.
if (element->custom_element_registry()->is_scoped())
element->custom_element_registry()->append_scoped_document(element->document());
// 2. If inclusiveDescendant is custom, then enqueue a custom element callback reaction with
// inclusiveDescendant, callback name "connectedCallback", and « ».
if (element->is_custom()) {
GC::RootVector<JS::Value> empty_arguments;
element->enqueue_a_custom_element_callback_reaction(HTML::CustomElementReactionNames::connectedCallback, move(empty_arguments));
}
// 3. Otherwise, try to upgrade inclusiveDescendant.
else {
element->try_to_upgrade();
}
}
// 4. Otherwise, if inclusiveDescendant is a shadow root, inclusiveDescendant’s custom element registry is
// non-null, and inclusiveDescendant’s custom element registry’s is scoped is true, then append
// inclusiveDescendant’s node document to inclusiveDescendant’s custom element registry’s scoped
// document set.
else if (auto* shadow_root = as_if<ShadowRoot>(inclusive_descendant);
shadow_root && shadow_root->custom_element_registry() && shadow_root->custom_element_registry()->is_scoped()) {
shadow_root->custom_element_registry()->append_scoped_document(shadow_root->document());
}
return TraversalDecision::Continue;
});
}
// 8. If suppressObservers is false, then queue a tree mutation record for parent with nodes, « », previousSibling,
// and child.
if (!suppress_observers) {
queue_tree_mutation_record(nodes, {}, previous_sibling.ptr(), child.ptr());
}
// 9. Run the children changed steps for parent.
ChildrenChangedMetadata metadata { ChildrenChangedMetadata::Type::Inserted, node };
children_changed(metadata);
// 10. Let staticNodeList be a list of nodes, initially « ».
// NOTE: We collect all nodes before calling the post-connection steps on any one of them, instead of calling the
// post-connection steps while we’re traversing the node tree. This is because the post-connection steps can
// modify the tree’s structure, making live traversal unsafe, possibly leading to the post-connection steps
// being called multiple times on the same node.
GC::RootVector<GC::Ref<Node>> static_node_list;
// 11. For each node of nodes, in tree order:
for (auto& node : nodes) {
// 1. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree
// order: append inclusiveDescendant to staticNodeList.
node->for_each_shadow_including_inclusive_descendant([&static_node_list](Node& inclusive_descendant) {
static_node_list.append(inclusive_descendant);
return TraversalDecision::Continue;
});
}
// 12. For each node of staticNodeList: if node is connected, then run the post-connection steps with node.
for (auto& node : static_node_list) {
if (node->is_connected())
node->post_connection();
}
if (is_connected()) {
// NB: Called during DOM insertion, layout is not up to date.
if (auto* element = as_if<Element>(*this); element && element->computed_properties() && element->computed_properties()->display().is_contents() && parent_element()) {
parent_element()->set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::NodeInsertBeforeWithDisplayContents);
}
set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::NodeInsertBefore);
}
// AD-HOC: invalidate the ordinal of the first list_item of the list_owner of the child node, if any.
if (child && child->is_element())
static_cast<Element*>(child.ptr())->maybe_invalidate_ordinals_for_list_owner();
else if (this->is_element() && !this->is_html_ol_ul_menu_element())
static_cast<Element*>(this)->maybe_invalidate_ordinals_for_list_owner();
// NOTE: If the child node is null and the parent node is an ol, ul or menu element then:
// the new node will be the first in the list of a potential list owner and it will not have
// an ordinal value (default from constructor).
// FIXME: This will not work if the child or the parent is not an element. Is insert_before even possible in this situation?
document().bump_dom_tree_version();
}
// https://dom.spec.whatwg.org/#concept-node-pre-insert
WebIDL::ExceptionOr<GC::Ref<Node>> Node::pre_insert(GC::Ref<Node> node, GC::Ptr<Node> child)
{
// 1. Ensure pre-insert validity given node, parent, child, and « ».
TRY(ensure_pre_insert_validity(realm(), node, child, ChildrenToExclude::None));
// 2. Let referenceChild be child.
auto reference_child = child;
// 3. If referenceChild is node, then set referenceChild to node’s next sibling.
if (reference_child == node)
reference_child = node->next_sibling();
// 4. Insert node into parent before referenceChild.
insert_before(node, reference_child);
// 5. Return node.
return node;
}
// https://dom.spec.whatwg.org/#dom-node-removechild
WebIDL::ExceptionOr<GC::Ref<Node>> Node::remove_child(GC::Ref<Node> child)
{
// The removeChild(child) method steps are to return the result of pre-removing child from this.
return pre_remove(child);
}
// https://dom.spec.whatwg.org/#concept-node-pre-remove
WebIDL::ExceptionOr<GC::Ref<Node>> Node::pre_remove(GC::Ref<Node> child)
{
// 1. If child’s parent is not parent, then throw a "NotFoundError" DOMException.
if (child->parent() != this)
return WebIDL::NotFoundError::create(realm(), "Child does not belong to this node"_utf16);
// 2. Remove child.
child->remove();
// 3. Return child.
return child;
}
// https://dom.spec.whatwg.org/#concept-node-append
WebIDL::ExceptionOr<GC::Ref<Node>> Node::append_child(GC::Ref<Node> node)
{
// To append a node node to a node parent: pre-insert node into parent before null.
return pre_insert(node, nullptr);
}
// https://dom.spec.whatwg.org/#live-range-pre-remove-steps
void Node::live_range_pre_remove()
{
// 1. Let parent be node’s parent.
auto* parent = this->parent();
// 2. Assert: parent is not null.
VERIFY(parent);
// 3. Let index be node’s index.
auto index = this->index();
// 4. For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
for (auto* range : Range::live_ranges()) {
if (range->start_container()->is_inclusive_descendant_of(*this))
MUST(range->set_start(*parent, index));
}
// 5. For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
for (auto* range : Range::live_ranges()) {
if (range->end_container()->is_inclusive_descendant_of(*this))
MUST(range->set_end(*parent, index));
}
// 6. For each live range whose start node is parent and start offset is greater than index, decrease its start
// offset by 1.
for (auto* range : Range::live_ranges()) {
if (range->start_container() == parent && range->start_offset() > index)
range->decrease_start_offset(1);
}
// 7. For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
for (auto* range : Range::live_ranges()) {
if (range->end_container() == parent && range->end_offset() > index)
range->decrease_end_offset(1);
}
}
// https://dom.spec.whatwg.org/#concept-node-remove
void Node::remove(bool suppress_observers)
{
// 1. Let parent be node’s parent
auto* parent = this->parent();
// 2. Assert: parent is non-null.
VERIFY(parent);
// 3. Run the live range pre-remove steps, given node.
live_range_pre_remove();
// 4. For each NodeIterator object iterator whose root’s node document is node’s node document:
// run the NodeIterator pre-removing steps given node and iterator.
document().for_each_node_iterator([&](NodeIterator& node_iterator) {
node_iterator.run_pre_removing_steps(*this);
});
// 5. Let oldPreviousSibling be node’s previous sibling.
GC::Ptr<Node> old_previous_sibling = previous_sibling();
// 6. Let oldNextSibling be node’s next sibling.
GC::Ptr<Node> old_next_sibling = next_sibling();
// AD-HOC: invalidate the ordinal of the first list_item of the list_owner of the removed node, if any.
if (is_element()) {
auto* this_element = static_cast<Element*>(this);
this_element->maybe_invalidate_ordinals_for_list_owner(this_element);
}
if (is_connected()) {
// Since the tree structure is about to change, we need to invalidate both style and layout.
// In the future, we should find a way to only invalidate the parts that actually need it.
invalidate_style(StyleInvalidationReason::NodeRemove);
// NOTE: If we didn’t have a layout node before, rebuilding the layout tree isn’t gonna give us one
// after we’ve been removed from the DOM.
// NB: Called during DOM removal, layout is not up to date.
if (unsafe_layout_node())
parent->set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::NodeRemove);
}
// 7. Remove node from its parent’s children.
parent->remove_child_impl(*this);
// 8. If node is assigned, then run assign slottables for node’s assigned slot.
if (auto assigned_slot = assigned_slot_for_node(*this))
assign_slottables(*assigned_slot);
auto& parent_root = parent->root();
// 9. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run
// signal a slot change for parent.
if (auto* parent_slot_element = as_if<HTML::HTMLSlotElement>(parent); parent_slot_element && parent_root.is_shadow_root()) {
if (parent_slot_element->assigned_nodes_internal().is_empty())
signal_a_slot_change(*parent_slot_element);
}
// 10. If node has an inclusive descendant that is a slot, then:
auto has_descendent_slot = false;
auto* shadow_root = as_if<ShadowRoot>(parent_root);
for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](auto& slot) {
has_descendent_slot = true;
if (!shadow_root)
return TraversalDecision::Break;
// AD-HOC: Unregister slot from the shadow root's registry before assign_slottables_for_a_tree.
shadow_root->unregister_slot(slot);
return TraversalDecision::Continue;
});
if (has_descendent_slot) {
// 1. Run assign slottables for a tree with parent’s root.