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