Skip to main content

leptos_css/
declaration.rs

1use std::borrow::Cow;
2
3use leptos::tachys::{
4    html::{
5        attribute::Attribute,
6        style::{IntoStyle, style},
7    },
8    renderer::{Rndr, dom::CssStyleDeclaration, types::Element},
9};
10
11use crate::CheckedCssValue;
12
13/// An owned CSS declaration whose property and value grammar were checked together.
14///
15/// The representation is private so a property name cannot be separated from its checked value
16/// and recombined with another value. Construction is restricted to crate-owned boundaries that
17/// pair a validated name with a sealed [`crate::CheckedCssValue`] grammar.
18///
19/// Different checked grammars and properties erase into the same storable type:
20///
21/// ```rust
22/// use leptos_css::{
23///     CheckedDeclaration, CssColor, Padding, css_custom_property, px, rgb,
24///     property::{ColorProperty, PaddingProperty},
25/// };
26///
27/// css_custom_property!(ACCENT: CssColor = "--accent");
28/// let declarations: Vec<CheckedDeclaration> = vec![
29///     PaddingProperty.declare(Padding::all(px(16))),
30///     ColorProperty.declare(rgb(255, 0, 0)),
31///     ACCENT.declare(rgb(0, 0, 255)),
32/// ];
33/// assert_eq!(declarations[0].property_name(), "padding");
34/// ```
35///
36/// Its private constructor prevents unchecked property/value recombination:
37///
38/// ```compile_fail
39/// use std::borrow::Cow;
40/// use leptos_css::{CheckedDeclaration, rgb};
41///
42/// let _ = CheckedDeclaration::new(Cow::Borrowed("padding"), rgb(255, 0, 0));
43/// ```
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct CheckedDeclaration {
46    property: Cow<'static, str>,
47    value: String,
48}
49
50impl CheckedDeclaration {
51    pub(crate) fn new(property: Cow<'static, str>, value: impl CheckedCssValue) -> Self {
52        // Most primitive and shorthand values fit without growing this initial allocation.
53        let mut rendered = String::with_capacity(32);
54        value.write_to(&mut rendered);
55        Self {
56            property,
57            value: rendered,
58        }
59    }
60
61    /// Return the checked CSS property name.
62    #[must_use]
63    pub fn property_name(&self) -> &str {
64        &self.property
65    }
66
67    /// Append the complete `property:value;` declaration to a string buffer.
68    pub fn write_declaration_to(&self, output: &mut String) {
69        output.push_str(&self.property);
70        output.push(':');
71        output.push_str(&self.value);
72        output.push(';');
73    }
74
75    /// Convert this declaration into a spreadable Leptos style attribute.
76    pub fn into_attribute(self) -> impl Attribute {
77        style(self)
78    }
79}
80
81fn set_declaration(style: &CssStyleDeclaration, declaration: &CheckedDeclaration) {
82    Rndr::set_css_property(style, declaration.property_name(), &declaration.value);
83}
84
85impl IntoStyle for CheckedDeclaration {
86    type AsyncOutput = Self;
87    type State = (CssStyleDeclaration, Self);
88    type Cloneable = Self;
89    type CloneableOwned = Self;
90
91    fn to_html(self, style: &mut String) {
92        self.write_declaration_to(style);
93    }
94
95    fn hydrate<const FROM_SERVER: bool>(self, el: &Element) -> Self::State {
96        (Rndr::style(el), self)
97    }
98
99    fn build(self, el: &Element) -> Self::State {
100        let style = Rndr::style(el);
101        set_declaration(&style, &self);
102        (style, self)
103    }
104
105    fn rebuild(self, state: &mut Self::State) {
106        let (style, current) = state;
107        if self.property != current.property {
108            Rndr::remove_css_property(style, current.property_name());
109            set_declaration(style, &self);
110        } else if self.value != current.value {
111            set_declaration(style, &self);
112        }
113        *current = self;
114    }
115
116    fn into_cloneable(self) -> Self::Cloneable {
117        self
118    }
119
120    fn into_cloneable_owned(self) -> Self::CloneableOwned {
121        self
122    }
123
124    fn dry_resolve(&mut self) {}
125
126    async fn resolve(self) -> Self::AsyncOutput {
127        self
128    }
129
130    fn reset(state: &mut Self::State) {
131        Rndr::remove_css_property(&state.0, state.1.property_name());
132    }
133}