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