From dc30ace1213241a744f3d88d432f0ff299b85987 Mon Sep 17 00:00:00 2001 From: Darren Burns Date: Thu, 16 Jun 2022 15:01:15 +0100 Subject: [PATCH] Fix specificity ordering --- src/textual/css/stylesheet.py | 16 +++++++++------- tests/css/test_stylesheet.py | 4 ++-- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/textual/css/stylesheet.py b/src/textual/css/stylesheet.py index 36de39f32..e3b194fc6 100644 --- a/src/textual/css/stylesheet.py +++ b/src/textual/css/stylesheet.py @@ -296,13 +296,15 @@ class Stylesheet: rule_attributes[key].append((rule_specificity, value)) # For each rule declared for this node, keep only the most specific one - node_rules: RulesMap = cast( - RulesMap, - { - name: specificity_rules[-1][1] - for name, specificity_rules in rule_attributes.items() - }, - ) + get_first_item = itemgetter(0) + node_rules: RulesMap = cast(RulesMap, {}) + for name, specificity_rules in rule_attributes.items(): + highest_specificity = max(specificity_rules, key=get_first_item)[0] + rules_with_highest_specificity = [ + rule for rule in specificity_rules if rule[0] == highest_specificity + ] + node_rules[name] = rules_with_highest_specificity[-1][1] + self.replace_rules(node, node_rules, animate=animate) if isinstance(node, Widget): node._refresh_scrollbars() diff --git a/tests/css/test_stylesheet.py b/tests/css/test_stylesheet.py index d8d067cd9..9892d034e 100644 --- a/tests/css/test_stylesheet.py +++ b/tests/css/test_stylesheet.py @@ -11,12 +11,12 @@ from textual.dom import DOMNode def test_stylesheet_apply_takes_final_rule_in_specificity_clash(): - css = ".a {background: red; color: lime} .b {background:blue}" + css = ".a {background: red; color: lime} .b {background: blue}" stylesheet = Stylesheet() stylesheet.source["test.css"] = css stylesheet.parse() - node = DOMNode(classes="a b") + node = DOMNode(classes="a b", id="c") stylesheet.apply(node) assert node.styles.color == Color(0, 255, 0) # color: lime