Skip to content

Commit

Permalink
style: Apply important declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
robinlinden committed Nov 16, 2023
1 parent 07e7fa0 commit 4d3a3b4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
12 changes: 12 additions & 0 deletions style/style.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,18 @@ std::vector<std::pair<css::PropertyId, std::string>> matching_rules(
}
}

// TODO(robinlinden): !important inline styles should override the ones from
// the style sheets.
for (auto const &rule : stylesheet.rules) {
if (rule.important_declarations.empty() || (rule.media_query.has_value() && !rule.media_query->evaluate(ctx))) {
continue;
}

if (std::ranges::any_of(rule.selectors, [&](auto const &selector) { return is_match(node, selector); })) {
std::ranges::copy(rule.important_declarations, std::back_inserter(matched_rules));
}
}

return matched_rules;
}

Expand Down
20 changes: 20 additions & 0 deletions style/style_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,25 @@ void inline_css_tests() {
std::pair{css::PropertyId::FontSize, "2000px"s}, std::pair{css::PropertyId::FontSize, "2px"s}});
});
}

void important_declarations_tests() {
etest::test("!important: has higher priority", [] {
dom::Node dom = dom::Element{"div"};
css::StyleSheet css{.rules{{
.selectors = {"div"},
.declarations = {{css::PropertyId::FontSize, "2px"}},
.important_declarations = {{css::PropertyId::FontSize, "20px"}},
}}};
auto styled = style::style_tree(dom, css);

// The last property is the one that's applied.
expect_eq(styled->properties,
std::vector{
std::pair{css::PropertyId::FontSize, "2px"s},
std::pair{css::PropertyId::FontSize, "20px"s},
});
});
}
} // namespace

int main() {
Expand Down Expand Up @@ -241,5 +260,6 @@ int main() {
});

inline_css_tests();
important_declarations_tests();
return etest::run_all_tests();
}

0 comments on commit 4d3a3b4

Please sign in to comment.