Skip to main content

leptos_css/
custom_property.rs

1use std::{borrow::Cow, fmt, marker::PhantomData};
2
3use crate::{
4    CheckedCssValue, CheckedDeclaration, checked_value,
5    identifier::is_checked_custom_property_name, serialization::CssWriteTo,
6};
7
8/// Error returned when a custom-property name is outside the checked identifier subset.
9///
10/// Checked names must start with `--`, followed by an ASCII letter or underscore, and then only
11/// contain ASCII letters, digits, hyphens, or underscores. CSS accepts additional escaped and
12/// non-ASCII identifiers, but rejecting those forms keeps this API fail-closed without accepting
13/// an unchecked token string.
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct InvalidCustomPropertyName {
16    name: String,
17}
18
19impl InvalidCustomPropertyName {
20    /// Return the rejected name.
21    pub fn name(&self) -> &str {
22        &self.name
23    }
24}
25
26impl fmt::Display for InvalidCustomPropertyName {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(
29            f,
30            "custom property name must match --[A-Za-z_][A-Za-z0-9_-]*, got {:?}",
31            self.name
32        )
33    }
34}
35
36impl std::error::Error for InvalidCustomPropertyName {}
37
38/// A validated CSS custom property associated with one Rust value grammar.
39///
40/// The type parameter prevents ordinary checked code from using, for example, a color variable
41/// as a size. The same CSS name must not be independently constructed with two different Rust
42/// grammar types; conflicting handwritten or external declarations are outside this crate's
43/// checked boundary. Constructors are available only when `T` implements the sealed
44/// [`CheckedCssValue`] marker.
45///
46/// [CSS Custom Properties Level 1]: https://www.w3.org/TR/css-variables-1/
47#[derive(Debug, PartialEq, Eq, Hash)]
48pub struct CssCustomProperty<T> {
49    name: Cow<'static, str>,
50    marker: PhantomData<fn() -> T>,
51}
52
53impl<T> Clone for CssCustomProperty<T> {
54    fn clone(&self) -> Self {
55        Self {
56            name: self.name.clone(),
57            marker: PhantomData,
58        }
59    }
60}
61
62impl<T: CheckedCssValue> CssCustomProperty<T> {
63    /// Construct a checked custom property from a static name.
64    ///
65    /// This constructor is const and therefore suitable for module-level declarations. Prefer the
66    /// [`css_custom_property`](crate::css_custom_property) macro for compile-time-checked literals.
67    ///
68    /// # Panics
69    ///
70    /// Const evaluation fails if `name` is outside the checked identifier subset.
71    #[track_caller]
72    pub const fn from_static(name: &'static str) -> Self {
73        assert!(
74            is_checked_custom_property_name(name),
75            "invalid checked CSS custom-property name"
76        );
77        Self {
78            name: Cow::Borrowed(name),
79            marker: PhantomData,
80        }
81    }
82
83    /// Construct a checked custom property.
84    ///
85    /// # Panics
86    ///
87    /// Panics if `name` is not in the checked custom-property identifier subset. Use
88    /// [`CssCustomProperty::try_new`] for runtime-derived names.
89    #[track_caller]
90    pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
91        Self::try_new(name).unwrap_or_else(|error| panic!("{error}"))
92    }
93
94    /// Attempt to construct a checked custom property.
95    pub fn try_new(name: impl Into<Cow<'static, str>>) -> Result<Self, InvalidCustomPropertyName> {
96        let name = name.into();
97        if is_checked_custom_property_name(&name) {
98            Ok(Self {
99                name,
100                marker: PhantomData,
101            })
102        } else {
103            Err(InvalidCustomPropertyName {
104                name: name.into_owned(),
105            })
106        }
107    }
108
109    /// Return the validated, case-sensitive CSS custom-property name.
110    pub fn as_str(&self) -> &str {
111        &self.name
112    }
113
114    /// Assign a checked value to this custom property.
115    ///
116    /// The value may be a literal of `T` or a typed [`crate::var`] reference with the same
117    /// grammar. Arbitrary custom-property token streams are intentionally unsupported.
118    pub fn declare(&self, value: impl Into<DeclarationValue<T>>) -> CheckedDeclaration {
119        CheckedDeclaration::new(self.name.clone(), value.into())
120    }
121}
122
123/// Declare a reusable, statically named typed CSS custom property.
124///
125/// The name is checked during const evaluation and the resulting value carries the declared Rust
126/// grammar type.
127///
128/// ```rust
129/// use leptos_css::{CssColor, css_custom_property};
130///
131/// css_custom_property!(ACCENT_COLOR: CssColor = "--accent-color");
132/// assert_eq!(ACCENT_COLOR.as_str(), "--accent-color");
133/// ```
134///
135/// Invalid literals fail during const evaluation:
136///
137/// ```compile_fail
138/// use leptos_css::{CssColor, css_custom_property};
139///
140/// css_custom_property!(ACCENT_COLOR: CssColor = "accent-color");
141/// ```
142#[macro_export]
143macro_rules! css_custom_property {
144    ($(#[$meta:meta])* $vis:vis $name:ident : $value:ty = $css_name:literal $(;)?) => {
145        $(#[$meta])*
146        $vis const $name: $crate::CssCustomProperty<$value> =
147            $crate::CssCustomProperty::from_static($css_name);
148    };
149}
150
151impl<T: CheckedCssValue> fmt::Display for CssCustomProperty<T> {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.write_str(self.as_str())
154    }
155}
156
157/// A checked literal or a typed custom-property reference for one CSS grammar.
158///
159/// The representation is private so callers cannot construct an untyped variable reference or
160/// raw fallback token stream. Public conversions are available only for [`CheckedCssValue`]
161/// grammars.
162#[derive(Clone, Debug, PartialEq)]
163pub struct DeclarationValue<T>(DeclarationValueKind<T>);
164
165#[derive(Clone, Debug, PartialEq)]
166enum DeclarationValueKind<T> {
167    Literal(T),
168    Variable(CssVariableReference<T>),
169}
170
171impl<T: CheckedCssValue> From<T> for DeclarationValue<T> {
172    fn from(value: T) -> Self {
173        Self(DeclarationValueKind::Literal(value))
174    }
175}
176
177/// A typed `var()` reference with a mandatory, grammar-matching fallback.
178#[derive(Clone, Debug, PartialEq)]
179pub struct CssVariableReference<T> {
180    property: CssCustomProperty<T>,
181    fallback: Box<DeclarationValue<T>>,
182}
183
184impl<T: CheckedCssValue> From<CssVariableReference<T>> for DeclarationValue<T> {
185    fn from(value: CssVariableReference<T>) -> Self {
186        Self(DeclarationValueKind::Variable(value))
187    }
188}
189
190impl<T: CheckedCssValue> checked_value::sealed::Sealed for DeclarationValue<T> {}
191
192impl<T: CheckedCssValue> checked_value::sealed::Sealed for CssVariableReference<T> {}
193
194impl<T: CheckedCssValue> CssWriteTo for DeclarationValue<T> {
195    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
196        match &self.0 {
197            DeclarationValueKind::Literal(value) => value.css_fmt(w),
198            DeclarationValueKind::Variable(value) => value.css_fmt(w),
199        }
200    }
201}
202
203impl<T: CheckedCssValue> CssWriteTo for CssVariableReference<T> {
204    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
205        write!(w, "var({}, ", self.property)?;
206        self.fallback.css_fmt(w)?;
207        w.write_char(')')
208    }
209}
210
211impl<T: CheckedCssValue> fmt::Display for DeclarationValue<T> {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        self.css_fmt(f)
214    }
215}
216
217impl<T: CheckedCssValue> fmt::Display for CssVariableReference<T> {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        self.css_fmt(f)
220    }
221}
222
223/// Reference a typed custom property using a mandatory fallback of the same grammar.
224///
225/// Requiring a fallback prevents an undefined custom property from invalidating the consuming
226/// declaration at computed-value time. The fallback may itself be another typed `var()` result.
227/// Both the property grammar and fallback must implement the sealed [`CheckedCssValue`] marker;
228/// [`CssWriteTo`] alone is only a serialization capability.
229///
230/// ```compile_fail
231/// use leptos_css::{CssCustomProperty, CssWriteTo, var};
232///
233/// fn reference<T: CssWriteTo>(property: &CssCustomProperty<T>, fallback: T) {
234///     let _ = var(property, fallback);
235/// }
236/// ```
237///
238/// [CSS variable substitution]: https://www.w3.org/TR/css-variables-1/#using-variables
239pub fn var<T: CheckedCssValue>(
240    property: &CssCustomProperty<T>,
241    fallback: impl Into<DeclarationValue<T>>,
242) -> CssVariableReference<T> {
243    CssVariableReference {
244        property: property.clone(),
245        fallback: Box::new(fallback.into()),
246    }
247}