use std::{collections::HashMap, sync::Arc};
use super::{
part_ids::{Lent, Owner},
part_style::PartStyle,
};
use crate::{
app::theme::{Breakpoint, Density, RoleName, Theme},
components::Text,
node::{Node, NodeUpdate},
};
pub type Name = RoleName;
pub const ROW_STEPS: [(Density, f32); 3] = [
(Density::Compact, -8.0),
(Density::Comfortable, 8.0),
(Density::Touch, 12.0),
];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Interaction {
Hovered,
Pressed,
FocusVisible,
}
impl Interaction {
pub const ALL: [Interaction; 3] = [Self::Hovered, Self::Pressed, Self::FocusVisible];
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Selector {
variant: Option<Name>,
size: Option<Name>,
density: Option<Name>,
breakpoint: Option<Breakpoint>,
states: Vec<Name>,
interaction: Option<Interaction>,
within: bool,
}
impl Selector {
pub fn new() -> Self {
Self::default()
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = Some(variant.into());
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = Some(size.into());
self
}
pub fn density(mut self, density: impl Into<Density>) -> Self {
self.density = Some(Name::new(density.into().as_str()));
self
}
pub fn breakpoint(mut self, breakpoint: Breakpoint) -> Self {
self.breakpoint = Some(breakpoint);
self
}
pub fn state(mut self, state: impl Into<Name>) -> Self {
let state = state.into();
if !self.states.contains(&state) {
self.states.push(state);
}
self
}
pub fn held_states(&self) -> &[Name] {
&self.states
}
pub fn interaction(&self) -> Option<Interaction> {
self.interaction
}
pub fn hovered(mut self) -> Self {
self.interaction = Some(Interaction::Hovered);
self
}
pub fn pressed(mut self) -> Self {
self.interaction = Some(Interaction::Pressed);
self
}
pub fn focus_visible(mut self) -> Self {
self.interaction = Some(Interaction::FocusVisible);
self
}
pub fn within(mut self) -> Self {
self.within = true;
self
}
fn rank(&self) -> usize {
if !self.states.is_empty() {
10 + self.states.len()
} else if let Some(breakpoint) = self.breakpoint {
4 + breakpoint as usize
} else if self.density.is_some() {
3
} else if self.size.is_some() {
2
} else if self.variant.is_some() {
1
} else {
0
}
}
fn holds(&self, case: &Case) -> bool {
self.variant.is_none_or(|variant| case.variant == Some(variant))
&& self.size.is_none_or(|size| case.size == Some(size))
&& self.density.is_none_or(|density| case.density == Some(density))
&& self
.breakpoint
.is_none_or(|from| case.breakpoint.is_some_and(|window| window >= from))
&& self.states.iter().all(|state| case.states.contains(state))
}
}
#[derive(Clone, Debug)]
pub struct Rule {
pub selector: Selector,
pub part: Name,
pub style: PartStyle,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Case {
pub variant: Option<Name>,
pub size: Option<Name>,
pub density: Option<Name>,
pub breakpoint: Option<Breakpoint>,
pub states: Vec<Name>,
}
impl Case {
pub fn new() -> Self {
Self::default()
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = Some(variant.into());
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = Some(size.into());
self
}
pub fn density(mut self, density: impl Into<Density>) -> Self {
self.density = Some(Name::new(density.into().as_str()));
self
}
pub(crate) fn in_theme(&self, theme: &Theme) -> Self {
let mut case = self.clone();
if case.density.is_none() {
case.density = Some(Name::new(theme.density().as_str()));
}
case
}
pub fn breakpoint(mut self, breakpoint: Option<Breakpoint>) -> Self {
self.breakpoint = breakpoint;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
if on && !self.states.contains(&state) {
self.states.push(state);
}
self
}
}
#[derive(Clone, Debug, Default)]
pub struct Recipe {
rules: Vec<Rule>,
lent: Option<Lent>,
descriptions: Vec<Description>,
}
type Description = (Arc<str>, Arc<str>);
impl Recipe {
pub fn new() -> Self {
Self::default()
}
pub fn when(mut self, selector: Selector, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules.push(Rule {
selector,
part: part.into(),
style: style(PartStyle::new()),
});
self
}
pub fn base(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new(), part, style)
}
pub fn variant(
self,
variant: impl Into<Name>,
part: impl Into<Name>,
style: impl FnOnce(PartStyle) -> PartStyle,
) -> Self {
self.when(Selector::new().variant(variant), part, style)
}
pub fn size(self, size: impl Into<Name>, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new().size(size), part, style)
}
pub fn density(
self,
density: impl Into<Density>,
part: impl Into<Name>,
style: impl FnOnce(PartStyle) -> PartStyle,
) -> Self {
self.when(Selector::new().density(density), part, style)
}
pub fn by_density(
self,
selector: Selector,
part: impl Into<Name>,
style: impl Fn(PartStyle, f32) -> PartStyle,
) -> Self {
let part = part.into();
ROW_STEPS.iter().fold(self, |recipe, (density, step)| {
recipe.when(selector.clone().density(*density), part, |s| style(s, *step))
})
}
pub fn row_density(self, selector: Selector, part: impl Into<Name>, height: f32) -> Self {
self.by_density(selector, part, move |s, step| s.height(height + step))
}
pub fn at(self, breakpoint: Breakpoint, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new().breakpoint(breakpoint), part, style)
}
pub fn state(
self,
state: impl Into<Name>,
part: impl Into<Name>,
style: impl FnOnce(PartStyle) -> PartStyle,
) -> Self {
self.when(Selector::new().state(state), part, style)
}
pub fn hovered(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new().hovered(), part, style)
}
pub fn pressed(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new().pressed(), part, style)
}
pub fn focus_visible(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new().focus_visible(), part, style)
}
pub fn within(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new().within(), part, style)
}
pub fn within_hovered(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new().within().hovered(), part, style)
}
pub fn within_pressed(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.when(Selector::new().within().pressed(), part, style)
}
pub fn extend(mut self, other: &Recipe) -> Self {
self.rules.extend(other.rules.iter().cloned());
self.lent = Lent::over(self.lent, other.lent.as_ref());
self.descriptions.extend(other.descriptions.iter().cloned());
self
}
pub fn describe(mut self, name: impl Into<Arc<str>>, value: impl Into<Arc<str>>) -> Self {
self.descriptions.push((name.into(), value.into()));
self
}
pub fn descriptions(&self) -> &[(Arc<str>, Arc<str>)] {
&self.descriptions
}
pub fn rules(&self) -> &[Rule] {
&self.rules
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
pub(crate) fn lent(&self) -> Option<&Lent> {
self.lent.as_ref()
}
pub fn resolve(&self, case: &Case, theme: &Theme) -> ResolvedRecipe {
resolve(&[self], case, theme)
}
}
pub(crate) fn resolve(recipes: &[&Recipe], case: &Case, theme: &Theme) -> ResolvedRecipe {
let lent = recipes.iter().rev().find_map(|recipe| recipe.lent.clone());
ResolvedRecipe::new(
theme,
Arc::new(resolve_styles(recipes, &case.in_theme(theme))),
ROOT,
lent,
)
.described(recipes)
}
pub(crate) const ROOT: &str = "root";
pub(crate) fn resolve_styles(recipes: &[&Recipe], case: &Case) -> ResolvedStyles {
let mut holding: Vec<(usize, usize, &Rule)> = recipes
.iter()
.enumerate()
.flat_map(|(layer, recipe)| recipe.rules.iter().map(move |rule| (layer, rule)))
.filter(|(_, rule)| rule.selector.holds(case))
.map(|(layer, rule)| (layer, rule.selector.rank(), rule))
.collect();
holding.sort_by_key(|(layer, rank, _)| (*layer, *rank));
let mut parts: HashMap<Name, PartStyles> = HashMap::new();
for (_, _, rule) in holding {
let part = parts.entry(rule.part).or_default();
match rule.selector.interaction {
None | Some(Interaction::FocusVisible) if rule.selector.within => part.within.merge(&rule.style),
Some(Interaction::Hovered) if rule.selector.within => part.within_hovered.merge(&rule.style),
Some(Interaction::Pressed) if rule.selector.within => part.within_pressed.merge(&rule.style),
None => part.rest.merge(&rule.style),
Some(Interaction::Hovered) => part.hovered.merge(&rule.style),
Some(Interaction::Pressed) => part.pressed.merge(&rule.style),
Some(Interaction::FocusVisible) => part.focus_visible.merge(&rule.style),
}
}
ResolvedStyles {
parts,
nothing: PartStyles::default(),
}
}
#[derive(Clone, Debug, Default)]
pub struct PartStyles {
pub rest: PartStyle,
pub hovered: PartStyle,
pub pressed: PartStyle,
pub focus_visible: PartStyle,
pub within: PartStyle,
pub within_hovered: PartStyle,
pub within_pressed: PartStyle,
}
impl PartStyles {
pub fn interaction(&self, interaction: Interaction) -> &PartStyle {
match interaction {
Interaction::Hovered => &self.hovered,
Interaction::Pressed => &self.pressed,
Interaction::FocusVisible => &self.focus_visible,
}
}
}
pub(crate) struct ResolvedStyles {
parts: HashMap<Name, PartStyles>,
nothing: PartStyles,
}
#[derive(Clone)]
pub struct ResolvedRecipe {
theme: Theme,
styles: Arc<ResolvedStyles>,
root: Name,
owner: Option<Owner>,
lent: Option<Lent>,
descriptions: Option<Arc<[Description]>>,
}
impl ResolvedRecipe {
pub(crate) fn new(theme: &Theme, styles: Arc<ResolvedStyles>, root: impl Into<Name>, lent: Option<Lent>) -> Self {
Self {
theme: theme.clone(),
styles,
root: root.into(),
owner: None,
lent,
descriptions: None,
}
}
pub(crate) fn described(mut self, recipes: &[&Recipe]) -> Self {
let said: Vec<Description> = recipes
.iter()
.flat_map(|recipe| recipe.descriptions.iter().cloned())
.collect();
self.descriptions = (!said.is_empty()).then(|| Arc::from(said));
self
}
pub(crate) fn rooted_at(mut self, part: impl Into<Name>) -> Self {
self.root = part.into();
self
}
pub fn owned_by(mut self, id: Option<&Arc<str>>) -> Self {
self.owner = match id {
Some(id) => Some(Owner::new(id.clone(), self.root, true)),
None => self.lent.take().and_then(|lent| lent.owner(self.root)),
};
self
}
pub fn owned_like(mut self, other: &ResolvedRecipe) -> Self {
self.owner = other.owner.as_ref().map(|owner| owner.rooted(self.root));
self.lent = None;
self
}
pub fn item(&self, id: Option<&Arc<str>>, root: impl Into<Name>) -> Self {
let mut item = self.clone();
if let Some(id) = id {
item.owner = Some(Owner::new(id.clone(), root.into(), true));
}
item
}
pub fn keyed_item(&self, key: &str, root: impl Into<Name>) -> Self {
let mut item = self.clone();
item.owner = self.owner.as_ref().map(|owner| owner.item(root.into(), key));
item
}
pub fn part_id(&self, part: impl Into<Name>) -> Option<Arc<str>> {
self.owner.as_ref()?.next(part.into())
}
pub fn keyed_id(&self, part: impl Into<Name>, key: impl std::fmt::Display) -> Option<Arc<str>> {
self.owner.as_ref()?.keyed(part.into(), &key.to_string())
}
pub fn lend(&self, part: impl Into<Name>) -> Recipe {
Recipe {
rules: Vec::new(),
lent: self.lent_part(part.into(), true),
descriptions: Vec::new(),
}
}
fn lent_part(&self, part: Name, to_root: bool) -> Option<Lent> {
self.owner.clone().map(|owner| Lent::new(owner, part, to_root))
}
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
ResolvedPart {
recipe: self.clone(),
part: part.into(),
forced: None,
named: true,
key: None,
}
}
pub fn theme(&self) -> &Theme {
&self.theme
}
pub fn has(&self, part: impl Into<Name>) -> bool {
self.styles.parts.contains_key(&part.into())
}
fn styles(&self, part: Name) -> &PartStyles {
self.styles.parts.get(&part).unwrap_or(&self.styles.nothing)
}
pub fn rules_for(&self, part: impl Into<Name>, inner: impl Into<Name>) -> Recipe {
let part = part.into();
let styles = self.styles(part).clone();
let inner = inner.into();
let mut recipe = Recipe::new();
recipe.lent = self.lent_part(part, inner.as_str() == ROOT);
recipe
.base(inner, |_| styles.rest.clone())
.hovered(inner, |_| styles.hovered.clone())
.pressed(inner, |_| styles.pressed.clone())
.focus_visible(inner, |_| styles.focus_visible.clone())
.within(inner, |_| styles.within.clone())
.within_hovered(inner, |_| styles.within_hovered.clone())
.within_pressed(inner, |_| styles.within_pressed.clone())
}
}
#[derive(Clone)]
pub struct ResolvedPart {
recipe: ResolvedRecipe,
part: Name,
forced: Option<Interaction>,
named: bool,
key: Option<Arc<str>>,
}
impl ResolvedPart {
pub fn forced(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn keyed(mut self, key: impl std::fmt::Display) -> Self {
self.key = Some(Arc::from(key.to_string()));
self
}
pub fn unnamed(mut self) -> Self {
self.named = false;
self
}
fn id(&self) -> Option<Arc<str>> {
let owner = self.recipe.owner.as_ref()?;
match &self.key {
Some(key) => owner.keyed(self.part, key),
None => owner.next(self.part),
}
}
pub fn styles(&self) -> &PartStyles {
self.recipe.styles(self.part)
}
pub fn rest(&self) -> PartStyle {
let styles = self.styles();
match self.forced {
Some(Interaction::Pressed) => styles
.rest
.clone()
.merged(&styles.within)
.merged(&styles.within_hovered)
.merged(&styles.within_pressed)
.merged(&styles.hovered)
.merged(&styles.pressed),
Some(Interaction::Hovered) => styles
.rest
.clone()
.merged(&styles.within)
.merged(&styles.within_hovered)
.merged(&styles.hovered),
Some(interaction) => styles
.rest
.clone()
.merged(&styles.within)
.merged(styles.interaction(interaction)),
None => styles.rest.clone(),
}
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn text(&self, content: &str) -> Text {
let rest = self.rest();
let mut style = rest.text.resolve(self.theme());
if !self.sets_foreground(&rest) {
return Text::styled(content, style);
}
let role = std::mem::replace(&mut style.color, crate::layout::text_style::DEFAULT_TEXT_COLOR);
let text = Text::styled(content, style);
if rest.foreground.is_none() && role != crate::layout::text_style::DEFAULT_TEXT_COLOR {
text.foreground(role)
} else {
text
}
}
fn sets_foreground(&self, rest: &PartStyle) -> bool {
let styles = self.styles();
rest.foreground.is_some()
|| [
&styles.hovered,
&styles.pressed,
&styles.focus_visible,
&styles.within,
&styles.within_hovered,
&styles.within_pressed,
]
.iter()
.any(|style| style.foreground.is_some())
}
pub(crate) fn apply(&self, node: &mut Node) {
if self.named
&& node.element_id.is_none()
&& let Some(id) = self.id()
{
NodeUpdate::id(node, id);
}
if self.part == self.recipe.root
&& let Some(descriptions) = &self.recipe.descriptions
{
for (name, value) in descriptions.iter() {
NodeUpdate::describe(node, name.clone(), value.clone());
}
}
let theme = self.theme();
let styles = self.styles();
self.rest().apply(node, theme);
if let Some(style) = styles.hovered.state_style(theme) {
NodeUpdate::hovered_style(node, style);
}
if let Some(style) = styles.pressed.state_style(theme) {
NodeUpdate::active_style(node, style);
}
if let Some(style) = styles.focus_visible.state_style(theme) {
NodeUpdate::focus_visible_style(node, style);
}
if let Some(style) = styles.within.state_style(theme) {
NodeUpdate::within_style(node, style);
}
if let Some(style) = styles.within_hovered.state_style(theme) {
NodeUpdate::within_hovered_style(node, style);
}
if let Some(style) = styles.within_pressed.state_style(theme) {
NodeUpdate::within_pressed_style(node, style);
}
}
}
#[cfg(test)]
mod tests {
use super::{Case, Interaction, Recipe, Selector};
use crate::{
app::theme::{ControlSize, PaletteColor, RadiusSize, Theme},
node::BackgroundColor,
ui::Length,
};
fn recipe() -> Recipe {
Recipe::new()
.base("root", |s| {
s.height(ControlSize::Md)
.radius(RadiusSize::Md)
.background(PaletteColor::Muted)
})
.variant("primary", "root", |s| s.background(PaletteColor::Primary))
.size("lg", "root", |s| s.height(ControlSize::Lg))
.state("disabled", "root", |s| s.opacity(0.5))
.when(Selector::new().variant("primary").hovered(), "root", |s| {
s.background(PaletteColor::PrimaryHover)
})
.hovered("root", |s| s.background(PaletteColor::StateHover))
}
fn background(color: PaletteColor) -> Option<BackgroundColor> {
Some(BackgroundColor::Palette(color))
}
#[test]
fn the_rules_that_hold_are_laid_the_more_specific_over_the_less() {
let theme = Theme::new();
let resolved = recipe().resolve(&Case::new().variant("primary").size("lg"), &theme);
let root = resolved.part("root").rest();
assert_eq!(
root.background,
background(PaletteColor::Primary),
"the variant over the base"
);
assert_eq!(
root.height,
Some(Length::Control(ControlSize::Lg)),
"the size over the base"
);
assert_eq!(
root.radius,
Some(crate::node::border::ThemedBorderRadius::all(RadiusSize::Md)),
"what nothing replaced"
);
assert_eq!(root.opacity, None, "a state it is not in");
}
#[test]
fn a_rule_for_a_state_holds_while_the_component_is_in_it() {
let theme = Theme::new();
let case = Case::new().state("disabled", true).state("loading", false);
assert!(recipe().resolve(&case, &theme).part("root").rest().opacity.is_some());
}
#[test]
fn an_interaction_is_kept_apart_from_the_style_at_rest() {
let theme = Theme::new();
let primary = recipe().resolve(&Case::new().variant("primary"), &theme);
let root = primary.part("root");
assert_eq!(root.rest().background, background(PaletteColor::Primary));
assert_eq!(
root.styles().hovered.background,
background(PaletteColor::PrimaryHover),
"the rule for a primary button under the pointer over the one for any"
);
let plain = recipe().resolve(&Case::new(), &theme);
assert_eq!(
plain.part("root").styles().hovered.background,
background(PaletteColor::StateHover)
);
}
#[test]
fn a_forced_interaction_is_drawn_as_the_style_at_rest() {
let theme = Theme::new();
let resolved = recipe().resolve(&Case::new().variant("primary"), &theme);
let hovered = resolved.part("root").forced(Some(Interaction::Hovered)).rest();
assert_eq!(hovered.background, background(PaletteColor::PrimaryHover));
assert_eq!(
hovered.radius,
Some(crate::node::border::ThemedBorderRadius::all(RadiusSize::Md))
);
}
#[test]
fn a_later_recipe_is_laid_over_an_earlier_one_whatever_the_case() {
let theme = Theme::new();
let instance = Recipe::new().base("root", |s| s.background(PaletteColor::Destructive));
let resolved = super::resolve(&[&recipe(), &instance], &Case::new().variant("primary"), &theme);
assert_eq!(
resolved.part("root").rest().background,
background(PaletteColor::Destructive),
"the instance's rule for any case over the theme's rule for the variant"
);
}
#[test]
fn a_rule_for_a_density_holds_while_the_theme_is_at_it() {
use crate::app::theme::Density;
let theme = Theme::new();
let recipe = Recipe::new()
.base("root", |s| s.height(36.0))
.size("lg", "root", |s| s.height(40.0))
.density(Density::Compact, "root", |s| s.height(28.0))
.density(Density::Touch, "root", |s| s.height(48.0));
let height = |case: Case| recipe.resolve(&case, &theme).part("root").rest().height;
assert_eq!(height(Case::new()), Some(Length::Px(36.0)), "the default density");
theme.set_density(Density::Compact);
assert_eq!(height(Case::new()), Some(Length::Px(28.0)), "the theme at compact");
assert_eq!(
height(Case::new().size("lg")),
Some(Length::Px(28.0)),
"the rule for the density over the rule for the size"
);
assert_eq!(
height(Case::new().density(Density::Touch)),
Some(Length::Px(48.0)),
"a case that names a density keeps it"
);
}
#[test]
fn a_rule_for_a_breakpoint_holds_from_that_width_up() {
use crate::app::theme::Breakpoint;
let theme = Theme::new();
let recipe = Recipe::new()
.base("root", |s| s.height(48.0))
.at(Breakpoint::Md, "root", |s| s.height(36.0))
.at(Breakpoint::Xl, "root", |s| s.height(40.0));
let height = |breakpoint| {
recipe
.resolve(&Case::new().breakpoint(breakpoint), &theme)
.part("root")
.rest()
.height
};
assert_eq!(
height(None),
Some(Length::Px(48.0)),
"a phone: the rule for every width"
);
assert_eq!(
height(Some(Breakpoint::Sm)),
Some(Length::Px(48.0)),
"narrower than the rule's"
);
assert_eq!(height(Some(Breakpoint::Md)), Some(Length::Px(36.0)));
assert_eq!(
height(Some(Breakpoint::Lg)),
Some(Length::Px(36.0)),
"and at every wider one"
);
assert_eq!(
height(Some(Breakpoint::Xl)),
Some(Length::Px(40.0)),
"the widest that holds wins"
);
}
#[test]
fn a_part_no_rule_styles_is_unstyled() {
let theme = Theme::new();
let resolved = recipe().resolve(&Case::new(), &theme);
assert!(resolved.part("icon").rest().is_empty());
assert!(
Recipe::new()
.resolve(&Case::new(), &theme)
.part("root")
.rest()
.is_empty()
);
}
#[test]
fn an_app_names_variants_and_states_of_its_own() {
let theme = Theme::new();
let recipe = recipe()
.variant("brand", "root", |s| s.background(PaletteColor::extra("brand")))
.state("pinned", "root", |s| s.radius(RadiusSize::Full));
let resolved = recipe.resolve(&Case::new().variant("brand").state("pinned", true), &theme);
let root = resolved.part("root").rest();
assert_eq!(root.background, background(PaletteColor::extra("brand")));
assert_eq!(
root.radius,
Some(crate::node::border::ThemedBorderRadius::all(RadiusSize::Full))
);
}
}