forked from LadybirdBrowser/ladybird
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathElement.cpp
3766 lines (3121 loc) · 170 KB
/
Element.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) 2018-2024, Andreas Kling <[email protected]>
* Copyright (c) 2022-2023, San Atkins <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/AnyOf.h>
#include <AK/Debug.h>
#include <AK/StringBuilder.h>
#include <LibUnicode/CharacterTypes.h>
#include <LibUnicode/Locale.h>
#include <LibWeb/Animations/Animation.h>
#include <LibWeb/Bindings/ElementPrototype.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/ComputedProperties.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/SelectorEngine.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleValues/CSSKeywordValue.h>
#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
#include <LibWeb/DOM/Attr.h>
#include <LibWeb/DOM/DOMTokenList.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/ElementFactory.h>
#include <LibWeb/DOM/HTMLCollection.h>
#include <LibWeb/DOM/NamedNodeMap.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/DOM/Text.h>
#include <LibWeb/Geometry/DOMRect.h>
#include <LibWeb/Geometry/DOMRectList.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>
#include <LibWeb/HTML/CustomElements/CustomElementName.h>
#include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
#include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/HTMLAnchorElement.h>
#include <LibWeb/HTML/HTMLAreaElement.h>
#include <LibWeb/HTML/HTMLBodyElement.h>
#include <LibWeb/HTML/HTMLButtonElement.h>
#include <LibWeb/HTML/HTMLFieldSetElement.h>
#include <LibWeb/HTML/HTMLFrameSetElement.h>
#include <LibWeb/HTML/HTMLHtmlElement.h>
#include <LibWeb/HTML/HTMLInputElement.h>
#include <LibWeb/HTML/HTMLLIElement.h>
#include <LibWeb/HTML/HTMLMenuElement.h>
#include <LibWeb/HTML/HTMLOListElement.h>
#include <LibWeb/HTML/HTMLOptGroupElement.h>
#include <LibWeb/HTML/HTMLOptionElement.h>
#include <LibWeb/HTML/HTMLSelectElement.h>
#include <LibWeb/HTML/HTMLSlotElement.h>
#include <LibWeb/HTML/HTMLStyleElement.h>
#include <LibWeb/HTML/HTMLTableElement.h>
#include <LibWeb/HTML/HTMLTemplateElement.h>
#include <LibWeb/HTML/HTMLTextAreaElement.h>
#include <LibWeb/HTML/HTMLUListElement.h>
#include <LibWeb/HTML/Numbers.h>
#include <LibWeb/HTML/Parser/HTMLParser.h>
#include <LibWeb/HTML/Scripting/Agent.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/TraversableNavigable.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Infra/CharacterTypes.h>
#include <LibWeb/Infra/Strings.h>
#include <LibWeb/Layout/BlockContainer.h>
#include <LibWeb/Layout/InlineNode.h>
#include <LibWeb/Layout/ListItemBox.h>
#include <LibWeb/Layout/TreeBuilder.h>
#include <LibWeb/Layout/Viewport.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Painting/PaintableBox.h>
#include <LibWeb/Painting/ViewportPaintable.h>
#include <LibWeb/SVG/SVGAElement.h>
#include <LibWeb/Selection/Selection.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::DOM {
Element::Element(Document& document, DOM::QualifiedName qualified_name)
: ParentNode(document, NodeType::ELEMENT_NODE)
, m_qualified_name(move(qualified_name))
{
make_html_uppercased_qualified_name();
}
Element::~Element() = default;
void Element::initialize(JS::Realm& realm)
{
Base::initialize(realm);
WEB_SET_PROTOTYPE_FOR_INTERFACE(Element);
m_attributes = NamedNodeMap::create(*this);
}
void Element::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
SlottableMixin::visit_edges(visitor);
Animatable::visit_edges(visitor);
visitor.visit(m_aria_active_descendant_element);
visitor.visit(m_attributes);
visitor.visit(m_inline_style);
visitor.visit(m_class_list);
visitor.visit(m_shadow_root);
visitor.visit(m_custom_element_definition);
visitor.visit(m_cascaded_properties);
visitor.visit(m_computed_properties);
if (m_pseudo_element_data) {
for (auto& pseudo_element : *m_pseudo_element_data) {
visitor.visit(pseudo_element.cascaded_properties);
visitor.visit(pseudo_element.computed_properties);
visitor.visit(pseudo_element.layout_node);
}
}
if (m_registered_intersection_observers) {
for (auto& registered_intersection_observers : *m_registered_intersection_observers)
visitor.visit(registered_intersection_observers.observer);
}
}
// https://dom.spec.whatwg.org/#dom-element-getattribute
Optional<String> Element::get_attribute(FlyString const& name) const
{
// 1. Let attr be the result of getting an attribute given qualifiedName and this.
auto const* attribute = m_attributes->get_attribute(name);
// 2. If attr is null, return null.
if (!attribute)
return {};
// 3. Return attr’s value.
return attribute->value();
}
// https://dom.spec.whatwg.org/#dom-element-getattributens
Optional<String> Element::get_attribute_ns(Optional<FlyString> const& namespace_, FlyString const& name) const
{
// 1. Let attr be the result of getting an attribute given namespace, localName, and this.
auto const* attribute = m_attributes->get_attribute_ns(namespace_, name);
// 2. If attr is null, return null.
if (!attribute)
return {};
// 3. Return attr’s value.
return attribute->value();
}
// https://dom.spec.whatwg.org/#concept-element-attributes-get-value
String Element::get_attribute_value(FlyString const& local_name, Optional<FlyString> const& namespace_) const
{
// 1. Let attr be the result of getting an attribute given namespace, localName, and element.
auto const* attribute = m_attributes->get_attribute_ns(namespace_, local_name);
// 2. If attr is null, then return the empty string.
if (!attribute)
return String {};
// 3. Return attr’s value.
return attribute->value();
}
// https://dom.spec.whatwg.org/#dom-element-getattributenode
GC::Ptr<Attr> Element::get_attribute_node(FlyString const& name) const
{
// The getAttributeNode(qualifiedName) method steps are to return the result of getting an attribute given qualifiedName and this.
return m_attributes->get_attribute(name);
}
// https://dom.spec.whatwg.org/#dom-element-getattributenodens
GC::Ptr<Attr> Element::get_attribute_node_ns(Optional<FlyString> const& namespace_, FlyString const& name) const
{
// The getAttributeNodeNS(namespace, localName) method steps are to return the result of getting an attribute given namespace, localName, and this.
return m_attributes->get_attribute_ns(namespace_, name);
}
// https://dom.spec.whatwg.org/#dom-element-setattribute
WebIDL::ExceptionOr<void> Element::set_attribute(FlyString const& name, String const& value)
{
// 1. If qualifiedName does not match the Name production in XML, then throw an "InvalidCharacterError" DOMException.
if (!Document::is_valid_name(name.to_string()))
return WebIDL::InvalidCharacterError::create(realm(), "Attribute name must not be empty or contain invalid characters"_string);
// 2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.
bool insert_as_lowercase = namespace_uri() == Namespace::HTML && document().document_type() == Document::Type::HTML;
// 3. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.
auto* attribute = m_attributes->get_attribute(name);
// 4. If attribute is null, create an attribute whose local name is qualifiedName, value is value, and node document
// is this’s node document, then append this attribute to this, and then return.
if (!attribute) {
auto new_attribute = Attr::create(document(), insert_as_lowercase ? name.to_ascii_lowercase() : name, value);
m_attributes->append_attribute(new_attribute);
return {};
}
// 5. Change attribute to value.
attribute->change_attribute(value);
return {};
}
// https://dom.spec.whatwg.org/#validate-and-extract
WebIDL::ExceptionOr<QualifiedName> validate_and_extract(JS::Realm& realm, Optional<FlyString> namespace_, FlyString const& qualified_name)
{
// To validate and extract a namespace and qualifiedName, run these steps:
// 1. If namespace is the empty string, then set it to null.
if (namespace_.has_value() && namespace_.value().is_empty())
namespace_ = {};
// 2. Validate qualifiedName.
TRY(Document::validate_qualified_name(realm, qualified_name));
// 3. Let prefix be null.
Optional<FlyString> prefix = {};
// 4. Let localName be qualifiedName.
auto local_name = qualified_name;
// 5. If qualifiedName contains a U+003A (:):
if (qualified_name.bytes_as_string_view().contains(':')) {
// 1. Let splitResult be the result of running strictly split given qualifiedName and U+003A (:).
// FIXME: Use the "strictly split" algorithm
auto split_result = qualified_name.bytes_as_string_view().split_view(':');
// 2. Set prefix to splitResult[0].
prefix = MUST(FlyString::from_utf8(split_result[0]));
// 3. Set localName to splitResult[1].
local_name = MUST(FlyString::from_utf8(split_result[1]));
}
// 6. If prefix is non-null and namespace is null, then throw a "NamespaceError" DOMException.
if (prefix.has_value() && !namespace_.has_value())
return WebIDL::NamespaceError::create(realm, "Prefix is non-null and namespace is null."_string);
// 7. If prefix is "xml" and namespace is not the XML namespace, then throw a "NamespaceError" DOMException.
if (prefix == "xml"sv && namespace_ != Namespace::XML)
return WebIDL::NamespaceError::create(realm, "Prefix is 'xml' and namespace is not the XML namespace."_string);
// 8. If either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace, then throw a "NamespaceError" DOMException.
if ((qualified_name == "xmlns"sv || prefix == "xmlns"sv) && namespace_ != Namespace::XMLNS)
return WebIDL::NamespaceError::create(realm, "Either qualifiedName or prefix is 'xmlns' and namespace is not the XMLNS namespace."_string);
// 9. If namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns", then throw a "NamespaceError" DOMException.
if (namespace_ == Namespace::XMLNS && !(qualified_name == "xmlns"sv || prefix == "xmlns"sv))
return WebIDL::NamespaceError::create(realm, "Namespace is the XMLNS namespace and neither qualifiedName nor prefix is 'xmlns'."_string);
// 10. Return namespace, prefix, and localName.
return QualifiedName { local_name, prefix, namespace_ };
}
// https://dom.spec.whatwg.org/#dom-element-setattributens
WebIDL::ExceptionOr<void> Element::set_attribute_ns(Optional<FlyString> const& namespace_, FlyString const& qualified_name, String const& value)
{
// 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
auto extracted_qualified_name = TRY(validate_and_extract(realm(), namespace_, qualified_name));
// 2. Set an attribute value for this using localName, value, and also prefix and namespace.
set_attribute_value(extracted_qualified_name.local_name(), value, extracted_qualified_name.prefix(), extracted_qualified_name.namespace_());
return {};
}
// https://dom.spec.whatwg.org/#concept-element-attributes-append
void Element::append_attribute(FlyString const& name, String const& value)
{
m_attributes->append_attribute(Attr::create(document(), name, value));
}
// https://dom.spec.whatwg.org/#concept-element-attributes-append
void Element::append_attribute(Attr& attribute)
{
m_attributes->append_attribute(attribute);
}
// https://dom.spec.whatwg.org/#concept-element-attributes-set-value
void Element::set_attribute_value(FlyString const& local_name, String const& value, Optional<FlyString> const& prefix, Optional<FlyString> const& namespace_)
{
// 1. Let attribute be the result of getting an attribute given namespace, localName, and element.
auto* attribute = m_attributes->get_attribute_ns(namespace_, local_name);
// 2. If attribute is null, create an attribute whose namespace is namespace, namespace prefix is prefix, local name
// is localName, value is value, and node document is element’s node document, then append this attribute to element,
// and then return.
if (!attribute) {
QualifiedName name { local_name, prefix, namespace_ };
auto new_attribute = Attr::create(document(), move(name), value);
m_attributes->append_attribute(new_attribute);
return;
}
// 3. Change attribute to value.
attribute->change_attribute(value);
}
// https://dom.spec.whatwg.org/#dom-element-setattributenode
WebIDL::ExceptionOr<GC::Ptr<Attr>> Element::set_attribute_node(Attr& attr)
{
// The setAttributeNode(attr) and setAttributeNodeNS(attr) methods steps are to return the result of setting an attribute given attr and this.
return m_attributes->set_attribute(attr);
}
// https://dom.spec.whatwg.org/#dom-element-setattributenodens
WebIDL::ExceptionOr<GC::Ptr<Attr>> Element::set_attribute_node_ns(Attr& attr)
{
// The setAttributeNode(attr) and setAttributeNodeNS(attr) methods steps are to return the result of setting an attribute given attr and this.
return m_attributes->set_attribute(attr);
}
// https://dom.spec.whatwg.org/#dom-element-removeattribute
void Element::remove_attribute(FlyString const& name)
{
// The removeAttribute(qualifiedName) method steps are to remove an attribute given qualifiedName and this, and then return undefined.
m_attributes->remove_attribute(name);
}
// https://dom.spec.whatwg.org/#dom-element-removeattributens
void Element::remove_attribute_ns(Optional<FlyString> const& namespace_, FlyString const& name)
{
// The removeAttributeNS(namespace, localName) method steps are to remove an attribute given namespace, localName, and this, and then return undefined.
m_attributes->remove_attribute_ns(namespace_, name);
}
// https://dom.spec.whatwg.org/#dom-element-removeattributenode
WebIDL::ExceptionOr<GC::Ref<Attr>> Element::remove_attribute_node(GC::Ref<Attr> attr)
{
return m_attributes->remove_attribute_node(attr);
}
// https://dom.spec.whatwg.org/#dom-element-hasattribute
bool Element::has_attribute(FlyString const& name) const
{
return m_attributes->get_attribute(name) != nullptr;
}
// https://dom.spec.whatwg.org/#dom-element-hasattributens
bool Element::has_attribute_ns(Optional<FlyString> const& namespace_, FlyString const& name) const
{
// 1. If namespace is the empty string, then set it to null.
// 2. Return true if this has an attribute whose namespace is namespace and local name is localName; otherwise false.
if (namespace_ == FlyString {})
return m_attributes->get_attribute_ns(OptionalNone {}, name) != nullptr;
return m_attributes->get_attribute_ns(namespace_, name) != nullptr;
}
// https://dom.spec.whatwg.org/#dom-element-toggleattribute
WebIDL::ExceptionOr<bool> Element::toggle_attribute(FlyString const& name, Optional<bool> force)
{
// 1. If qualifiedName does not match the Name production in XML, then throw an "InvalidCharacterError" DOMException.
if (!Document::is_valid_name(name.to_string()))
return WebIDL::InvalidCharacterError::create(realm(), "Attribute name must not be empty or contain invalid characters"_string);
// 2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.
bool insert_as_lowercase = namespace_uri() == Namespace::HTML && document().document_type() == Document::Type::HTML;
// 3. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.
auto* attribute = m_attributes->get_attribute(name);
// 4. If attribute is null, then:
if (!attribute) {
// 1. If force is not given or is true, create an attribute whose local name is qualifiedName, value is the empty
// string, and node document is this’s node document, then append this attribute to this, and then return true.
if (!force.has_value() || force.value()) {
auto new_attribute = Attr::create(document(), insert_as_lowercase ? name.to_ascii_lowercase() : name.to_string(), String {});
m_attributes->append_attribute(new_attribute);
return true;
}
// 2. Return false.
return false;
}
// 5. Otherwise, if force is not given or is false, remove an attribute given qualifiedName and this, and then return false.
if (!force.has_value() || !force.value()) {
m_attributes->remove_attribute(name);
return false;
}
// 6. Return true.
return true;
}
// https://dom.spec.whatwg.org/#dom-element-getattributenames
Vector<String> Element::get_attribute_names() const
{
// The getAttributeNames() method steps are to return the qualified names of the attributes in this’s attribute list, in order; otherwise a new list.
Vector<String> names;
for (size_t i = 0; i < m_attributes->length(); ++i) {
auto const* attribute = m_attributes->item(i);
names.append(attribute->name().to_string());
}
return names;
}
GC::Ptr<Layout::Node> Element::create_layout_node(GC::Ref<CSS::ComputedProperties> style)
{
if (local_name() == "noscript" && document().is_scripting_enabled())
return nullptr;
auto display = style->display();
return create_layout_node_for_display_type(document(), display, style, this);
}
GC::Ptr<Layout::NodeWithStyle> Element::create_layout_node_for_display_type(DOM::Document& document, CSS::Display const& display, GC::Ref<CSS::ComputedProperties> style, Element* element)
{
if (display.is_table_inside() || display.is_table_row_group() || display.is_table_header_group() || display.is_table_footer_group() || display.is_table_row())
return document.heap().allocate<Layout::Box>(document, element, move(style));
if (display.is_list_item())
return document.heap().allocate<Layout::ListItemBox>(document, element, move(style));
if (display.is_table_cell())
return document.heap().allocate<Layout::BlockContainer>(document, element, move(style));
if (display.is_table_column() || display.is_table_column_group() || display.is_table_caption()) {
// FIXME: This is just an incorrect placeholder until we improve table layout support.
return document.heap().allocate<Layout::BlockContainer>(document, element, move(style));
}
if (display.is_math_inside()) {
// https://w3c.github.io/mathml-core/#new-display-math-value
// MathML elements with a computed display value equal to block math or inline math control box generation
// and layout according to their tag name, as described in the relevant sections.
// FIXME: Figure out what kind of node we should make for them. For now, we'll stick with a generic Box.
return document.heap().allocate<Layout::BlockContainer>(document, element, move(style));
}
if (display.is_inline_outside()) {
if (display.is_flow_root_inside())
return document.heap().allocate<Layout::BlockContainer>(document, element, move(style));
if (display.is_flow_inside())
return document.heap().allocate<Layout::InlineNode>(document, element, move(style));
if (display.is_flex_inside())
return document.heap().allocate<Layout::Box>(document, element, move(style));
if (display.is_grid_inside())
return document.heap().allocate<Layout::Box>(document, element, move(style));
dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Support display: {}", display.to_string());
return document.heap().allocate<Layout::InlineNode>(document, element, move(style));
}
if (display.is_flex_inside() || display.is_grid_inside())
return document.heap().allocate<Layout::Box>(document, element, move(style));
if (display.is_flow_inside() || display.is_flow_root_inside() || display.is_contents())
return document.heap().allocate<Layout::BlockContainer>(document, element, move(style));
dbgln("FIXME: CSS display '{}' not implemented yet.", display.to_string());
// FIXME: We don't actually support `display: block ruby`, this is just a hack to prevent a crash
if (display.is_ruby_inside())
return document.heap().allocate<Layout::BlockContainer>(document, element, move(style));
return document.heap().allocate<Layout::InlineNode>(document, element, move(style));
}
void Element::run_attribute_change_steps(FlyString const& local_name, Optional<String> const& old_value, Optional<String> const& value, Optional<FlyString> const& namespace_)
{
attribute_changed(local_name, old_value, value, namespace_);
if (old_value != value) {
invalidate_style_after_attribute_change(local_name, old_value, value);
document().bump_dom_tree_version();
}
}
static CSS::RequiredInvalidationAfterStyleChange compute_required_invalidation(CSS::ComputedProperties const& old_style, CSS::ComputedProperties const& new_style)
{
CSS::RequiredInvalidationAfterStyleChange invalidation;
if (!old_style.computed_font_list().equals(new_style.computed_font_list()))
invalidation.relayout = true;
for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
auto property_id = static_cast<CSS::PropertyID>(i);
auto old_value = old_style.maybe_null_property(property_id);
auto new_value = new_style.maybe_null_property(property_id);
if (!old_value && !new_value)
continue;
invalidation |= CSS::compute_property_invalidation(property_id, old_value, new_value);
}
return invalidation;
}
CSS::RequiredInvalidationAfterStyleChange Element::recompute_style()
{
VERIFY(parent());
m_affected_by_has_pseudo_class_in_subject_position = false;
m_affected_by_has_pseudo_class_in_non_subject_position = false;
m_affected_by_has_pseudo_class_with_relative_selector_that_has_sibling_combinator = false;
m_affected_by_direct_sibling_combinator = false;
m_affected_by_indirect_sibling_combinator = false;
m_affected_by_first_or_last_child_pseudo_class = false;
m_affected_by_nth_child_pseudo_class = false;
m_sibling_invalidation_distance = 0;
auto& style_computer = document().style_computer();
auto new_computed_properties = style_computer.compute_style(*this);
// Tables must not inherit -libweb-* values for text-align.
// FIXME: Find the spec for this.
if (is<HTML::HTMLTableElement>(*this)) {
auto text_align = new_computed_properties->text_align();
if (text_align == CSS::TextAlign::LibwebLeft || text_align == CSS::TextAlign::LibwebCenter || text_align == CSS::TextAlign::LibwebRight)
new_computed_properties->set_property(CSS::PropertyID::TextAlign, CSS::CSSKeywordValue::create(CSS::Keyword::Start));
}
bool had_list_marker = false;
CSS::RequiredInvalidationAfterStyleChange invalidation;
if (m_computed_properties) {
invalidation = compute_required_invalidation(*m_computed_properties, new_computed_properties);
had_list_marker = m_computed_properties->display().is_list_item();
} else {
invalidation = CSS::RequiredInvalidationAfterStyleChange::full();
}
auto old_display_is_none = m_computed_properties ? m_computed_properties->display().is_none() : true;
auto new_display_is_none = new_computed_properties->display().is_none();
if (!invalidation.is_none())
set_computed_properties(move(new_computed_properties));
if (old_display_is_none != new_display_is_none) {
play_or_cancel_animations_after_display_property_change();
}
// Any document change that can cause this element's style to change, could also affect its pseudo-elements.
auto recompute_pseudo_element_style = [&](CSS::Selector::PseudoElement::Type pseudo_element) {
style_computer.push_ancestor(*this);
auto pseudo_element_style = pseudo_element_computed_properties(pseudo_element);
auto new_pseudo_element_style = style_computer.compute_pseudo_element_style_if_needed(*this, pseudo_element);
// TODO: Can we be smarter about invalidation?
if (pseudo_element_style && new_pseudo_element_style) {
invalidation |= compute_required_invalidation(*pseudo_element_style, *new_pseudo_element_style);
} else if (pseudo_element_style || new_pseudo_element_style) {
invalidation = CSS::RequiredInvalidationAfterStyleChange::full();
}
set_pseudo_element_computed_properties(pseudo_element, move(new_pseudo_element_style));
style_computer.pop_ancestor(*this);
};
recompute_pseudo_element_style(CSS::Selector::PseudoElement::Type::Before);
recompute_pseudo_element_style(CSS::Selector::PseudoElement::Type::After);
if (had_list_marker || m_computed_properties->display().is_list_item())
recompute_pseudo_element_style(CSS::Selector::PseudoElement::Type::Marker);
if (invalidation.is_none())
return invalidation;
if (invalidation.repaint)
document().set_needs_to_resolve_paint_only_properties();
if (!invalidation.rebuild_layout_tree && layout_node()) {
// If we're keeping the layout tree, we can just apply the new style to the existing layout tree.
layout_node()->apply_style(*m_computed_properties);
if (invalidation.repaint && paintable())
paintable()->set_needs_display();
// Do the same for pseudo-elements.
for (auto i = 0; i < to_underlying(CSS::Selector::PseudoElement::Type::KnownPseudoElementCount); i++) {
auto pseudo_element_type = static_cast<CSS::Selector::PseudoElement::Type>(i);
auto pseudo_element = get_pseudo_element(pseudo_element_type);
if (!pseudo_element.has_value() || !pseudo_element->layout_node)
continue;
auto pseudo_element_style = pseudo_element_computed_properties(pseudo_element_type);
if (!pseudo_element_style)
continue;
if (auto* node_with_style = dynamic_cast<Layout::NodeWithStyle*>(pseudo_element->layout_node.ptr())) {
node_with_style->apply_style(*pseudo_element_style);
if (invalidation.repaint && node_with_style->first_paintable())
node_with_style->first_paintable()->set_needs_display();
}
}
}
return invalidation;
}
CSS::RequiredInvalidationAfterStyleChange Element::recompute_inherited_style()
{
auto computed_properties = this->computed_properties();
if (!m_cascaded_properties || !computed_properties || !layout_node())
return {};
CSS::RequiredInvalidationAfterStyleChange invalidation;
HashMap<size_t, RefPtr<CSS::CSSStyleValue const>> old_values_with_relative_units;
for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
auto property_id = static_cast<CSS::PropertyID>(i);
auto const& preabsolutized_value = m_cascaded_properties->property(property_id);
RefPtr old_value = computed_properties->maybe_null_property(property_id);
// Update property if it uses relative units as it might have been affected by a change in ancestor element style.
if (preabsolutized_value && preabsolutized_value->is_length() && preabsolutized_value->as_length().length().is_font_relative()) {
auto is_inherited = computed_properties->is_property_inherited(property_id);
computed_properties->set_property(property_id, *preabsolutized_value, is_inherited ? CSS::ComputedProperties::Inherited::Yes : CSS::ComputedProperties::Inherited::No);
old_values_with_relative_units.set(i, old_value);
}
if (!computed_properties->is_property_inherited(property_id))
continue;
RefPtr new_value = CSS::StyleComputer::get_inherit_value(property_id, this);
computed_properties->set_property(property_id, *new_value, CSS::ComputedProperties::Inherited::Yes);
invalidation |= CSS::compute_property_invalidation(property_id, old_value, new_value);
}
if (invalidation.is_none() && old_values_with_relative_units.is_empty())
return invalidation;
document().style_computer().compute_font(*computed_properties, this, {});
document().style_computer().absolutize_values(*computed_properties, this);
for (auto [property_id, old_value] : old_values_with_relative_units) {
auto new_value = computed_properties->maybe_null_property(static_cast<CSS::PropertyID>(property_id));
invalidation |= CSS::compute_property_invalidation(static_cast<CSS::PropertyID>(property_id), old_value, new_value);
}
if (invalidation.is_none())
return invalidation;
layout_node()->apply_style(*computed_properties);
return invalidation;
}
GC::Ref<CSS::ComputedProperties> Element::resolved_css_values(Optional<CSS::Selector::PseudoElement::Type> type)
{
auto element_computed_style = CSS::CSSStyleProperties::create_resolved_style({ *this, type });
auto properties = heap().allocate<CSS::ComputedProperties>();
for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
auto property_id = (CSS::PropertyID)i;
auto maybe_value = element_computed_style->property(property_id);
if (!maybe_value.has_value())
continue;
properties->set_property(property_id, maybe_value.release_value().value);
}
return properties;
}
void Element::reset_animated_css_properties()
{
if (!m_computed_properties)
return;
m_computed_properties->reset_animated_properties();
}
DOMTokenList* Element::class_list()
{
if (!m_class_list)
m_class_list = DOMTokenList::create(*this, HTML::AttributeNames::class_);
return m_class_list;
}
// https://dom.spec.whatwg.org/#valid-shadow-host-name
static bool is_valid_shadow_host_name(FlyString const& name)
{
// A valid shadow host name is:
// - a valid custom element name
// - "article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "main", "nav", "p", "section", or "span"
if (!HTML::is_valid_custom_element_name(name)
&& !name.is_one_of("article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "main", "nav", "p", "section", "span")) {
return false;
}
return true;
}
// https://dom.spec.whatwg.org/#concept-attach-a-shadow-root
WebIDL::ExceptionOr<void> Element::attach_a_shadow_root(Bindings::ShadowRootMode mode, bool clonable, bool serializable, bool delegates_focus, Bindings::SlotAssignmentMode slot_assignment)
{
// 1. If element’s namespace is not the HTML namespace, then throw a "NotSupportedError" DOMException.
if (namespace_uri() != Namespace::HTML)
return WebIDL::NotSupportedError::create(realm(), "Element's namespace is not the HTML namespace"_string);
// 2. If element’s local name is not a valid shadow host name, then throw a "NotSupportedError" DOMException.
if (!is_valid_shadow_host_name(local_name()))
return WebIDL::NotSupportedError::create(realm(), "Element's local name is not a valid shadow host name"_string);
// 3. If element’s local name is a valid custom element name, or element’s is value is not null, then:
if (HTML::is_valid_custom_element_name(local_name()) || m_is_value.has_value()) {
// 1. Let definition be the result of looking up a custom element definition given element’s node document, its namespace, its local name, and its is value.
auto definition = document().lookup_custom_element_definition(namespace_uri(), local_name(), m_is_value);
// 2. If definition is not null and definition’s disable shadow is true, then throw a "NotSupportedError" DOMException.
if (definition && definition->disable_shadow())
return WebIDL::NotSupportedError::create(realm(), "Cannot attach a shadow root to a custom element that has disabled shadow roots"_string);
}
// 4. If element is a shadow host, then:
if (is_shadow_host()) {
// 1. Let currentShadowRoot be element’s shadow root.
auto current_shadow_root = shadow_root();
// 2. If any of the following are true:
// - currentShadowRoot’s declarative is false; or
// - currentShadowRoot’s mode is not mode,
// then throw a "NotSupportedError" DOMException.
if (!current_shadow_root->declarative() || current_shadow_root->mode() != mode) {
return WebIDL::NotSupportedError::create(realm(), "Element already is a shadow host"_string);
}
// 3. Otherwise:
// 1. Remove all of currentShadowRoot’s children, in tree order.
current_shadow_root->remove_all_children();
// 2. Set currentShadowRoot’s declarative to false.
current_shadow_root->set_declarative(false);
// 3. Return.
return {};
}
// 5. Let shadow be a new shadow root whose node document is element’s node document, host is this, and mode is mode.
auto shadow = realm().create<ShadowRoot>(document(), *this, mode);
// 6. Set shadow’s delegates focus to delegatesFocus".
shadow->set_delegates_focus(delegates_focus);
// 7. If element’s custom element state is "precustomized" or "custom", then set shadow’s available to element internals to true.
if (m_custom_element_state == CustomElementState::Precustomized || m_custom_element_state == CustomElementState::Custom)
shadow->set_available_to_element_internals(true);
// 8. Set shadow’s slot assignment to slotAssignment.
shadow->set_slot_assignment(slot_assignment);
// 9. Set shadow’s declarative to false.
shadow->set_declarative(false);
// 10. Set shadow’s clonable to clonable.
shadow->set_clonable(clonable);
// 11. Set shadow’s serializable to serializable.
shadow->set_serializable(serializable);
// 12. Set element’s shadow root to shadow.
set_shadow_root(shadow);
return {};
}
// https://dom.spec.whatwg.org/#dom-element-attachshadow
WebIDL::ExceptionOr<GC::Ref<ShadowRoot>> Element::attach_shadow(ShadowRootInit init)
{
// 1. Run attach a shadow root with this, init["mode"], init["clonable"], init["serializable"], init["delegatesFocus"], and init["slotAssignment"].
TRY(attach_a_shadow_root(init.mode, init.clonable, init.serializable, init.delegates_focus, init.slot_assignment));
// 2. Return this’s shadow root.
return GC::Ref { *shadow_root() };
}
// https://dom.spec.whatwg.org/#dom-element-shadowroot
GC::Ptr<ShadowRoot> Element::shadow_root_for_bindings() const
{
// 1. Let shadow be this’s shadow root.
auto shadow = m_shadow_root;
// 2. If shadow is null or its mode is "closed", then return null.
if (shadow == nullptr || shadow->mode() == Bindings::ShadowRootMode::Closed)
return nullptr;
// 3. Return shadow.
return shadow;
}
// https://dom.spec.whatwg.org/#dom-element-matches
WebIDL::ExceptionOr<bool> Element::matches(StringView selectors) const
{
// 1. Let s be the result of parse a selector from selectors.
auto maybe_selectors = parse_selector(CSS::Parser::ParsingParams(document()), selectors);
// 2. If s is failure, then throw a "SyntaxError" DOMException.
if (!maybe_selectors.has_value())
return WebIDL::SyntaxError::create(realm(), "Failed to parse selector"_string);
// 3. If the result of match a selector against an element, using s, this, and scoping root this, returns success, then return true; otherwise, return false.
auto sel = maybe_selectors.value();
for (auto& s : sel) {
SelectorEngine::MatchContext context;
if (SelectorEngine::matches(s, *this, nullptr, context, {}, static_cast<ParentNode const*>(this)))
return true;
}
return false;
}
// https://dom.spec.whatwg.org/#dom-element-closest
WebIDL::ExceptionOr<DOM::Element const*> Element::closest(StringView selectors) const
{
// 1. Let s be the result of parse a selector from selectors.
auto maybe_selectors = parse_selector(CSS::Parser::ParsingParams(document()), selectors);
// 2. If s is failure, then throw a "SyntaxError" DOMException.
if (!maybe_selectors.has_value())
return WebIDL::SyntaxError::create(realm(), "Failed to parse selector"_string);
auto matches_selectors = [this](CSS::SelectorList const& selector_list, Element const* element) {
// 4. For each element in elements, if match a selector against an element, using s, element, and scoping root this, returns success, return element.
for (auto const& selector : selector_list) {
SelectorEngine::MatchContext context;
if (SelectorEngine::matches(selector, *element, nullptr, context, {}, this))
return true;
}
return false;
};
auto const selector_list = maybe_selectors.release_value();
// 3. Let elements be this’s inclusive ancestors that are elements, in reverse tree order.
for (auto* element = this; element; element = element->parent_element()) {
if (!matches_selectors(selector_list, element))
continue;
return element;
}
// 5. Return null.
return nullptr;
}
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-innerhtml
WebIDL::ExceptionOr<void> Element::set_inner_html(StringView value)
{
// FIXME: 1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, the given value, "Element innerHTML", and "script".
// 2. Let context be this.
DOM::Node* context = this;
// 3. Let fragment be the result of invoking the fragment parsing algorithm steps with context and compliantString. FIXME: Use compliantString.
auto fragment = TRY(as<Element>(*context).parse_fragment(value));
// 4. If context is a template element, then set context to the template element's template contents (a DocumentFragment).
if (is<HTML::HTMLTemplateElement>(*context))
context = as<HTML::HTMLTemplateElement>(*context).content();
// 5. Replace all with fragment within context.
context->replace_all(fragment);
// NOTE: We don't invalidate style & layout for <template> elements since they don't affect rendering.
if (!is<HTML::HTMLTemplateElement>(*context)) {
context->set_needs_style_update(true);
if (context->is_connected()) {
// NOTE: Since the DOM has changed, we have to rebuild the layout tree.
context->set_needs_layout_tree_update(true);
}
}
return {};
}
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-innerhtml
WebIDL::ExceptionOr<String> Element::inner_html() const
{
return serialize_fragment(HTML::RequireWellFormed::Yes);
}
bool Element::is_focused() const
{
return document().focused_element() == this;
}
bool Element::is_active() const
{
return document().active_element() == this;
}
bool Element::is_target() const
{
return document().target_element() == this;
}
// https://dom.spec.whatwg.org/#document-element
bool Element::is_document_element() const
{
// The document element of a document is the element whose parent is that document, if it exists; otherwise null.
return parent() == &document();
}
// https://dom.spec.whatwg.org/#element-shadow-host
bool Element::is_shadow_host() const
{
// An element is a shadow host if its shadow root is non-null.
return m_shadow_root != nullptr;
}
void Element::set_shadow_root(GC::Ptr<ShadowRoot> shadow_root)
{
if (m_shadow_root == shadow_root)
return;
if (m_shadow_root)
m_shadow_root->set_host(nullptr);
m_shadow_root = move(shadow_root);
if (m_shadow_root)
m_shadow_root->set_host(this);
invalidate_style(StyleInvalidationReason::ElementSetShadowRoot);
}
GC::Ref<CSS::CSSStyleProperties> Element::style_for_bindings()
{
if (!m_inline_style)
m_inline_style = CSS::CSSStyleProperties::create_element_inline_style({ *this }, {}, {});
return *m_inline_style;
}
// https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name
void Element::make_html_uppercased_qualified_name()
{
// This is allowed by the spec: "User agents could optimize qualified name and HTML-uppercased qualified name by storing them in internal slots."
if (namespace_uri() == Namespace::HTML && document().document_type() == Document::Type::HTML)
m_html_uppercased_qualified_name = qualified_name().to_ascii_uppercase();
else
m_html_uppercased_qualified_name = qualified_name();
}
// https://html.spec.whatwg.org/multipage/webappapis.html#queue-an-element-task
HTML::TaskID Element::queue_an_element_task(HTML::Task::Source source, Function<void()> steps)
{
return queue_a_task(source, HTML::main_thread_event_loop(), document(), GC::create_function(heap(), move(steps)));
}
// https://html.spec.whatwg.org/multipage/syntax.html#void-elements
bool Element::is_void_element() const
{
return local_name().is_one_of(HTML::TagNames::area, HTML::TagNames::base, HTML::TagNames::br, HTML::TagNames::col, HTML::TagNames::embed, HTML::TagNames::hr, HTML::TagNames::img, HTML::TagNames::input, HTML::TagNames::link, HTML::TagNames::meta, HTML::TagNames::param, HTML::TagNames::source, HTML::TagNames::track, HTML::TagNames::wbr);
}
// https://html.spec.whatwg.org/multipage/parsing.html#serializes-as-void
bool Element::serializes_as_void() const
{
return is_void_element() || local_name().is_one_of(HTML::TagNames::basefont, HTML::TagNames::bgsound, HTML::TagNames::frame, HTML::TagNames::keygen);
}
// https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
GC::Ref<Geometry::DOMRect> Element::get_bounding_client_rect() const
{
// 1. Let list be the result of invoking getClientRects() on element.
auto list = get_client_rects();
// 2. If the list is empty return a DOMRect object whose x, y, width and height members are zero.
if (list->length() == 0)
return Geometry::DOMRect::construct_impl(realm(), 0, 0, 0, 0).release_value_but_fixme_should_propagate_errors();
// 3. If all rectangles in list have zero width or height, return the first rectangle in list.
auto all_rectangle_has_zero_width_or_height = true;
for (auto i = 0u; i < list->length(); ++i) {
auto const& rect = list->item(i);
if (rect->width() != 0 && rect->height() != 0) {
all_rectangle_has_zero_width_or_height = false;
break;
}
}
if (all_rectangle_has_zero_width_or_height)
return GC::Ref { *const_cast<Geometry::DOMRect*>(list->item(0)) };
// 4. Otherwise, return a DOMRect object describing the smallest rectangle that includes all of the rectangles in
// list of which the height or width is not zero.
auto const* first_rect = list->item(0);
auto bounding_rect = Gfx::Rect { first_rect->x(), first_rect->y(), first_rect->width(), first_rect->height() };
for (auto i = 1u; i < list->length(); ++i) {
auto const& rect = list->item(i);
if (rect->width() == 0 || rect->height() == 0)
continue;
bounding_rect.unite({ rect->x(), rect->y(), rect->width(), rect->height() });
}
return Geometry::DOMRect::create(realm(), bounding_rect.to_type<float>());
}
// https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
GC::Ref<Geometry::DOMRectList> Element::get_client_rects() const
{
auto navigable = document().navigable();
if (!navigable)
return Geometry::DOMRectList::create(realm(), {});
// NOTE: Ensure that layout is up-to-date before looking at metrics.
const_cast<Document&>(document()).update_layout(UpdateLayoutReason::ElementGetClientRects);