summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp
blob: f94d8c425da8d1251403414962f228d0b06e8de4 (plain)
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
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2021, Sam Atkins <atkinssj@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibWeb/CSS/Parser/DeprecatedCSSParser.h>
#include <LibWeb/CSS/SelectorEngine.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/Text.h>
#include <LibWeb/HTML/AttributeNames.h>
#include <LibWeb/HTML/HTMLElement.h>

namespace Web::SelectorEngine {

static bool matches_hover_pseudo_class(DOM::Element const& element)
{
    auto* hovered_node = element.document().hovered_node();
    if (!hovered_node)
        return false;
    if (&element == hovered_node)
        return true;
    return element.is_ancestor_of(*hovered_node);
}

static bool matches_attribute(CSS::Selector::SimpleSelector::Attribute const& attribute, DOM::Element const& element)
{
    switch (attribute.match_type) {
    case CSS::Selector::SimpleSelector::Attribute::MatchType::HasAttribute:
        return element.has_attribute(attribute.name);
        break;
    case CSS::Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch:
        return element.attribute(attribute.name) == attribute.value;
        break;
    case CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsWord:
        return element.attribute(attribute.name).split(' ').contains_slow(attribute.value);
        break;
    case CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsString:
        return element.attribute(attribute.name).contains(attribute.value);
        break;
    case CSS::Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment:
        return element.attribute(attribute.name).split('-').first() == attribute.value;
        break;
    case CSS::Selector::SimpleSelector::Attribute::MatchType::StartsWithString:
        return element.attribute(attribute.name).starts_with(attribute.value);
        break;
    case CSS::Selector::SimpleSelector::Attribute::MatchType::EndsWithString:
        return element.attribute(attribute.name).ends_with(attribute.value);
        break;
    case CSS::Selector::SimpleSelector::Attribute::MatchType::None:
        VERIFY_NOT_REACHED();
        break;
    }

    return false;
}

static bool matches_pseudo_class(CSS::Selector::SimpleSelector::PseudoClass const& pseudo_class, DOM::Element const& element)
{
    switch (pseudo_class.type) {
    case CSS::Selector::SimpleSelector::PseudoClass::Type::None:
        break;
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Link:
        return element.is_link();
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Visited:
        // FIXME: Maybe match this selector sometimes?
        return false;
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Active:
        return element.is_active();
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Hover:
        return matches_hover_pseudo_class(element);
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Focus:
        return element.is_focused();
    case CSS::Selector::SimpleSelector::PseudoClass::Type::FirstChild:
        return !element.previous_element_sibling();
    case CSS::Selector::SimpleSelector::PseudoClass::Type::LastChild:
        return !element.next_element_sibling();
    case CSS::Selector::SimpleSelector::PseudoClass::Type::OnlyChild:
        return !(element.previous_element_sibling() || element.next_element_sibling());
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Empty:
        return !(element.first_child_of_type<DOM::Element>() || element.first_child_of_type<DOM::Text>());
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Root:
        return is<HTML::HTMLElement>(element);
    case CSS::Selector::SimpleSelector::PseudoClass::Type::FirstOfType:
        for (auto* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
            if (sibling->tag_name() == element.tag_name())
                return false;
        }
        return true;
    case CSS::Selector::SimpleSelector::PseudoClass::Type::LastOfType:
        for (auto* sibling = element.next_element_sibling(); sibling; sibling = sibling->next_element_sibling()) {
            if (sibling->tag_name() == element.tag_name())
                return false;
        }
        return true;
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Disabled:
        if (!element.tag_name().equals_ignoring_case(HTML::TagNames::input))
            return false;
        if (!element.has_attribute("disabled"))
            return false;
        return true;
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Enabled:
        if (!element.tag_name().equals_ignoring_case(HTML::TagNames::input))
            return false;
        if (element.has_attribute("disabled"))
            return false;
        return true;
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Checked:
        if (!element.tag_name().equals_ignoring_case(HTML::TagNames::input))
            return false;
        if (!element.has_attribute("checked"))
            return false;
        return true;
    case CSS::Selector::SimpleSelector::PseudoClass::Type::Not: {
        if (pseudo_class.not_selector.is_empty())
            return false;
        auto not_selector = Web::parse_selector(CSS::DeprecatedParsingContext(element), pseudo_class.not_selector);
        if (!not_selector.has_value())
            return false;
        auto not_matches = matches(not_selector.value(), element);
        return !not_matches;
    }
    case CSS::Selector::SimpleSelector::PseudoClass::Type::NthChild:
    case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastChild:
        auto const step_size = pseudo_class.nth_child_pattern.step_size;
        auto const offset = pseudo_class.nth_child_pattern.offset;
        if (step_size == 0 && offset == 0)
            return false; // "If both a and b are equal to zero, the pseudo-class represents no element in the document tree."

        auto const* parent = element.parent_element();
        if (!parent)
            return false;

        int index = 1;
        if (pseudo_class.type == CSS::Selector::SimpleSelector::PseudoClass::Type::NthChild) {
            for (auto* child = parent->first_child_of_type<DOM::Element>(); child && child != &element; child = child->next_element_sibling())
                ++index;
        } else {
            for (auto* child = parent->last_child_of_type<DOM::Element>(); child && child != &element; child = child->previous_element_sibling())
                ++index;
        }

        if (step_size < 0) {
            // When "step_size" is negative, selector represents first "offset" elements in document tree.
            return !(offset <= 0 || index > offset);
        } else if (step_size == 1) {
            // When "step_size == 1", selector represents last "offset" elements in document tree.
            return !(offset < 0 || index < offset);
        }

        // Like "a % b", but handles negative integers correctly.
        auto const canonical_modulo = [](int a, int b) -> int {
            int c = a % b;
            if ((c < 0 && b > 0) || (c > 0 && b < 0)) {
                c += b;
            }
            return c;
        };

        if (step_size == 0) {
            // Avoid divide by zero.
            if (index != offset) {
                return false;
            }
        } else if (canonical_modulo(index - offset, step_size) != 0) {
            return false;
        }
        return true;
    }

    return false;
}

static bool matches(CSS::Selector::SimpleSelector const& component, DOM::Element const& element)
{
    switch (component.type) {
    case CSS::Selector::SimpleSelector::Type::Universal:
        return true;
    case CSS::Selector::SimpleSelector::Type::Id:
        return component.value == element.attribute(HTML::AttributeNames::id);
    case CSS::Selector::SimpleSelector::Type::Class:
        return element.has_class(component.value);
    case CSS::Selector::SimpleSelector::Type::TagName:
        return component.value == element.local_name();
    case CSS::Selector::SimpleSelector::Type::Attribute:
        return matches_attribute(component.attribute, element);
    case CSS::Selector::SimpleSelector::Type::PseudoClass:
        return matches_pseudo_class(component.pseudo_class, element);
    case CSS::Selector::SimpleSelector::Type::PseudoElement:
        // FIXME: Implement pseudo-elements.
        return false;
    default:
        VERIFY_NOT_REACHED();
    }
}

static bool matches(CSS::Selector const& selector, int component_list_index, DOM::Element const& element)
{
    auto& component_list = selector.complex_selectors()[component_list_index];
    for (auto& component : component_list.compound_selector) {
        if (!matches(component, element))
            return false;
    }
    switch (component_list.relation) {
    case CSS::Selector::ComplexSelector::Relation::None:
        return true;
    case CSS::Selector::ComplexSelector::Relation::Descendant:
        VERIFY(component_list_index != 0);
        for (auto* ancestor = element.parent(); ancestor; ancestor = ancestor->parent()) {
            if (!is<DOM::Element>(*ancestor))
                continue;
            if (matches(selector, component_list_index - 1, verify_cast<DOM::Element>(*ancestor)))
                return true;
        }
        return false;
    case CSS::Selector::ComplexSelector::Relation::ImmediateChild:
        VERIFY(component_list_index != 0);
        if (!element.parent() || !is<DOM::Element>(*element.parent()))
            return false;
        return matches(selector, component_list_index - 1, verify_cast<DOM::Element>(*element.parent()));
    case CSS::Selector::ComplexSelector::Relation::AdjacentSibling:
        VERIFY(component_list_index != 0);
        if (auto* sibling = element.previous_element_sibling())
            return matches(selector, component_list_index - 1, *sibling);
        return false;
    case CSS::Selector::ComplexSelector::Relation::GeneralSibling:
        VERIFY(component_list_index != 0);
        for (auto* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
            if (matches(selector, component_list_index - 1, *sibling))
                return true;
        }
        return false;
    case CSS::Selector::ComplexSelector::Relation::Column:
        TODO();
    }
    VERIFY_NOT_REACHED();
}

bool matches(CSS::Selector const& selector, DOM::Element const& element)
{
    VERIFY(!selector.complex_selectors().is_empty());
    return matches(selector, selector.complex_selectors().size() - 1, element);
}

}