srctree

Robin Linden parent 9918f7f2 0f043143
style: Support css variables with fallback values

inlinesplit
style/styled_node.cpp added: 32, removed: 3, total 29
@@ -239,10 +239,18 @@ std::string_view StyledNode::get_raw_property(css::PropertyId property) const {
// TODO(robinlinden): Fallback values.
// If this is a var() we can easily expand here, do so.
if (it->second.starts_with("var(") && (it->second.find(')') != std::string::npos)) {
auto value = std::string_view{it->second};
 
// Remove "var(" from the start and ")" from the end. 5 characters in total.
auto var_name = it->second.substr(4, it->second.size() - 5);
auto var = value.substr(4, value.size() - 5);
auto [var_name, fallback] = util::split_once(var, ",");
auto prop = resolve_variable(var_name);
if (!prop) {
fallback = util::trim(fallback);
if (!fallback.empty()) {
return fallback;
}
 
return it->second;
}
 
 
style/styled_node_test.cpp added: 32, removed: 3, total 29
@@ -488,6 +488,27 @@ int main() {
std::nullopt);
});
 
etest::test("var() with fallback, var exists", [] {
dom::Node dom = dom::Element{"baka"};
style::StyledNode styled_node{
.node = dom,
.properties{{css::PropertyId::FontWeight, "var(--a, 789)"}},
.custom_properties{{"--a", "123"}},
};
 
expect_eq(styled_node.get_property<css::PropertyId::FontWeight>()->value, 123);
});
 
etest::test("var() with fallback, no var exists", [] {
dom::Node dom = dom::Element{"baka"};
style::StyledNode styled_node{
.node = dom,
.properties{{css::PropertyId::FontWeight, "var(--a, 789)"}},
};
 
expect_eq(styled_node.get_property<css::PropertyId::FontWeight>()->value, 789);
});
 
etest::test("var, inherited custom property", [] {
dom::Node dom = dom::Element{"baka"};
style::StyledNode styled_node{