diff --git a/crates/egui/src/class/has_classes.rs b/crates/egui/src/class/has_classes.rs index 43b13636f..fbfec0a09 100644 --- a/crates/egui/src/class/has_classes.rs +++ b/crates/egui/src/class/has_classes.rs @@ -108,6 +108,17 @@ pub trait HasClasses { fn classes_as_slice(&self) -> &[ClassName] { self.classes().as_slice() } + + /// The last class that names a `T`, if any. + /// + /// Scanning backwards is what makes the last class win, so a widget given two classes of the + /// same kind takes the one set last — the way a later stylesheet rule overrides an earlier one. + fn last_class(&self, from_class_name: impl Fn(&str) -> Option) -> Option { + self.classes_as_slice() + .iter() + .rev() + .find_map(|class| from_class_name(class)) + } } #[cfg(test)] diff --git a/crates/egui/src/ui_stack.rs b/crates/egui/src/ui_stack.rs index 508b9e53e..421fd6447 100644 --- a/crates/egui/src/ui_stack.rs +++ b/crates/egui/src/ui_stack.rs @@ -295,6 +295,15 @@ impl UiStack { pub fn has_class(&self, class: &str) -> bool { self.iter().any(|node| node.classes.has_class(class)) } + + /// Read a value from the classes up the stack, nearest node first. + /// + /// This is how an inherited property works in a stylesheet: a container states it once, and + /// everything inside picks it up. The nearest [`crate::Ui`] wins, so an inner container can + /// override an outer one. + pub fn inherited(&self, from_classes: impl Fn(&Classes) -> Option) -> Option { + self.iter().find_map(|node| from_classes(&node.classes)) + } } // ---------------------------------------------------------------------------- diff --git a/crates/egui/src/widget_style/mod.rs b/crates/egui/src/widget_style/mod.rs index dfd93f754..745ffc851 100644 --- a/crates/egui/src/widget_style/mod.rs +++ b/crates/egui/src/widget_style/mod.rs @@ -228,4 +228,11 @@ impl StyleArgs<'_> { pub fn has_class(&self, class: &str) -> bool { self.classes.has_class(class) || self.stack.has_class(class) } + + /// Read a value from the widget's own classes, falling back to the [`crate::Ui`]s it sits in. + /// + /// See [`UiStack::inherited`] for how the fallback resolves. + pub fn inherited(&self, from_classes: impl Fn(&Classes) -> Option) -> Option { + from_classes(self.classes).or_else(|| self.stack.inherited(from_classes)) + } }