Skip to main content

euv_core/vdom/attribute/
impl.rs

1use super::*;
2
3/// SAFETY: `InjectedClassesCell` is only used in single-threaded WASM contexts.
4unsafe impl Sync for InjectedClassesCell {}
5
6/// Implementation of injected class tracking for CSS deduplication.
7impl InjectedClassesCell {
8    /// Returns a shared reference to the injected classes set.
9    ///
10    /// # Returns
11    ///
12    /// - `&'static HashSet<String>` - A shared reference to the global set of injected class names.
13    #[allow(static_mut_refs)]
14    pub(crate) fn get_injected_classes() -> &'static HashSet<String> {
15        unsafe { &*INJECTED_CLASSES.deref().get_0().get() }
16    }
17
18    /// Returns a mutable reference to the injected classes set.
19    ///
20    /// # Returns
21    ///
22    /// - `&'static mut HashSet<String>` - A mutable reference to the global set of injected class names.
23    #[allow(static_mut_refs)]
24    pub(crate) fn get_mut_injected_classes() -> &'static mut HashSet<String> {
25        unsafe { &mut *INJECTED_CLASSES.deref().get_0().get() }
26    }
27
28    /// Returns `true` if the given class name has already been injected into the DOM.
29    ///
30    /// Encapsulates `static mut` access so callers do not need `unsafe` blocks.
31    ///
32    /// # Arguments
33    ///
34    /// - `&str` - The CSS class name to check.
35    ///
36    /// # Returns
37    ///
38    /// - `bool` - Whether the class name has been injected.
39    pub(crate) fn is_injected(class_name: &str) -> bool {
40        Self::get_injected_classes().contains(class_name)
41    }
42
43    /// Marks a class name as injected so future calls to `is_injected` return `true`.
44    ///
45    /// Encapsulates `static mut` access so callers do not need `unsafe` blocks.
46    ///
47    /// # Arguments
48    ///
49    /// - `&str` - The CSS class name to mark as injected.
50    pub(crate) fn mark_injected(class_name: &str) {
51        Self::get_mut_injected_classes().insert(class_name.to_string());
52    }
53}
54
55/// Implementation of attribute value factory methods for reactive and merged values.
56impl AttributeValue {
57    /// Creates a reactive attribute `Self` for conditional attribute values.
58    ///
59    /// This function replaces the inline `Signal::create(...)` + `subscribe_attr(...)`
60    /// boilerplate that was previously generated by the `html!` macro for every
61    /// attribute value containing an `if` condition.
62    ///
63    /// # Arguments
64    ///
65    /// - `F: Fn() -> String + 'static` - A closure that computes the current attribute value.
66    ///   Called on initial render and whenever any signal changes.
67    ///
68    /// # Returns
69    ///
70    /// - `Self` - A `Self::Signal` backed by a `Signal<String>`
71    ///   that reactively re-evaluates the attribute value on signal updates.
72    pub fn reactive<F>(compute: F) -> Self
73    where
74        F: Fn() -> String + 'static,
75    {
76        let attr_signal: Signal<String> = Signal::create(compute());
77        Self::subscribe_attr(attr_signal, compute);
78        Self::Signal(attr_signal)
79    }
80
81    /// Merges multiple class attribute values into a single `Self`.
82    ///
83    /// Each input value is adapted into a `Self` via `IntoReactiveValue`.
84    /// `Css` values are injected into the DOM and their names are collected.
85    /// All non-empty class names are joined with spaces into a final `Text` attribute.
86    /// If any value is signal-backed, the result becomes a reactive `Signal` attribute
87    /// that re-evaluates when any constituent signal changes.
88    ///
89    /// # Arguments
90    ///
91    /// - `&[Self]` - The class attribute values to merge.
92    ///
93    /// # Returns
94    ///
95    /// - `Self` - A merged attribute value containing space-separated class names.
96    pub fn merge_class(values: &[Self]) -> Self {
97        let has_signal: bool = values
98            .iter()
99            .any(|value: &Self| matches!(value, Self::Signal(_)));
100        if has_signal {
101            let owned_values: Vec<Self> = values.to_vec();
102            let compute: Box<dyn Fn() -> String> = Box::new(move || {
103                owned_values
104                    .iter()
105                    .filter_map(|value: &Self| match value {
106                        Self::Css(css) => {
107                            css.inject_style();
108                            Some(css.get_name().to_string())
109                        }
110                        // OPT-11: `CssRef` shares the same `Css` body as the
111                        // owned `Css` variant, so the static-borrow name is
112                        // identical and the style still needs to be injected
113                        // once on first reference. Without this arm the ref
114                        // would fall through to `_ => None` and silently drop
115                        // out of the merged class list — the regression that
116                        // wiped every multi-class CssRef entry (e.g. the
117                        // `c_binding_slider` class next to a parameterized
118                        // `c_slider_value("30%")` on the same `<input>`).
119                        Self::CssRef(css) => {
120                            css.inject_style();
121                            Some(css.get_name().to_string())
122                        }
123                        Self::Text(text_value) => Some(text_value.clone()),
124                        Self::Signal(signal) => Some(signal.get()),
125                        _ => None,
126                    })
127                    .filter(|segment: &String| !segment.is_empty())
128                    .collect::<Vec<String>>()
129                    .join(&CHAR_SPACE.to_string())
130            });
131            let attr_signal: Signal<String> = Signal::create(compute());
132            Self::subscribe_attr(attr_signal, compute);
133            return Self::Signal(attr_signal);
134        }
135        let result: String = values
136            .iter()
137            .filter_map(|value: &Self| match value {
138                Self::Css(css) => {
139                    css.inject_style();
140                    Some(css.get_name().to_string())
141                }
142                // OPT-11: see the matching arm in the signal branch above.
143                Self::CssRef(css) => {
144                    css.inject_style();
145                    Some(css.get_name().to_string())
146                }
147                Self::Text(text_value) => Some(text_value.clone()),
148                _ => None,
149            })
150            .filter(|segment: &String| !segment.is_empty())
151            .collect::<Vec<String>>()
152            .join(&CHAR_SPACE.to_string());
153        Self::Text(result)
154    }
155
156    /// Merges multiple style attribute values into a single `Self`.
157    ///
158    /// Each input value is expected to be a style string (`Text`) or a reactive
159    /// `Signal<String>` producing a style string. All non-empty style strings are
160    /// joined with spaces into a final combined style attribute.
161    /// If any value is signal-backed, the result becomes a reactive `Signal` attribute.
162    ///
163    /// # Arguments
164    ///
165    /// - `&[Self]` - The style attribute values to merge.
166    ///
167    /// # Returns
168    ///
169    /// - `Self` - A merged attribute value containing the combined CSS style string.
170    pub fn merge_style(values: &[Self]) -> Self {
171        let has_signal: bool = values
172            .iter()
173            .any(|value: &Self| matches!(value, Self::Signal(_)));
174        if has_signal {
175            let owned_values: Vec<Self> = values.to_vec();
176            let compute: Box<dyn Fn() -> String> = Box::new(move || {
177                owned_values
178                    .iter()
179                    .filter_map(|value: &Self| match value {
180                        Self::Text(text_value) => Some(text_value.clone()),
181                        Self::Signal(signal) => Some(signal.get()),
182                        _ => None,
183                    })
184                    .filter(|segment: &String| !segment.is_empty())
185                    .collect::<Vec<String>>()
186                    .join(&CHAR_SPACE.to_string())
187            });
188            let attr_signal: Signal<String> = Signal::create(compute());
189            Self::subscribe_attr(attr_signal, compute);
190            return Self::Signal(attr_signal);
191        }
192        let result: String = values
193            .iter()
194            .filter_map(|value: &Self| match value {
195                Self::Text(text_value) => Some(text_value.clone()),
196                _ => None,
197            })
198            .filter(|segment: &String| !segment.is_empty())
199            .collect::<Vec<String>>()
200            .join(&CHAR_SPACE.to_string());
201        Self::Text(result)
202    }
203
204    /// Subscribes an attribute signal to the global signal update dispatch cycle.
205    ///
206    /// Creates a callback that re-computes the attribute value and sets
207    /// it on the signal whenever a signal update cycle runs. The callback
208    /// is registered in the signal update registry using the signal's
209    /// inner address as the key.
210    ///
211    /// # Arguments
212    ///
213    /// - `Signal<String>` - The attribute signal to subscribe.
214    /// - `F: Fn() -> String + 'static` - A closure that computes the current attribute value string.
215    fn subscribe_attr<F>(attr_signal: Signal<String>, compute: F)
216    where
217        F: Fn() -> String + 'static,
218    {
219        Registry::register_attr_listener(
220            attr_signal.get_inner(),
221            Box::new(move || {
222                attr_signal.set(compute());
223            }),
224        );
225    }
226
227    /// Converts a bool signal into a reactive `Signal<String>` attribute value.
228    ///
229    /// Creates a `Signal<String>` initialized with the bool's string
230    /// representation, then subscribes to the source signal so that
231    /// whenever the bool changes, the string signal is updated accordingly.
232    ///
233    /// # Arguments
234    ///
235    /// - `Signal<bool>` - The source boolean signal.
236    ///
237    /// # Returns
238    ///
239    /// - `AttributeValue` - An `AttributeValue::Signal` wrapping the derived string signal.
240    pub(crate) fn bool_to_attr(source: Signal<bool>) -> AttributeValue {
241        let string_signal: Signal<String> = Signal::create(source.get().to_string());
242        let string_signal_clone: Signal<String> = string_signal;
243        let source_for_sub: Signal<bool> = source;
244        source_for_sub.subscribe(move || {
245            string_signal_clone.set(source_for_sub.get().to_string());
246        });
247        // The closure above captures `string_signal_clone` (which aliases
248        // `string_signal`), so `source` now transitively keeps the bridge
249        // alive. Register that dependency so the bridge's heap allocation
250        // can be reclaimed once `source` is deactivated.
251        BridgeRefsCell::track(string_signal.get_inner(), source_for_sub.get_inner());
252        AttributeValue::Signal(string_signal)
253    }
254}
255
256/// Visual equality comparison for attribute values.
257///
258/// Compares values by their visual output rather than identity. `Signal`
259/// values are compared by their current resolved string; when both signals
260/// share the same inner pointer, they are always considered **unequal**
261/// because the signal may have mutated between VDOM snapshots and `.get()`
262/// would return the same current value for both, masking the change.
263/// `Event` values are always considered equal (re-binding is handled by the
264/// handler registry), and `Css` values are compared by class name.
265impl PartialEq for AttributeValue {
266    /// Compares two attribute values for visual equality.
267    ///
268    /// # Arguments
269    ///
270    /// - `&Self` - The first attribute value.
271    /// - `&Self` - The second attribute value.
272    ///
273    /// # Returns
274    ///
275    /// - `bool` - `true` if the values are visually equal.
276    fn eq(&self, other: &Self) -> bool {
277        match (self, other) {
278            (Self::Text(old_value), Self::Text(new_value)) => old_value == new_value,
279            (Self::Signal(old_signal), Self::Signal(new_signal)) => {
280                if old_signal.get_inner() == new_signal.get_inner() {
281                    return false;
282                }
283                old_signal.get() == new_signal.get()
284            }
285            (Self::Signal(old_signal), Self::Text(new_value)) => old_signal.get() == *new_value,
286            (Self::Text(old_value), Self::Signal(new_signal)) => *old_value == new_signal.get(),
287            (Self::Event(_), Self::Event(_)) => true,
288            (Self::Css(old_class), Self::Css(new_class)) => {
289                old_class.get_name() == new_class.get_name()
290            }
291            (Self::Dynamic(old_dynamic), Self::Dynamic(new_dynamic)) => old_dynamic == new_dynamic,
292            _ => false,
293        }
294    }
295}
296
297/// Visual equality comparison for attribute entries.
298///
299/// Two attribute entries are equal when their names match and their values
300/// are visually equal as defined by `AttributeValue::eq`.
301impl PartialEq for AttributeEntry {
302    /// Compares two attribute entries for visual equality.
303    ///
304    /// # Arguments
305    ///
306    /// - `&Self` - The first attribute entry.
307    /// - `&Self` - The second attribute entry.
308    ///
309    /// # Returns
310    ///
311    /// - `bool` - `true` if both names and values match.
312    fn eq(&self, other: &Self) -> bool {
313        self.get_name() == other.get_name() && self.get_value() == other.get_value()
314    }
315}
316
317/// Visual equality comparison for CSS classes.
318///
319/// Two CSS classes are considered equal when their class names match,
320/// since the name uniquely identifies the visual style rule.
321impl PartialEq for Css {
322    /// Compares two CSS classes by name.
323    ///
324    /// # Arguments
325    ///
326    /// - `&Self` - The first CSS class.
327    /// - `&Self` - The second CSS class.
328    ///
329    /// # Returns
330    ///
331    /// - `bool` - `true` if the class names match.
332    fn eq(&self, other: &Self) -> bool {
333        self.get_name() == other.get_name()
334    }
335}
336
337/// Implementation of Css construction and style injection.
338impl Css {
339    /// Parses pseudo-class/pseudo-element rules from a compact serialization string.
340    ///
341    /// The serialization format is: `:selector { key: value; key: value; }:another { ... }`
342    /// This is used by the `class!` macro for fully static class definitions
343    /// where pseudo rules can be computed at compile time.
344    ///
345    /// # Arguments
346    ///
347    /// - `I: AsRef<str>` - The serialized pseudo rules string.
348    ///
349    /// # Returns
350    ///
351    /// - `Vec<PseudoRule>` - The parsed pseudo rules.
352    pub fn parse_pseudo_rules<I>(input: I) -> Vec<PseudoRule>
353    where
354        I: AsRef<str>,
355    {
356        let mut remaining: &str = input.as_ref();
357        let mut rules: Vec<PseudoRule> = Vec::new();
358        while !remaining.is_empty() {
359            let selector_end: Option<usize> = remaining.find(CSS_RULE_OPEN);
360            let Some(selector_end_index) = selector_end else {
361                break;
362            };
363            let selector: &str = &remaining[..selector_end_index];
364            let after_selector: &str = remaining[selector_end_index..]
365                .strip_prefix(CSS_RULE_OPEN)
366                .unwrap_or_default();
367            let style_end: Option<usize> = after_selector.find(CHAR_CSS_RULE_CLOSE);
368            let Some(style_end_index) = style_end else {
369                break;
370            };
371            let style: &str = &after_selector[..style_end_index];
372            if !selector.is_empty() && !style.is_empty() {
373                rules.push(PseudoRule::new(selector.to_string(), style.to_string()));
374            }
375            remaining = after_selector[style_end_index..]
376                .strip_prefix(CHAR_CSS_RULE_CLOSE)
377                .unwrap_or_default();
378        }
379        rules
380    }
381
382    /// Parses media query rules from a compact serialization string.
383    ///
384    /// The serialization format is:
385    /// `@media query { key: value; ::selector { key: value; } }@media query2 { ... }`
386    /// This is used by the `class!` macro for fully static class definitions
387    /// where media rules can be computed at compile time.
388    /// Supports nested pseudo-element blocks inside media query blocks.
389    ///
390    /// # Arguments
391    ///
392    /// - `S: AsRef<str>` - The serialized media rules string.
393    ///
394    /// # Returns
395    ///
396    /// - `Vec<MediaRule>` - The parsed media rules.
397    pub fn parse_media_rules<S>(input: S) -> Vec<MediaRule>
398    where
399        S: AsRef<str>,
400    {
401        let input: &str = input.as_ref();
402        let mut rules: Vec<MediaRule> = Vec::new();
403        let mut remaining: &str = input;
404        while !remaining.is_empty() {
405            if !remaining.starts_with(CSS_MEDIA_PREFIX) {
406                break;
407            }
408            let after_prefix: &str = remaining.strip_prefix(CSS_MEDIA_PREFIX).unwrap_or_default();
409            let query_end: Option<usize> = after_prefix.find(CSS_RULE_OPEN);
410            let Some(query_end_index) = query_end else {
411                break;
412            };
413            let query: &str = &after_prefix[..query_end_index];
414            let after_query: &str = after_prefix[query_end_index..]
415                .strip_prefix(CSS_RULE_OPEN)
416                .unwrap_or_default();
417            let mut depth: usize = 1;
418            let mut close_pos: usize = 0;
419            for (index, char_value) in after_query.char_indices() {
420                if char_value == '{' {
421                    depth += 1;
422                } else if char_value == '}' {
423                    depth -= 1;
424                    if depth == 0 {
425                        close_pos = index;
426                        break;
427                    }
428                }
429            }
430            if close_pos == 0 {
431                break;
432            }
433            let body: &str = &after_query[..close_pos];
434            let (style, pseudo_rules): (String, Vec<PseudoRule>) = Self::parse_media_body(body);
435            if !query.is_empty() && (!style.is_empty() || !pseudo_rules.is_empty()) {
436                rules.push(MediaRule::new(query.to_string(), style, pseudo_rules));
437            }
438            remaining = after_query[close_pos..]
439                .strip_prefix(CHAR_CSS_RULE_CLOSE)
440                .unwrap_or_default();
441        }
442        rules
443    }
444
445    /// Parses the body of a media rule, separating top-level style declarations
446    /// from nested pseudo-element blocks.
447    ///
448    /// # Arguments
449    ///
450    /// - `&str` - The media rule body content (between the outer braces).
451    ///
452    /// # Returns
453    ///
454    /// - `(String, Vec<PseudoRule>)` - A tuple of the style string and pseudo rules.
455    fn parse_media_body(body: &str) -> (String, Vec<PseudoRule>) {
456        let mut style_parts: String = String::new();
457        let mut pseudo_rules: Vec<PseudoRule> = Vec::new();
458        let mut remaining: &str = body;
459        while !remaining.is_empty() {
460            let brace_pos: Option<usize> = remaining.find('{');
461            match brace_pos {
462                Some(pos) => {
463                    let before_brace: &str = remaining[..pos].trim();
464                    if before_brace.starts_with("::") || before_brace.starts_with(':') {
465                        let selector: &str = before_brace;
466                        let after_brace: &str = &remaining[pos + 1..];
467                        let mut depth: usize = 1;
468                        let mut close_pos: usize = 0;
469                        for (index, char_value) in after_brace.char_indices() {
470                            if char_value == '{' {
471                                depth += 1;
472                            } else if char_value == '}' {
473                                depth -= 1;
474                                if depth == 0 {
475                                    close_pos = index;
476                                    break;
477                                }
478                            }
479                        }
480                        if close_pos > 0 {
481                            let inner_style: &str = after_brace[..close_pos].trim();
482                            if !selector.is_empty() && !inner_style.is_empty() {
483                                pseudo_rules.push(PseudoRule::new(
484                                    selector.to_string(),
485                                    inner_style.to_string(),
486                                ));
487                            }
488                            remaining = after_brace[close_pos + 1..].trim_start();
489                            continue;
490                        }
491                        break;
492                    } else {
493                        style_parts.push_str(before_brace);
494                        style_parts.push(' ');
495                        let after_brace: &str = &remaining[pos + 1..];
496                        let mut depth: usize = 1;
497                        let mut close_pos: usize = 0;
498                        for (index, char_value) in after_brace.char_indices() {
499                            if char_value == '{' {
500                                depth += 1;
501                            } else if char_value == '}' {
502                                depth -= 1;
503                                if depth == 0 {
504                                    close_pos = index;
505                                    break;
506                                }
507                            }
508                        }
509                        if close_pos > 0 {
510                            style_parts.push_str(after_brace[..close_pos].trim());
511                            style_parts.push(' ');
512                            remaining = after_brace[close_pos + 1..].trim_start();
513                            continue;
514                        }
515                        break;
516                    }
517                }
518                None => {
519                    style_parts.push_str(remaining.trim());
520                    break;
521                }
522            }
523        }
524        (style_parts.trim().to_string(), pseudo_rules)
525    }
526
527    /// Injects this class's styles into the DOM if not already present.
528    ///
529    /// Uses a global `HashSet` to track injected class names, avoiding the
530    /// expensive `existing_css.contains(css)` full-text search on every call.
531    /// Builds the class rule, pseudo-class rules, and media rules as CSS text,
532    /// then appends them directly to the `<style>` element via
533    /// `append_child` with a new text node — no read-modify-write of the
534    /// entire stylesheet content.
535    ///
536    /// # Panics
537    ///
538    /// Panics if `window()` or `document()` is unavailable on the current platform.
539    pub fn inject_style(&self) {
540        let class_name: &String = self.get_name();
541        if InjectedClassesCell::is_injected(class_name) {
542            return;
543        }
544        InjectedClassesCell::mark_injected(class_name);
545        let raw_name: String = self.get_name().clone();
546        let mut escaped_name: String = String::with_capacity(raw_name.len() * 2);
547        for ch in raw_name.chars() {
548            if ch.is_ascii_alphanumeric() || ch == CHAR_HYPHEN || ch == CHAR_UNDERSCORE {
549                escaped_name.push(ch);
550            } else {
551                escaped_name.push(CHAR_CSS_ESCAPE);
552                escaped_name.push(ch);
553            }
554        }
555        let mut css_text: String = format!(
556            "{CHAR_CSS_CLASS_PREFIX}{escaped_name}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
557            self.get_style()
558        );
559        for pseudo_rule in self.get_pseudo_rules() {
560            if !pseudo_rule.get_style().is_empty() {
561                css_text = format!(
562                    "{css_text}{CHAR_CSS_RULE_SEPARATOR}{CHAR_CSS_CLASS_PREFIX}{}{}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
563                    escaped_name,
564                    pseudo_rule.get_selector(),
565                    pseudo_rule.get_style()
566                );
567            }
568        }
569        for media_rule in self.get_media_rules() {
570            if !media_rule.get_query().is_empty() {
571                let mut media_body: String = format!(
572                    "{CHAR_CSS_CLASS_PREFIX}{}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
573                    escaped_name,
574                    media_rule.get_style()
575                );
576                for pseudo_rule in media_rule.get_pseudo_rules() {
577                    if !pseudo_rule.get_style().is_empty() {
578                        media_body = format!(
579                            "{media_body} {CHAR_CSS_CLASS_PREFIX}{}{}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
580                            escaped_name,
581                            pseudo_rule.get_selector(),
582                            pseudo_rule.get_style()
583                        );
584                    }
585                }
586                css_text = format!(
587                    "{css_text}{CHAR_CSS_RULE_SEPARATOR}{CSS_MEDIA_PREFIX}{}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
588                    media_rule.get_query(),
589                    media_body
590                );
591            }
592        }
593        Self::append_css(&css_text);
594    }
595
596    /// Appends CSS text directly to the shared `<style>` element.
597    ///
598    /// Creates a new text node and appends it as a child of the `<style>`
599    /// element, avoiding the read-modify-write pattern of reading the entire
600    /// `innerText`, concatenating, and setting it back.
601    ///
602    /// # Arguments
603    ///
604    /// - `&str` - The CSS text to append.
605    ///
606    fn append_css(css_text: &str) {
607        let style_id: &str = EUV_CSS_INJECTED_ID;
608        let window_value: Window = match window() {
609            Some(window_instance) => window_instance,
610            None => return,
611        };
612        let document: Document = match window_value.document() {
613            Some(document_instance) => document_instance,
614            None => return,
615        };
616        let style_element: HtmlStyleElement = match document.get_element_by_id(style_id) {
617            Some(existing_element) => match existing_element.dyn_into::<HtmlStyleElement>() {
618                Ok(element) => element,
619                Err(_err) => return,
620            },
621            None => {
622                let created: Element = match document.create_element(STYLE_TAG) {
623                    Ok(element) => element,
624                    Err(_err) => return,
625                };
626                let style_element_from_id: HtmlStyleElement =
627                    match created.dyn_into::<HtmlStyleElement>() {
628                        Ok(element) => element,
629                        Err(_err) => return,
630                    };
631                style_element_from_id.set_id(style_id);
632                if let Some(head) = document.head() {
633                    let _: Result<Node, JsValue> = head.append_child(&style_element_from_id);
634                }
635                style_element_from_id
636            }
637        };
638        if !css_text.is_empty() {
639            let text_node: Text = document.create_text_node(css_text);
640            let _: Result<Node, JsValue> = style_element.append_child(&text_node);
641        }
642    }
643
644    /// Builds a CSS style string from an array of key-value pairs.
645    ///
646    /// This function is used by the `html!` macro to convert static `style:`
647    /// attributes into a CSS string without allocating intermediate objects.
648    ///
649    /// # Arguments
650    ///
651    /// - `S: AsRef<str>` - An array of CSS property name-value pairs.
652    ///
653    /// # Returns
654    ///
655    /// - `String` - The CSS string (e.g., `"margin: 0 auto; max-width: 800px;"`).
656    pub fn style_string<K, V>(props: &[(K, V)]) -> String
657    where
658        K: AsRef<str>,
659        V: AsRef<str>,
660    {
661        props
662            .iter()
663            .map(|(key, value): &(K, V)| {
664                format!(
665                    "{}{CSS_PROP_SEPARATOR}{}{CHAR_CSS_DECL_TERMINATOR}",
666                    key.as_ref(),
667                    value.as_ref()
668                )
669            })
670            .collect::<Vec<String>>()
671            .join(&CHAR_SPACE.to_string())
672    }
673
674    /// Builds a stable suffix for a class name from a dynamic parameter value.
675    ///
676    /// Used by the `class!` macro when a parameter is wrapped in `{}` in the
677    /// class body. Wrapping a parameter opts it into value-dependent class
678    /// names, so each distinct value can inject its own CSS rule.
679    ///
680    /// # Arguments
681    ///
682    /// - `&str` - The dynamic parameter value.
683    ///
684    /// # Returns
685    ///
686    /// - `String` - A stable hexadecimal suffix for the class name.
687    pub fn param_class_name(value: &str) -> String {
688        let mut hash: u64 = CLASS_PARAM_HASH_FNV_OFFSET;
689        for byte in value.as_bytes() {
690            hash ^= u64::from(*byte);
691            hash = hash.wrapping_mul(CLASS_PARAM_HASH_FNV_PRIME);
692        }
693        format!("{hash:x}")
694    }
695
696    /// Builds a CSS style string from owned key-value pairs.
697    ///
698    /// Used by the `html!` macro for reactive style attributes (with `if`
699    /// conditions) where values are computed at runtime.
700    ///
701    /// # Arguments
702    ///
703    /// - `&[(String, String)]` - An array of owned CSS property name-value pairs.
704    ///
705    /// # Returns
706    ///
707    /// - `String` - The CSS string (e.g., `"margin: 0 auto; max-width: 800px;"`).
708    pub fn style_string_owned(props: &[(String, String)]) -> String {
709        props
710            .iter()
711            .map(|(key, value): &(String, String)| {
712                format!("{key}{CSS_PROP_SEPARATOR}{value}{CHAR_CSS_DECL_TERMINATOR}")
713            })
714            .collect::<Vec<String>>()
715            .join(&CHAR_SPACE.to_string())
716    }
717
718    /// Injects CSS text into the shared `<style>` element in the DOM.
719    ///
720    /// Delegates to [`Css::append_css`] for the actual DOM append.
721    /// Unlike the previous implementation, this does not read the existing
722    /// stylesheet content or perform a full-text `contains` search.
723    ///
724    /// # Arguments
725    ///
726    /// - `S: AsRef<str>` - The CSS text to inject (e.g., reset styles, keyframes, media queries).
727    ///
728    /// # Panics
729    ///
730    /// Panics if `window()` or `document()` is unavailable on the current platform.
731    pub fn inject_css<S>(css_text: S)
732    where
733        S: AsRef<str>,
734    {
735        let css_text: &str = css_text.as_ref();
736        Self::append_css(css_text);
737    }
738}
739
740/// Displays the CSS class name.
741///
742/// This enables `format!("{css}")` to produce the class name string,
743/// which is required for reactive `if` conditions in `class:` attributes.
744impl Display for Css {
745    /// Formats the CSS class as its name string.
746    ///
747    /// # Arguments
748    ///
749    /// - `&mut Formatter` - The formatter.
750    ///
751    /// # Returns
752    ///
753    /// - `fmt::Result` - The formatting result.
754    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
755        write!(formatter, "{}", self.get_name())
756    }
757}