Skip to main content

euv_core/vdom/attribute/
impl.rs

1use crate::*;
2
3/// Visual equality comparison for attribute values.
4///
5/// Compares values by their visual output rather than identity. `Signal`
6/// values are compared by their current resolved string, `Event` values
7/// are always considered equal (re-binding is handled by the handler
8/// registry), and `CssClass` values are compared by class name.
9impl PartialEq for AttributeValue {
10    /// Compares two attribute values for visual equality.
11    ///
12    /// # Arguments
13    ///
14    /// - `&Self` - The first attribute value.
15    /// - `&Self` - The second attribute value.
16    ///
17    /// # Returns
18    ///
19    /// - `bool` - `true` if the values are visually equal.
20    fn eq(&self, other: &Self) -> bool {
21        match (self, other) {
22            (AttributeValue::Text(old_val), AttributeValue::Text(new_val)) => old_val == new_val,
23            (AttributeValue::Signal(old_sig), AttributeValue::Signal(new_sig)) => {
24                old_sig.get() == new_sig.get()
25            }
26            (AttributeValue::Signal(old_sig), AttributeValue::Text(new_val)) => {
27                old_sig.get() == *new_val
28            }
29            (AttributeValue::Text(old_val), AttributeValue::Signal(new_sig)) => {
30                *old_val == new_sig.get()
31            }
32            (AttributeValue::Event(_), AttributeValue::Event(_)) => true,
33            (AttributeValue::Css(old_css), AttributeValue::Css(new_css)) => {
34                old_css.get_name() == new_css.get_name()
35            }
36            (AttributeValue::Dynamic(old_dyn), AttributeValue::Dynamic(new_dyn)) => {
37                old_dyn == new_dyn
38            }
39            _ => false,
40        }
41    }
42}
43
44/// Visual equality comparison for attribute entries.
45///
46/// Two attribute entries are equal when their names match and their values
47/// are visually equal as defined by `AttributeValue::eq`.
48impl PartialEq for AttributeEntry {
49    /// Compares two attribute entries for visual equality.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Self` - The first attribute entry.
54    /// - `&Self` - The second attribute entry.
55    ///
56    /// # Returns
57    ///
58    /// - `bool` - `true` if both names and values match.
59    fn eq(&self, other: &Self) -> bool {
60        self.get_name() == other.get_name() && self.get_value() == other.get_value()
61    }
62}
63
64/// Visual equality comparison for CSS classes.
65///
66/// Two CSS classes are considered equal when their class names match,
67/// since the name uniquely identifies the visual style rule.
68impl PartialEq for CssClass {
69    /// Compares two CSS classes by name.
70    ///
71    /// # Arguments
72    ///
73    /// - `&Self` - The first CSS class.
74    /// - `&Self` - The second CSS class.
75    ///
76    /// # Returns
77    ///
78    /// - `bool` - `true` if the class names match.
79    fn eq(&self, other: &Self) -> bool {
80        self.get_name() == other.get_name()
81    }
82}
83
84/// Implementation of style CSS serialization.
85impl Style {
86    /// Adds a style property.
87    ///
88    /// Property names are automatically converted from snake_case to kebab-case
89    /// (e.g., `flex_direction` becomes `flex-direction`).
90    ///
91    /// # Arguments
92    ///
93    /// - `N` - The property name (snake_case will be converted to kebab-case).
94    /// - `V` - The property value.
95    ///
96    /// # Returns
97    ///
98    /// - `Self` - This style with the property added.
99    pub fn property<N, V>(mut self, name: N, value: V) -> Self
100    where
101        N: AsRef<str>,
102        V: AsRef<str>,
103    {
104        self.get_mut_properties().push(StyleProperty::new(
105            name.as_ref().replace('_', "-"),
106            value.as_ref().to_string(),
107        ));
108        self
109    }
110
111    /// Converts the style to a CSS string.
112    ///
113    /// # Returns
114    ///
115    /// - `String` - The CSS string representation.
116    pub fn to_css_string(&self) -> String {
117        self.get_properties()
118            .iter()
119            .map(|style: &StyleProperty| format!("{}: {};", style.get_name(), style.get_value()))
120            .collect::<Vec<String>>()
121            .join(" ")
122    }
123
124    /// Builds a CSS style string from an array of key-value pairs.
125    ///
126    /// This function is used by the `html!` macro to convert static `style:`
127    /// attributes into a CSS string without allocating intermediate `Style`
128    /// and `Vec<StyleProperty>` objects. Keys are converted from snake_case
129    /// to kebab-case automatically.
130    ///
131    /// # Arguments
132    ///
133    /// - `&[(&str, &str)]` - An array of CSS property name-value pairs.
134    ///
135    /// # Returns
136    ///
137    /// - `String` - The CSS string (e.g., `"margin: 0 auto; max-width: 800px;"`).
138    pub fn create_style_string(props: &[(&str, &str)]) -> String {
139        let mut result: String = String::new();
140        for (key, value) in props {
141            if !result.is_empty() {
142                result.push(' ');
143            }
144            result.push_str(&key.replace('_', "-"));
145            result.push_str(": ");
146            result.push_str(value);
147            result.push(';');
148        }
149        result
150    }
151}
152
153/// Provides a default empty style.
154impl Default for Style {
155    /// Returns a default `Style` with no properties.
156    ///
157    /// # Returns
158    ///
159    /// - `Self` - An empty style.
160    fn default() -> Self {
161        Self::new(Vec::new())
162    }
163}
164
165/// Implementation of CssClass construction and style injection.
166impl CssClass {
167    /// Creates a new CSS class with the given name and style declarations.
168    ///
169    /// Automatically injects the styles into the DOM upon creation.
170    ///
171    /// # Arguments
172    ///
173    /// - `String` - The class name.
174    /// - `String` - The CSS style declarations.
175    ///
176    /// # Returns
177    ///
178    /// - `Self` - A new CSS class with injected styles.
179    pub fn new(name: String, style: String) -> Self {
180        let mut css_class: CssClass = CssClass::default();
181        css_class.set_name(name);
182        css_class.set_style(style);
183        css_class.inject_style();
184        css_class
185    }
186
187    /// Creates a new CSS class with the given name, style declarations, and pseudo rules.
188    ///
189    /// Automatically injects the base styles, pseudo-class/pseudo-element rules,
190    /// and media query rules into the DOM upon creation.
191    ///
192    /// # Arguments
193    ///
194    /// - `String` - The class name.
195    /// - `String` - The CSS style declarations.
196    /// - `Vec<PseudoRule>` - The pseudo-class and pseudo-element rules.
197    /// - `Vec<MediaRule>` - The media query rules.
198    ///
199    /// # Returns
200    ///
201    /// - `Self` - A new CSS class with injected styles and pseudo rules.
202    pub fn new_with_rules(
203        name: String,
204        style: String,
205        pseudo_rules: Vec<PseudoRule>,
206        media_rules: Vec<MediaRule>,
207    ) -> Self {
208        let mut css_class: CssClass = CssClass::default();
209        css_class.set_name(name);
210        css_class.set_style(style);
211        css_class.set_pseudo_rules(pseudo_rules);
212        css_class.set_media_rules(media_rules);
213        css_class.inject_style();
214        css_class
215    }
216
217    /// Parses pseudo-class/pseudo-element rules from a compact serialization string.
218    ///
219    /// The serialization format is: `:selector { key: value; key: value; }:another { ... }`
220    /// This is used by the `class!` macro for fully static class definitions
221    /// where pseudo rules can be computed at compile time.
222    ///
223    /// # Arguments
224    ///
225    /// - `&str` - The serialized pseudo rules string.
226    ///
227    /// # Returns
228    ///
229    /// - `Vec<PseudoRule>` - The parsed pseudo rules.
230    pub fn parse_pseudo_rules(input: &str) -> Vec<PseudoRule> {
231        let mut rules: Vec<PseudoRule> = Vec::new();
232        let mut remaining: &str = input;
233        while !remaining.is_empty() {
234            let selector_end: Option<usize> = remaining.find(" { ");
235            let Some(sel_end) = selector_end else {
236                break;
237            };
238            let selector: &str = &remaining[..sel_end];
239            let after_selector: &str = remaining[sel_end..].strip_prefix(" { ").unwrap_or("");
240            let style_end: Option<usize> = after_selector.find('}');
241            let Some(st_end) = style_end else {
242                break;
243            };
244            let style: &str = &after_selector[..st_end];
245            if !selector.is_empty() && !style.is_empty() {
246                rules.push(PseudoRule::new(selector.to_string(), style.to_string()));
247            }
248            remaining = after_selector[st_end..].strip_prefix('}').unwrap_or("");
249        }
250        rules
251    }
252
253    /// Parses media query rules from a compact serialization string.
254    ///
255    /// The serialization format is: `@media query { key: value; key: value; }@media query2 { ... }`
256    /// This is used by the `class!` macro for fully static class definitions
257    /// where media rules can be computed at compile time.
258    ///
259    /// # Arguments
260    ///
261    /// - `&str` - The serialized media rules string.
262    ///
263    /// # Returns
264    ///
265    /// - `Vec<MediaRule>` - The parsed media rules.
266    pub fn parse_media_rules(input: &str) -> Vec<MediaRule> {
267        let mut rules: Vec<MediaRule> = Vec::new();
268        let mut remaining: &str = input;
269        while !remaining.is_empty() {
270            if !remaining.starts_with("@media ") {
271                break;
272            }
273            let after_prefix: &str = remaining.strip_prefix("@media ").unwrap_or("");
274            let query_end: Option<usize> = after_prefix.find(" { ");
275            let Some(q_end) = query_end else {
276                break;
277            };
278            let query: &str = &after_prefix[..q_end];
279            let after_query: &str = after_prefix[q_end..].strip_prefix(" { ").unwrap_or("");
280            let style_end: Option<usize> = after_query.find('}');
281            let Some(st_end) = style_end else {
282                break;
283            };
284            let style: &str = &after_query[..st_end];
285            if !query.is_empty() && !style.is_empty() {
286                rules.push(MediaRule::new(query.to_string(), style.to_string()));
287            }
288            remaining = after_query[st_end..].strip_prefix('}').unwrap_or("");
289        }
290        rules
291    }
292
293    /// Injects this class's styles into the DOM if not already present.
294    ///
295    /// Creates a `<style>` element with id `euv-css-injected` on first call,
296    /// then appends the class rule, pseudo-class rules, and media rules.
297    /// Subsequent calls for the same class name are no-ops. On first creation,
298    /// also injects global CSS keyframes required by built-in animations.
299    ///
300    /// # Panics
301    ///
302    /// Panics if `window()` or `document()` is unavailable on the current platform.
303    pub fn inject_style(&self) {
304        #[cfg(target_arch = "wasm32")]
305        {
306            let style_id: &str = "euv-css-injected";
307            let document: Document = window()
308                .expect("no global window exists")
309                .document()
310                .expect("no document exists");
311            let style_element: HtmlStyleElement = match document.get_element_by_id(style_id) {
312                Some(el) => el.dyn_into::<HtmlStyleElement>().unwrap(),
313                None => {
314                    let el: HtmlStyleElement = document
315                        .create_element("style")
316                        .unwrap()
317                        .dyn_into::<HtmlStyleElement>()
318                        .unwrap();
319                    el.set_id(style_id);
320                    let keyframes: &str = "@keyframes euv-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } @keyframes euv-fade-in { from { opacity: 0; } to { opacity: 1; } } @keyframes euv-scale-in { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } } @keyframes euv-pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.2); } } @keyframes euv-slide-up { from { transform: translateY(100%); } to { transform: translateY(0); } } @keyframes euv-slide-left { from { transform: translateX(-100%); } to { transform: translateX(0); } } @keyframes euv-fade-in-up { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }";
321                    let global: &str = "html, body, #app { height: 100%; margin: 0; padding: 0; overflow: hidden; } * { -webkit-tap-highlight-color: transparent; }";
322                    let media_queries: &str = "@media (max-width: 767px) { .c_app_nav { display: none; } .c_app_main { padding: 20px 16px; max-width: 100%; } .c_page_title { font-size: 22px; } .c_page_subtitle { font-size: 14px; } .c_card { padding: 16px; margin: 12px 0; border-radius: 10px; } .c_card_title { font-size: 16px; } .c_form_grid { grid-template-columns: 1fr; } .c_browser_api_row { grid-template-columns: 1fr; } .c_modal_content { max-width: 100%; width: calc(100% - 32px); border-radius: 16px; max-height: 85vh; overflow-y: auto; } .c_modal_overlay { align-items: center; justify-content: center; } .c_event_stats { gap: 12px; flex-wrap: wrap; } .c_event_section_row { gap: 12px; flex-wrap: wrap; } .c_event_section_col { min-width: 100%; } .c_counter_value { font-size: 20px; } .c_timer_value { font-size: 36px; } .c_not_found_code { font-size: 56px; } .c_not_found_container { padding: 40px 20px; } .c_list_input_row { flex-direction: column; } .c_vconsole_button { bottom: 16px; right: 16px; width: 44px; height: 44px; border-radius: 12px; } .c_tab_bar { flex-wrap: wrap; } .c_primary_button { padding: 10px 18px; font-size: 14px; } .c_badge { padding: 4px 10px; font-size: 11px; } .c_badge_outline { padding: 4px 10px; font-size: 11px; } .c_browser_info_grid { grid-template-columns: 1fr; } .c_anim_spin { font-size: 36px; } .c_anim_spin_stopped { font-size: 36px; } .c_anim_pulse { font-size: 36px; } .c_anim_pulse_stopped { font-size: 36px; } }";
323                    el.set_inner_text(&format!("{} {} {}", global, keyframes, media_queries));
324                    document.head().unwrap().append_child(&el).unwrap();
325                    el
326                }
327            };
328            let existing_css: String = style_element.inner_text();
329            let class_rule: String = format!(".{} {{ {} }}", self.get_name(), self.get_style());
330            let mut new_css: String = existing_css.clone();
331            if !existing_css.contains(&class_rule) {
332                new_css = if new_css.is_empty() {
333                    class_rule
334                } else {
335                    format!("{}\n{}", new_css, class_rule)
336                };
337            }
338            for pseudo_rule in self.get_pseudo_rules() {
339                let pseudo_rule_str: String = format!(
340                    ".{}{} {{ {} }}",
341                    self.get_name(),
342                    pseudo_rule.get_selector(),
343                    pseudo_rule.get_style()
344                );
345                if !pseudo_rule.get_style().is_empty() && !existing_css.contains(&pseudo_rule_str) {
346                    new_css = if new_css.is_empty() {
347                        pseudo_rule_str
348                    } else {
349                        format!("{}\n{}", new_css, pseudo_rule_str)
350                    };
351                }
352            }
353            for media_rule in self.get_media_rules() {
354                let media_rule_str: String = format!(
355                    "@media {} {{ .{} {{ {} }} }}",
356                    media_rule.get_query(),
357                    self.get_name(),
358                    media_rule.get_style()
359                );
360                if !media_rule.get_query().is_empty() && !existing_css.contains(&media_rule_str) {
361                    new_css = if new_css.is_empty() {
362                        media_rule_str
363                    } else {
364                        format!("{}\n{}", new_css, media_rule_str)
365                    };
366                }
367            }
368            if new_css != existing_css {
369                style_element.set_inner_text(&new_css);
370            }
371        }
372    }
373}
374
375/// Displays the CSS class name.
376///
377/// This enables `format!("{}", css_class)` to produce the class name string,
378/// which is required for reactive `if` conditions in `class:` attributes.
379impl std::fmt::Display for CssClass {
380    /// Formats the CSS class as its name string.
381    ///
382    /// # Arguments
383    ///
384    /// - `&mut Formatter` - The formatter.
385    ///
386    /// # Returns
387    ///
388    /// - `std::fmt::Result` - The formatting result.
389    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390        write!(f, "{}", self.get_name())
391    }
392}