forked from LadybirdBrowser/ladybird
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathElement.cpp
More file actions
4855 lines (4040 loc) · 223 KB
/
Element.cpp
File metadata and controls
4855 lines (4040 loc) · 223 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) 2022-2023, Sam Atkins <atkinssj@serenityos.org>
* Copyright (c) 2025, Simon Farre <simon.farre.cx@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/AnyOf.h>
#include <AK/Assertions.h>
#include <AK/Checked.h>
#include <AK/Debug.h>
#include <AK/IterationDecision.h>
#include <AK/JsonObjectSerializer.h>
#include <AK/NumericLimits.h>
#include <AK/StringBuilder.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/ImmutableBitmap.h>
#include <LibJS/Runtime/NativeFunction.h>
#include <LibURL/Parser.h>
#include <LibUnicode/CharacterTypes.h>
#include <LibUnicode/Locale.h>
#include <LibWeb/Bindings/ElementPrototype.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/CascadedProperties.h>
#include <LibWeb/CSS/ComputedProperties.h>
#include <LibWeb/CSS/CountersSet.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/StyleInvalidation.h>
#include <LibWeb/CSS/StylePropertyMap.h>
#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
#include <LibWeb/CSS/StyleValues/RandomValueSharingStyleValue.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/CustomElements/CustomStateSet.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/HTMLAnchorElement.h>
#include <LibWeb/HTML/HTMLAreaElement.h>
#include <LibWeb/HTML/HTMLBaseElement.h>
#include <LibWeb/HTML/HTMLBodyElement.h>
#include <LibWeb/HTML/HTMLButtonElement.h>
#include <LibWeb/HTML/HTMLDialogElement.h>
#include <LibWeb/HTML/HTMLFieldSetElement.h>
#include <LibWeb/HTML/HTMLFrameSetElement.h>
#include <LibWeb/HTML/HTMLHtmlElement.h>
#include <LibWeb/HTML/HTMLIFrameElement.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/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/HTMLTemplateElement.h>
#include <LibWeb/HTML/HTMLTextAreaElement.h>
#include <LibWeb/HTML/HTMLUListElement.h>
#include <LibWeb/HTML/Navigable.h>
#include <LibWeb/HTML/Numbers.h>
#include <LibWeb/HTML/Parser/HTMLParser.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/TraversableNavigable.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/XMLSerializer.h>
#include <LibWeb/Infra/CharacterTypes.h>
#include <LibWeb/Infra/Strings.h>
#include <LibWeb/IntersectionObserver/IntersectionObserver.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/MathML/MathMLElement.h>
#include <LibWeb/MathML/TagNames.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Painting/AccumulatedVisualContext.h>
#include <LibWeb/Painting/PaintableBox.h>
#include <LibWeb/Painting/StackingContext.h>
#include <LibWeb/Painting/ViewportPaintable.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/SVG/SVGAElement.h>
#include <LibWeb/Selection/Selection.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
#include <LibWeb/XML/XMLFragmentParser.h>
namespace Web::DOM {
GC_DEFINE_ALLOCATOR(Element);
Element::Element(Document& document, DOM::QualifiedName qualified_name)
: ParentNode(document, NodeType::ELEMENT_NODE)
, m_qualified_name(move(qualified_name))
{
}
Element::~Element() = default;
void Element::initialize(JS::Realm& realm)
{
WEB_SET_PROTOTYPE_FOR_INTERFACE(Element);
Base::initialize(realm);
}
void Element::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
SlottableMixin::visit_edges(visitor);
Animatable::visit_edges(visitor);
ARIAMixin::visit_edges(visitor);
visitor.visit(m_attributes);
visitor.visit(m_inline_style);
visitor.visit(m_class_list);
visitor.visit(m_shadow_root);
visitor.visit(m_part_list);
visitor.visit(m_custom_element_definition);
visitor.visit(m_custom_state_set);
visitor.visit(m_cascaded_properties);
visitor.visit(m_computed_properties);
visitor.visit(m_computed_style_map_cache);
visitor.visit(m_attribute_style_map);
if (m_pseudo_element_data) {
for (auto& pseudo_element : *m_pseudo_element_data) {
visitor.visit(pseudo_element.value);
}
}
if (m_registered_intersection_observers) {
for (auto& registered_intersection_observers : *m_registered_intersection_observers)
visitor.visit(registered_intersection_observers.observer);
}
if (m_counters_set)
m_counters_set->visit_edges(visitor);
}
// 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.
if (!m_attributes)
return {};
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.
if (!m_attributes)
return {};
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.
if (!m_attributes)
return {};
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://html.spec.whatwg.org/multipage/semantics.html#get-an-element's-target
String Element::get_an_elements_target(Optional<String> target) const
{
// To get an element's target, given an a, area, or form element element, and an optional string-or-null target (default null), run these steps:
// 1. If target is null, then:
if (!target.has_value()) {
// 1. If element has a target attribute, then set target to that attribute's value.
if (auto maybe_target = attribute(HTML::AttributeNames::target); maybe_target.has_value()) {
target = maybe_target.release_value();
}
// 2. Otherwise, if element's node document contains a base element with a target attribute,
// set target to the value of the target attribute of the first such base element.
else if (auto base_element = document().first_base_element_with_target_in_tree_order()) {
target = base_element->attribute(HTML::AttributeNames::target);
}
}
// 2. If target is not null, and contains an ASCII tab or newline and a U+003C (<), then set target to "_blank".
if (target.has_value() && target->bytes_as_string_view().contains("\t\n\r"sv) && target->contains('<'))
target = "_blank"_string;
// 3. Return target.
return target.value_or({});
}
// https://html.spec.whatwg.org/multipage/links.html#get-an-element's-noopener
HTML::TokenizedFeature::NoOpener Element::get_an_elements_noopener(URL::URL const& url, StringView target) const
{
// To get an element's noopener, given an a, area, or form element element, a URL record url, and a string target,
// perform the following steps. They return a boolean.
auto rel = MUST(get_attribute_value(HTML::AttributeNames::rel).to_lowercase());
auto link_types = rel.bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace);
// 1. If element's link types include the noopener or noreferrer keyword, then return true.
if (link_types.contains_slow("noopener"sv) || link_types.contains_slow("noreferrer"sv))
return HTML::TokenizedFeature::NoOpener::Yes;
// 2. If element's link types do not include the opener keyword and
// target is an ASCII case-insensitive match for "_blank", then return true.
if (!link_types.contains_slow("opener"sv) && target.equals_ignoring_ascii_case("_blank"sv))
return HTML::TokenizedFeature::NoOpener::Yes;
// 3. If url's blob URL entry is not null:
if (url.blob_url_entry().has_value()) {
// 1. Let blobOrigin be url's blob URL entry's environment's origin.
auto const& blob_origin = url.blob_url_entry()->environment.origin;
// 2. Let topLevelOrigin be element's relevant settings object's top-level origin.
auto const& top_level_origin = HTML::relevant_settings_object(*this).top_level_origin;
// 3. If blobOrigin is not same site with topLevelOrigin, then return true.
if (!blob_origin.is_same_site(top_level_origin.value()))
return HTML::TokenizedFeature::NoOpener::Yes;
}
// 4. Return false.
return HTML::TokenizedFeature::NoOpener::No;
}
// https://html.spec.whatwg.org/multipage/links.html#cannot-navigate
bool Element::cannot_navigate() const
{
// An element element cannot navigate if one of the following is true:
// - element's node document is not fully active
if (!document().is_fully_active())
return true;
// - element is not an a element and is not connected.
return !(is_html_anchor_element() || is_svg_a_element()) && !is_connected();
}
// https://html.spec.whatwg.org/multipage/links.html#following-hyperlinks-2
void Element::follow_the_hyperlink(Optional<String> hyperlink_suffix, HTML::UserNavigationInvolvement user_involvement)
{
// 1. If subject cannot navigate, then return.
if (cannot_navigate())
return;
// 2. Let targetAttributeValue be the empty string.
String target_attribute_value;
// 3. If subject is an a or area element, then set targetAttributeValue to the result of getting an element's target given subject.
if (is_html_anchor_element() || is_html_area_element() || is_svg_a_element())
target_attribute_value = get_an_elements_target();
// 4. Let urlRecord be the result of encoding-parsing a URL given subject's href attribute value, relative to subject's node document.
auto url_record = document().encoding_parse_url(get_attribute_value(HTML::AttributeNames::href));
// 5. If urlRecord is failure, then return.
if (!url_record.has_value())
return;
// 6. Let noopener be the result of getting an element's noopener with subject, urlRecord, and targetAttributeValue.
auto noopener = get_an_elements_noopener(*url_record, target_attribute_value);
// 7. Let targetNavigable be the first return value of applying the rules for choosing a navigable given
// targetAttributeValue, subject's node navigable, and noopener.
auto target_navigable = document().navigable()->choose_a_navigable(target_attribute_value, noopener).navigable;
// 8. If targetNavigable is null, then return.
if (!target_navigable)
return;
// 9. Let urlString be the result of applying the URL serializer to urlRecord.
auto url_string = url_record->serialize();
// 10. If hyperlinkSuffix is non-null, then append it to urlString.
if (hyperlink_suffix.has_value())
url_string = MUST(String::formatted("{}{}", url_string, *hyperlink_suffix));
// 11. Let referrerPolicy be the current state of subject's referrerpolicy content attribute.
auto referrer_policy = ReferrerPolicy::from_string(attribute(HTML::AttributeNames::referrerpolicy).value_or({})).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString);
// FIXME: 12. If subject's link types includes the noreferrer keyword, then set referrerPolicy to "no-referrer".
// 13. Navigate targetNavigable to urlString using subject's node document, with referrerPolicy set to referrerPolicy and userInvolvement set to userInvolvement.
auto url = URL::Parser::basic_parse(url_string);
VERIFY(url.has_value());
MUST(target_navigable->navigate({ .url = url.release_value(), .source_document = document(), .referrer_policy = referrer_policy, .user_involvement = user_involvement }));
}
// 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.
if (!m_attributes)
return {};
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.
if (!m_attributes)
return {};
return m_attributes->get_attribute_ns(namespace_, name);
}
// https://dom.spec.whatwg.org/#dom-element-setattribute
WebIDL::ExceptionOr<void> Element::set_attribute_for_bindings(FlyString qualified_name, Variant<GC::Root<TrustedTypes::TrustedHTML>, GC::Root<TrustedTypes::TrustedScript>, GC::Root<TrustedTypes::TrustedScriptURL>, Utf16String> const& value)
{
// 1. If qualifiedName is not a valid attribute local name, then throw an "InvalidCharacterError" DOMException.
if (!is_valid_attribute_local_name(qualified_name))
return WebIDL::InvalidCharacterError::create(realm(), "Attribute name must not be empty or contain invalid characters"_utf16);
// 2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to
// qualifiedName in ASCII lowercase.
if (namespace_uri() == Namespace::HTML && document().document_type() == Document::Type::HTML)
qualified_name = qualified_name.to_ascii_lowercase();
// 3. Let verifiedValue be the result of calling get Trusted Types-compliant attribute value
// with qualifiedName, null, this, and value.
auto const verified_value = TRY(TrustedTypes::get_trusted_types_compliant_attribute_value(qualified_name, {}, *this, value));
// 4. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.
auto* attribute = attributes()->get_attribute(qualified_name);
// 5. If attribute is non-null, then change attribute to verifiedValue and return.
if (attribute) {
attribute->change_attribute(verified_value.to_utf8_but_should_be_ported_to_utf16());
return {};
}
// 6. Set attribute to a new attribute whose local name is qualifiedName, value is verifiedValue,
// and node document is this’s node document.
attribute = Attr::create(document(), qualified_name, verified_value.to_utf8_but_should_be_ported_to_utf16());
// 7. Append attribute to this.
m_attributes->append_attribute(*attribute);
return {};
}
// https://dom.spec.whatwg.org/#dom-element-setattribute
WebIDL::ExceptionOr<void> Element::set_attribute_for_bindings(FlyString qualified_name, Variant<GC::Root<TrustedTypes::TrustedHTML>, GC::Root<TrustedTypes::TrustedScript>, GC::Root<TrustedTypes::TrustedScriptURL>, String> const& value)
{
return set_attribute_for_bindings(move(qualified_name),
value.visit(
[](auto const& trusted_type) -> Variant<GC::Root<TrustedTypes::TrustedHTML>, GC::Root<TrustedTypes::TrustedScript>, GC::Root<TrustedTypes::TrustedScriptURL>, Utf16String> { return trusted_type; },
[](String const& string) -> Variant<GC::Root<TrustedTypes::TrustedHTML>, GC::Root<TrustedTypes::TrustedScript>, GC::Root<TrustedTypes::TrustedScriptURL>, Utf16String> { return Utf16String::from_utf8(string); }));
}
// https://dom.spec.whatwg.org/#valid-namespace-prefix
bool is_valid_namespace_prefix(FlyString const& prefix)
{
// A string is a valid namespace prefix if its length is at least 1 and it does not contain ASCII whitespace, U+0000 NULL, U+002F (/), or U+003E (>).
constexpr Array<u32, 8> INVALID_NAMESPACE_PREFIX_CHARACTERS { '\t', '\n', '\f', '\r', ' ', '\0', '/', '>' };
return !prefix.is_empty() && !prefix.code_points().contains_any_of(INVALID_NAMESPACE_PREFIX_CHARACTERS);
}
// https://dom.spec.whatwg.org/#valid-attribute-local-name
bool is_valid_attribute_local_name(FlyString const& local_name)
{
// A string is a valid attribute local name if its length is at least 1 and it does not contain ASCII whitespace, U+0000 NULL, U+002F (/), U+003D (=), or U+003E (>).
constexpr Array<u32, 9> INVALID_ATTRIBUTE_LOCAL_NAME_CHARACTERS { '\t', '\n', '\f', '\r', ' ', '\0', '/', '=', '>' };
return !local_name.is_empty() && !local_name.code_points().contains_any_of(INVALID_ATTRIBUTE_LOCAL_NAME_CHARACTERS);
}
// https://dom.spec.whatwg.org/#valid-element-local-name
bool is_valid_element_local_name(FlyString const& name)
{
// 1. If name’s length is 0, then return false.
if (name.is_empty())
return false;
// 2. If name’s 0th code point is an ASCII alpha, then:
auto first_code_point = *name.code_points().begin().peek();
if (is_ascii_alpha(first_code_point)) {
// 1. If name contains ASCII whitespace, U+0000 NULL, U+002F (/), or U+003E (>), then return false.
constexpr Array<u32, 8> INVALID_CHARACTERS { '\t', '\n', '\f', '\r', ' ', '\0', '/', '>' };
if (name.code_points().contains_any_of(INVALID_CHARACTERS))
return false;
// 2. Return true.
return true;
}
// 3. If name’s 0th code point is not U+003A (:), U+005F (_), or in the range U+0080 to U+10FFFF, inclusive, then return false.
if (!first_is_one_of(first_code_point, 0x003Au, 0x005Fu) && (first_code_point < 0x0080 || first_code_point > 0x10FFFF))
return false;
// 4. If name’s subsequent code points, if any, are not ASCII alphas, ASCII digits, U+002D (-), U+002E (.), U+003A (:), U+005F (_), or in the range U+0080 to U+10FFFF, inclusive, then return false.
for (auto code_point : name.code_points().unicode_substring_view(1)) {
if (!is_ascii_alpha(code_point) && !is_ascii_digit(code_point) && !first_is_one_of(code_point, 0X002Du, 0X002Eu, 0X003Au, 0X005Fu) && (code_point < 0x0080 || code_point > 0x10FFFF))
return false;
}
// 5. Return true.
return true;
}
// https://dom.spec.whatwg.org/#validate-and-extract
WebIDL::ExceptionOr<QualifiedName> validate_and_extract(JS::Realm& realm, Optional<FlyString> namespace_, FlyString const& qualified_name, ValidationContext context)
{
// 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. Let prefix be null.
Optional<FlyString> prefix = {};
// 3. Let localName be qualifiedName.
auto local_name = qualified_name;
// 4. If qualifiedName contains a U+003A (:):
auto qualified_name_view = qualified_name.bytes_as_string_view();
auto colon_position = qualified_name_view.find(':');
if (colon_position.has_value()) {
// 1. Set prefix to the part of qualifiedName before the first U+003A (:).
prefix = MUST(FlyString::from_utf8(qualified_name_view.substring_view(0, *colon_position)));
// 2. Set localName to the part of qualifiedName after the first U+003A (:).
local_name = MUST(FlyString::from_utf8(qualified_name_view.substring_view(*colon_position + 1)));
// 3. If prefix is not a valid namespace prefix, then throw an "InvalidCharacterError" DOMException.
if (!is_valid_namespace_prefix(*prefix))
return WebIDL::InvalidCharacterError::create(realm, "Prefix not a valid namespace prefix."_utf16);
}
// 5. Assert: prefix is either null or a valid namespace prefix.
ASSERT(!prefix.has_value() || is_valid_namespace_prefix(*prefix));
// 6. If context is "attribute" and localName is not a valid attribute local name, then throw an "InvalidCharacterError" DOMException.
if (context == ValidationContext::Attribute && !is_valid_attribute_local_name(local_name))
return WebIDL::InvalidCharacterError::create(realm, "Local name not a valid attribute local name."_utf16);
// 7. If context is "element" and localName is not a valid element local name, then throw an "InvalidCharacterError" DOMException.
if (context == ValidationContext::Element && !is_valid_element_local_name(local_name))
return WebIDL::InvalidCharacterError::create(realm, "Local name not a valid element local name."_utf16);
// 8. 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."_utf16);
// 9. 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."_utf16);
// 10. 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."_utf16);
// 11. 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'."_utf16);
// 12. Return (namespace, prefix, localName).
return QualifiedName { local_name, prefix, namespace_ };
}
// https://dom.spec.whatwg.org/#dom-element-setattributens
WebIDL::ExceptionOr<void> Element::set_attribute_ns_for_bindings(Optional<FlyString> const& namespace_, FlyString const& qualified_name, Variant<GC::Root<TrustedTypes::TrustedHTML>, GC::Root<TrustedTypes::TrustedScript>, GC::Root<TrustedTypes::TrustedScriptURL>, Utf16String> const& value)
{
// 1. Let (namespace, prefix, localName) be the result of validating and extracting namespace and qualifiedName given "attribute".
auto extracted_qualified_name = TRY(validate_and_extract(realm(), namespace_, qualified_name, ValidationContext::Attribute));
// 2. Let verifiedValue be the result of calling get Trusted Types-compliant attribute value
// with localName, namespace, this, and value.
auto const verified_value = TRY(TrustedTypes::get_trusted_types_compliant_attribute_value(
extracted_qualified_name.local_name(),
extracted_qualified_name.namespace_().has_value() ? Utf16String::from_utf8(extracted_qualified_name.namespace_().value()) : Optional<Utf16String>(),
*this,
value));
// 3. Set an attribute value for this using localName, verifiedValue, and also prefix and namespace.
set_attribute_value(extracted_qualified_name.local_name(), verified_value.to_utf8_but_should_be_ported_to_utf16(), 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)
{
attributes()->append_attribute(Attr::create(document(), name, value));
}
// https://dom.spec.whatwg.org/#concept-element-attributes-append
void Element::append_attribute(Attr& attribute)
{
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 = 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_for_bindings(Attr& attr)
{
// The setAttributeNode(attr) and setAttributeNodeNS(attr) methods steps are to return the result of setting an attribute given attr and this.
return attributes()->set_attribute(attr);
}
// https://dom.spec.whatwg.org/#dom-element-setattributenodens
WebIDL::ExceptionOr<GC::Ptr<Attr>> Element::set_attribute_node_ns_for_bindings(Attr& attr)
{
// The setAttributeNode(attr) and setAttributeNodeNS(attr) methods steps are to return the result of setting an attribute given attr and this.
return 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.
if (!m_attributes)
return;
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.
if (!m_attributes)
return;
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 attributes()->remove_attribute_node(attr);
}
// https://dom.spec.whatwg.org/#dom-element-hasattribute
bool Element::has_attribute(FlyString const& name) const
{
if (!m_attributes)
return false;
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
{
if (!m_attributes)
return false;
// 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 is not a valid attribute local name, then throw an "InvalidCharacterError" DOMException.
if (!is_valid_attribute_local_name(name))
return WebIDL::InvalidCharacterError::create(realm(), "Attribute name must not be empty or contain invalid characters"_utf16);
// 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 = 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.
if (!m_attributes)
return {};
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;
}
// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#attr-associated-element
GC::Ptr<DOM::Element> Element::get_the_attribute_associated_element(FlyString const& content_attribute, GC::Ptr<DOM::Element> explicitly_set_attribute_element) const
{
// 1. Let element be the result of running reflectedTarget's get the element.
auto const& element = *this;
// 2. Let contentAttributeValue be the result of running reflectedTarget's get the content attribute.
auto content_attribute_value = element.get_attribute(content_attribute);
// 3. If reflectedTarget's explicitly set attr-element is not null:
if (explicitly_set_attribute_element) {
// 1. If reflectedTarget's explicitly set attr-element is a descendant of any of element's shadow-including
// ancestors, then return reflectedTarget's explicitly set attr-element.
if (&explicitly_set_attribute_element->root() == &element.shadow_including_root())
return *explicitly_set_attribute_element;
// 2. Return null.
return {};
}
// 4. Otherwise, if contentAttributeValue is not null, return the first element candidate, in tree order, that meets
// the following criteria:
// * candidate's root is the same as element's root;
// * candidate's ID is contentAttributeValue; and
// * candidate implements T.
if (content_attribute_value.has_value())
return element.document().get_element_by_id(*content_attribute_value);
// 5. If no such element exists, then return null.
// 6. Return null.
return {};
}
// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#attr-associated-elements
Optional<GC::RootVector<GC::Ref<DOM::Element>>> Element::get_the_attribute_associated_elements(FlyString const& content_attribute, Optional<Vector<GC::Weak<DOM::Element>> const&> explicitly_set_attribute_elements) const
{
// 1. Let elements be an empty list.
GC::RootVector<GC::Ref<DOM::Element>> elements(heap());
// 2. Let element be the result of running reflectedTarget's get the element.
auto const& element = *this;
// 3. If reflectedTarget's explicitly set attr-elements is not null:
if (explicitly_set_attribute_elements.has_value()) {
// 1. For each attrElement in reflectedTarget's explicitly set attr-elements:
for (auto const& attribute_element : *explicitly_set_attribute_elements) {
// 1. If attrElement is not a descendant of any of element's shadow-including ancestors, then continue.
if (!attribute_element || &attribute_element->root() != &element.shadow_including_root())
continue;
// 2. Append attrElement to elements.
elements.append(*attribute_element);
}
}
// 4. Otherwise:
else {
// 1. Let contentAttributeValue be the result of running reflectedTarget's get the content attribute.
auto content_attribute_value = element.get_attribute(content_attribute);
// 2. If contentAttributeValue is null, then return null.
if (!content_attribute_value.has_value())
return {};
// 3. Let tokens be contentAttributeValue, split on ASCII whitespace.
auto tokens = content_attribute_value->bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace);
// 4. For each id of tokens:
for (auto id : tokens) {
// 1. Let candidate be the first element, in tree order, that meets the following criteria:
// * candidate's root is the same as element's root;
// * candidate's ID is id; and
// * candidate implements T.
auto candidate = element.document().get_element_by_id(MUST(FlyString::from_utf8(id)));
// 2. If no such element exists, then continue.
if (!candidate)
continue;
// 3. Append candidate to elements.
elements.append(*candidate);
}
}
// 5. Return elements.
return elements;
}
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_none())
return {};
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::FontComputer const& font_computer)
{
CSS::RequiredInvalidationAfterStyleChange invalidation;
if (old_style.computed_font_list(font_computer) != new_style.computed_font_list(font_computer))
invalidation.relayout = true;
for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
auto property_id = static_cast<CSS::PropertyID>(i);
invalidation |= CSS::compute_property_invalidation(property_id, old_style.property(property_id), new_style.property(property_id));
}
return invalidation;
}
CSS::RequiredInvalidationAfterStyleChange Element::recompute_style(bool& did_change_custom_properties)
{
VERIFY(parent());
m_style_uses_attr_css_function = false;
m_style_uses_var_css_function = false;
m_style_uses_tree_counting_function = false;
m_style_uses_if_css_function = false;
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_child_pseudo_class = false;
m_affected_by_last_child_pseudo_class = false;
m_affected_by_forward_positional_pseudo_class = false;
m_affected_by_backward_positional_pseudo_class = false;
m_sibling_invalidation_distance = 0;
auto& style_computer = document().style_computer();
auto new_computed_properties = style_computer.compute_style({ *this }, did_change_custom_properties);
// 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::KeywordStyleValue::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, document().font_computer());
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();
set_computed_properties({}, move(new_computed_properties));
if (old_display_is_none != new_display_is_none) {
for_each_shadow_including_inclusive_descendant([&](auto& node) {
if (!node.is_element())
return TraversalDecision::Continue;
auto& element = static_cast<Element&>(node);
element.play_or_cancel_animations_after_display_property_change();
return TraversalDecision::Continue;
});
}
// Any document change that can cause this element's style to change, could also affect its pseudo-elements.
auto recompute_pseudo_element_style = [&](CSS::PseudoElement pseudo_element) {
style_computer.push_ancestor(*this);
auto pseudo_element_style = computed_properties(pseudo_element);
auto new_pseudo_element_style = style_computer.compute_pseudo_element_style_if_needed({ *this, pseudo_element }, did_change_custom_properties);
// 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, document().font_computer());
} else if (pseudo_element_style || new_pseudo_element_style) {
invalidation = CSS::RequiredInvalidationAfterStyleChange::full();
}
set_computed_properties(pseudo_element, move(new_pseudo_element_style));
style_computer.pop_ancestor(*this);
};
recompute_pseudo_element_style(CSS::PseudoElement::Before);
recompute_pseudo_element_style(CSS::PseudoElement::After);
recompute_pseudo_element_style(CSS::PseudoElement::Selection);
if (m_rendered_in_top_layer)
recompute_pseudo_element_style(CSS::PseudoElement::Backdrop);
if (had_list_marker || m_computed_properties->display().is_list_item())
recompute_pseudo_element_style(CSS::PseudoElement::Marker);
if (invalidation.is_none())
return invalidation;
if (!invalidation.rebuild_layout_tree && unsafe_layout_node()) {
// If we're keeping the layout tree, we can just apply the new style to the existing layout tree.
unsafe_layout_node()->apply_style(*m_computed_properties);
if (invalidation.repaint)
set_needs_repaint();
// Do the same for pseudo-elements.
for (auto i = 0; i < to_underlying(CSS::PseudoElement::KnownPseudoElementCount); i++) {
auto pseudo_element_type = static_cast<CSS::PseudoElement>(i);
auto pseudo_element = get_pseudo_element(pseudo_element_type);
if (!pseudo_element.has_value() || !pseudo_element->unsafe_layout_node())
continue;
auto pseudo_element_style = computed_properties(pseudo_element_type);
if (!pseudo_element_style)
continue;
if (auto node_with_style = pseudo_element->unsafe_layout_node()) {
node_with_style->apply_style(*pseudo_element_style);
if (invalidation.repaint && node_with_style->first_paintable())
node_with_style->first_paintable()->set_needs_repaint();
}
}
}
return invalidation;
}
CSS::RequiredInvalidationAfterStyleChange Element::recompute_inherited_style()
{
auto computed_properties = this->computed_properties();
// NB: We use unsafe_layout_node() because we're in the middle of style recalculation
// and layout is inherently stale while recomputing inherited styles.
if (!m_cascaded_properties || !computed_properties || !unsafe_layout_node())
return {};
CSS::RequiredInvalidationAfterStyleChange invalidation;
HashMap<size_t, RefPtr<CSS::StyleValue const>> property_values_affected_by_inherited_style;
for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
auto property_id = static_cast<CSS::PropertyID>(i);
// FIXME: We should use the specified value rather than the cascaded value as the cascaded value may include
// unresolved CSS-wide keywords (e.g. 'initial' or 'inherit') rather than the resolved value.
auto const& preabsolutized_value = m_cascaded_properties->property(property_id);
RefPtr old_value = computed_properties->property(property_id);
if (preabsolutized_value) {
// A property needs updating if:
// - It uses relative units as it might have been affected by a change in ancestor element style.
// FIXME: Consider other style values that rely on relative lengths (e.g. CalculatedStyleValue,
// StyleValues which contain lengths (e.g. StyleValueList))
// - font-weight is `bolder` or `lighter`
// - font-size is `larger` or `smaller`
// FIXME: Consider any other properties that rely on inherited values for computation.
auto needs_updating = (preabsolutized_value->is_length() && preabsolutized_value->as_length().length().is_font_relative())
|| (property_id == CSS::PropertyID::FontWeight && first_is_one_of(preabsolutized_value->to_keyword(), CSS::Keyword::Bolder, CSS::Keyword::Lighter))
|| (property_id == CSS::PropertyID::FontSize && first_is_one_of(preabsolutized_value->to_keyword(), CSS::Keyword::Larger, CSS::Keyword::Smaller));
if (needs_updating) {
computed_properties->set_property_without_modifying_flags(property_id, *preabsolutized_value);
property_values_affected_by_inherited_style.set(i, old_value);
}
}
if (!computed_properties->is_property_inherited(property_id))