LibHTML: Support the :first-child and :last-child pseudo classes

This commit is contained in:
Andreas Kling 2019-12-16 19:34:52 +01:00
parent 870df4a8c6
commit c1474e594e
Notes: sideshowbarker 2024-07-19 10:50:13 +09:00
6 changed files with 63 additions and 0 deletions

View file

@ -0,0 +1,24 @@
<html>
<head>
<title>:first-child test</title>
<style>
p:first-child {
color: lime;
background-color: black;
padding: 5px;
}
</style>
</head>
<body>
<div>
<p>This text is selected!</p>
<p>This text isn't selected.</p>
</div>
<div>
<h2>This text isn't selected: it's not a `p`.</h2>
<p>This text isn't selected.</p>
</div>
</body>
</html>

View file

@ -0,0 +1,23 @@
<html>
<head>
<title>:last-child test</title>
<style>
p:last-child {
color: lime;
background-color: black;
padding: 5px;
}
</style>
</head>
<body>
<div>
<p>This text isn't selected.</p>
<p>This text is selected!</p>
</div>
<div>
<p>This text isn't selected.</p>
<h2>This text isn't selected: it's not a `p`.</h2>
</div>
</body>
</html>

View file

@ -24,6 +24,8 @@ h1 {
<p>Some small test pages:</p>
<ul>
<li><a href="small.html">small</a></li>
<li><a href="first-child.html">:first-child</a></li>
<li><a href="last-child.html">:last-child</a></li>
<li><a href="form.html">form</a></li>
<li><a href="borders.html">borders</a></li>
<li><a href="css.html">css</a></li>

View file

@ -20,6 +20,8 @@ public:
None,
Link,
Hover,
FirstChild,
LastChild,
};
PseudoClass pseudo_class { PseudoClass::None };

View file

@ -27,6 +27,14 @@ bool matches(const Selector::SimpleSelector& component, const Element& element)
if (!matches_hover_pseudo_class(element))
return false;
break;
case Selector::SimpleSelector::PseudoClass::FirstChild:
if (element.previous_element_sibling())
return false;
break;
case Selector::SimpleSelector::PseudoClass::LastChild:
if (element.next_element_sibling())
return false;
break;
}
switch (component.attribute_match_type) {

View file

@ -321,6 +321,10 @@ public:
simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Link;
else if (pseudo_name == "hover")
simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Hover;
else if (pseudo_name == "first-child")
simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::FirstChild;
else if (pseudo_name == "last-child")
simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::LastChild;
}
return simple_selector;