leptos_css/
declaration.rs1use 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#[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 let mut rendered = String::with_capacity(32);
54 value.write_to(&mut rendered);
55 Self {
56 property,
57 value: rendered,
58 }
59 }
60
61 #[must_use]
63 pub fn property_name(&self) -> &str {
64 &self.property
65 }
66
67 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 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}