euv_core/vdom/attribute/impl.rs
1use super::*;
2
3/// Implementation of the public read side of an attribute entry.
4impl AttributeEntry {
5 /// Returns the CSS class names this attribute carries.
6 ///
7 /// The `class` attribute is the one place where a component's
8 /// styling decisions become observable, so it needs a public read
9 /// side: a component library's tests have to be able to assert
10 /// that a state actually landed on the right class, and an external
11 /// crate cannot read the raw attribute value.
12 ///
13 /// Every shape the attribute can take is reported:
14 /// `Css` and `CssRef` contribute the class name they carry, `Text`
15 /// and `StaticText` contribute their string split on whitespace,
16 /// a `Signal` contributes the class list it currently holds — that
17 /// is the shape a reactive `class:` attribute takes — and the
18 /// remaining shapes, an event handler, contribute nothing, because
19 /// neither is a class list.
20 ///
21 /// # Returns
22 ///
23 /// - `Vec<String>` - The class names, in the order they appear.
24 pub fn class_names(&self) -> Vec<String> {
25 match self.get_value() {
26 AttributeValue::Css(css) => vec![css.get_name().clone()],
27 AttributeValue::CssRef(css) => vec![css.get_name().clone()],
28 AttributeValue::Text(text) => split_class_names(text),
29 AttributeValue::StaticText(text) => split_class_names(text),
30 AttributeValue::Signal(signal) => signal.with(|text: &String| split_class_names(text)),
31 _ => Vec::new(),
32 }
33 }
34
35 /// Returns the attribute's value as text, when it carries one.
36 ///
37 /// A `Text` or `StaticText` attribute is its own value; a `Css` or
38 /// `CssRef` attribute contributes its class name, because that is
39 /// the text the browser ends up showing for it. The remaining
40 /// shapes — a reactive signal, an event handler — carry no text.
41 ///
42 /// # Returns
43 ///
44 /// - `Option<String>` - The value, when the attribute has one.
45 pub fn text_value(&self) -> Option<String> {
46 match self.get_value() {
47 AttributeValue::Text(text) => Some(text.clone()),
48 AttributeValue::StaticText(text) => Some((*text).to_string()),
49 AttributeValue::Css(css) => Some(css.get_name().clone()),
50 AttributeValue::CssRef(css) => Some(css.get_name().clone()),
51 _ => None,
52 }
53 }
54
55 /// Returns the markup an `inner_html` attribute carries.
56 ///
57 /// An `inner_html` attribute is a payload the renderer writes into
58 /// the element, not a text the reader sees, so `text_value` does
59 /// not report it. A consumer that needs to know what the payload
60 /// says — a component that inlines a rendered diagram, a test that
61 /// pins what the payload contains — reads it here. The reactive
62 /// shape reports the markup it currently holds.
63 ///
64 /// # Returns
65 ///
66 /// - `Option<String>` - The markup, when the attribute is an
67 /// `inner_html` attribute.
68 pub fn inner_html_value(&self) -> Option<String> {
69 match self.get_value() {
70 AttributeValue::InnerHtml(html) => Some(html.clone()),
71 AttributeValue::InnerHtmlSignal(signal) => {
72 Some(signal.with(|html: &String| html.clone()))
73 }
74 _ => None,
75 }
76 }
77}
78
79/// Implementation of injected class tracking for CSS deduplication.
80impl InjectedClassesCell {
81 /// Returns `true` if the given class name has already been injected into
82 /// the DOM.
83 ///
84 /// # Arguments
85 ///
86 /// - `&str` - The CSS class name to check.
87 ///
88 /// # Returns
89 ///
90 /// - `bool` - Whether the class name has been injected.
91 pub(crate) fn is_injected(class_name: &str) -> bool {
92 INJECTED_CLASSES
93 .read()
94 .map(|classes: RwLockReadGuard<'_, HashSet<String>>| classes.contains(class_name))
95 .unwrap_or(false)
96 }
97
98 /// Marks a class name as injected so future calls to `is_injected`
99 /// return `true`.
100 ///
101 /// A poisoned lock (which only happens if another thread panicked while
102 /// holding the write guard) is recovered from rather than propagated:
103 /// the set is deduplication bookkeeping, so losing a lock must never
104 /// take down the render path.
105 ///
106 /// # Arguments
107 ///
108 /// - `&str` - The CSS class name to mark as injected.
109 pub(crate) fn mark_injected(class_name: &str) {
110 let write_result: Result<
111 InjectedClassesWriteGuard<'_>,
112 PoisonError<InjectedClassesWriteGuard<'_>>,
113 > = INJECTED_CLASSES.write();
114 let Ok(mut classes) = write_result else {
115 return;
116 };
117 classes.insert(class_name.to_string());
118 }
119}
120
121/// Implementation of attribute value factory methods for reactive and merged values.
122impl AttributeValue {
123 /// Creates a reactive attribute `Self` for conditional attribute values.
124 ///
125 /// This function replaces the inline `Signal::create(...)` boilerplate
126 /// that was previously generated by the `html!` macro for every
127 /// attribute value containing an `if` condition.
128 ///
129 /// The returned `Self::Text` is a snapshot computed on each render of
130 /// the enclosing dynamic node: the signals read inside
131 /// `compute` during that render register the dynamic node as their
132 /// dependent, so any source change re-renders the node and rebuilds
133 /// this attribute with the new value. No signal slot or registry
134 /// listener is allocated for the snapshot. Direct `Self::Signal`
135 /// bindings retain their independent DOM subscription behavior.
136 ///
137 /// # Arguments
138 ///
139 /// - `F` - A closure that computes the current attribute value.
140 /// Called once per render of the enclosing dynamic node.
141 ///
142 /// # Returns
143 ///
144 /// - `Self` - A `Self::Text` carrying the freshly computed value.
145 pub fn reactive<F>(compute: F) -> Self
146 where
147 F: Fn() -> String + 'static,
148 {
149 Self::Text(compute())
150 }
151
152 /// Merges multiple class attribute values into a single `Self`.
153 ///
154 /// Each input value is adapted into a `Self` via `IntoReactiveValue`.
155 /// `Css` values are injected into the DOM and their names are collected.
156 /// All non-empty class names are joined with spaces into a final `Text` attribute.
157 /// Signal inputs are read without allocating a new signal for the
158 /// merged snapshot. The enclosing dynamic node re-renders on any
159 /// constituent signal change (see
160 /// [`AttributeValue::reactive`]).
161 ///
162 /// # Arguments
163 ///
164 /// - `&[Self]` - The class attribute values to merge.
165 ///
166 /// # Returns
167 ///
168 /// - `Self` - A merged attribute value containing space-separated class names.
169 pub fn merge_class(values: &[Self]) -> Self {
170 Self::Text(Self::join_class_segments(values))
171 }
172
173 /// Joins class attribute values into a single space-separated string.
174 ///
175 /// Appends borrowed segments directly to the result. Signal snapshots
176 /// stay borrowed through `with`, avoiding an owned string clone for
177 /// every reactive segment on every render.
178 ///
179 /// OPT-11: both `Css` and `CssRef` arms inject the style on first
180 /// reference. Without the `CssRef` arm the ref would fall through
181 /// to `_ => None` and silently drop out of the merged class list —
182 /// the regression that wiped every multi-class CssRef entry (e.g.
183 /// the `c_binding_slider` class next to a parameterized
184 /// `c_slider_value("30%")` on the same `<input>`).
185 ///
186 /// # Arguments
187 ///
188 /// - `&[Self]` - The class attribute values to merge, in order.
189 ///
190 /// # Returns
191 ///
192 /// - `String` - The merged class list, segments separated by a
193 /// single space; empty when no segment survived filtering.
194 fn join_class_segments(values: &[Self]) -> String {
195 let mut joined: String = String::with_capacity(Self::segments_capacity(values, true));
196 for value in values {
197 match value {
198 Self::Css(css) => {
199 css.inject_style();
200 Self::append_segment(&mut joined, css.get_name());
201 }
202 Self::CssRef(css) => {
203 css.inject_style();
204 Self::append_segment(&mut joined, css.get_name());
205 }
206 Self::Text(text_value) => {
207 Self::append_segment(&mut joined, text_value);
208 }
209 Self::Signal(signal) => {
210 signal.with(|text: &String| Self::append_segment(&mut joined, text));
211 }
212 _ => {}
213 }
214 }
215 joined
216 }
217
218 /// Computes the output byte capacity without copying signal payloads.
219 ///
220 /// # Arguments
221 ///
222 /// - `&[Self]` - Input segments whose supported nonempty values are counted.
223 /// - `bool` - Whether CSS class references are accepted by the merge.
224 ///
225 /// # Returns
226 ///
227 /// - `usize` - Required bytes including separators between nonempty segments.
228 fn segments_capacity(values: &[Self], classes: bool) -> usize {
229 let mut capacity: usize = 0;
230 for value in values {
231 let size: usize = match value {
232 Self::Css(css) if classes => css.get_name().len(),
233 Self::CssRef(css) if classes => css.get_name().len(),
234 Self::Text(text) => text.len(),
235 Self::Signal(signal) => signal.with(String::len),
236 _ => 0,
237 };
238 if size > 0 {
239 if capacity > 0 {
240 capacity += CHAR_SPACE.len();
241 }
242 capacity += size;
243 }
244 }
245 capacity
246 }
247
248 /// Appends a nonempty segment, separating it from preceding segments.
249 ///
250 /// # Arguments
251 ///
252 /// - `&mut String` - The destination string.
253 /// - `&str` - The borrowed segment to append.
254 fn append_segment(joined: &mut String, segment: &str) {
255 if segment.is_empty() {
256 return;
257 }
258 if !joined.is_empty() {
259 joined.push_str(CHAR_SPACE);
260 }
261 joined.push_str(segment);
262 }
263
264 /// Merges multiple style attribute values into a single `Self`.
265 ///
266 /// Each input value is expected to be a style string (`Text`) or a reactive
267 /// `Signal<String>` producing a style string. All non-empty style strings are
268 /// joined with spaces into a final combined style attribute.
269 /// Signal inputs are read without allocating a new signal for the
270 /// merged snapshot. The enclosing dynamic node re-renders on any
271 /// constituent signal change (see
272 /// [`AttributeValue::reactive`]).
273 ///
274 /// # Arguments
275 ///
276 /// - `&[Self]` - The style attribute values to merge.
277 ///
278 /// # Returns
279 ///
280 /// - `Self` - A merged attribute value containing the combined CSS style string.
281 pub fn merge_style(values: &[Self]) -> Self {
282 Self::Text(Self::join_style_segments(values))
283 }
284
285 /// Joins style attribute values into a single space-separated string.
286 ///
287 /// Borrows signal values without allocating intermediate snapshots,
288 /// using the same separator and empty-segment rules as class merging.
289 ///
290 /// # Arguments
291 ///
292 /// - `&[Self]` - The style attribute values to merge, in order.
293 ///
294 /// # Returns
295 ///
296 /// - `String` - The merged CSS declarations, segments separated by a
297 /// single space; empty when no segment carried a declaration.
298 fn join_style_segments(values: &[Self]) -> String {
299 let mut joined: String = String::with_capacity(Self::segments_capacity(values, false));
300 for value in values {
301 match value {
302 Self::Text(text_value) => {
303 Self::append_segment(&mut joined, text_value);
304 }
305 Self::Signal(signal) => {
306 signal.with(|text: &String| Self::append_segment(&mut joined, text));
307 }
308 _ => {}
309 }
310 }
311 joined
312 }
313
314 /// Converts a bool signal into a reactive boolean attribute value.
315 ///
316 /// Produces `AttributeValue::BoolSignal` directly: the renderer writes
317 /// `"true"` / `"false"` and subscribes the source signal to the element
318 /// with no intermediate mapping signal (the previous `Signal<String>`
319 /// bridge) and no per-render subscription.
320 ///
321 /// # Arguments
322 ///
323 /// - `Signal<bool>` - The source boolean signal.
324 ///
325 /// # Returns
326 ///
327 /// - `AttributeValue` - A `BoolSignal` wrapping the source signal.
328 pub(crate) fn bool_to_attr(source: Signal<bool>) -> AttributeValue {
329 AttributeValue::BoolSignal(source)
330 }
331}
332
333/// Visual equality comparison for attribute values.
334///
335/// Compares values by their visual output rather than identity. `Signal`
336/// values are compared by their current resolved string (borrow-compared
337/// via `Signal::with`, no `String` clones); when both signals share the
338/// same slab slot, they are always considered **unequal** — the patch walk
339/// recognises that case separately and skips the DOM write because the
340/// mount-time signal binding already owns the attribute's DOM value (see
341/// `patch_attributes`), while the unequal verdict keeps `visual_eq` from
342/// masking a value change between VDOM snapshots.
343/// `Event` values are always considered equal (re-binding is handled by the
344/// handler registry), and `Css` values are compared by class name.
345impl PartialEq for AttributeValue {
346 /// Compares two attribute values for visual equality.
347 ///
348 /// # Arguments
349 ///
350 /// - `&Self` - The first attribute value.
351 /// - `&Self` - The second attribute value.
352 ///
353 /// # Returns
354 ///
355 /// - `bool` - `true` if the values are visually equal.
356 fn eq(&self, other: &Self) -> bool {
357 match (self, other) {
358 (Self::Text(old_value), Self::Text(new_value)) => old_value == new_value,
359 (Self::StaticText(old_value), Self::StaticText(new_value)) => old_value == new_value,
360 (Self::Text(old_value), Self::StaticText(new_value)) => old_value == new_value,
361 (Self::StaticText(old_value), Self::Text(new_value)) => old_value == new_value,
362 (Self::Signal(old_signal), Self::Signal(new_signal)) => {
363 if old_signal.get_inner() == new_signal.get_inner() {
364 return false;
365 }
366 old_signal.with(|old_value: &String| {
367 new_signal.with(|new_value: &String| old_value == new_value)
368 })
369 }
370 (Self::Signal(old_signal), Self::Text(new_value)) => {
371 old_signal.with(|old_value: &String| old_value == new_value)
372 }
373 (Self::Text(old_value), Self::Signal(new_signal)) => {
374 new_signal.with(|new_value: &String| old_value == new_value)
375 }
376 (Self::BoolSignal(old_signal), Self::BoolSignal(new_signal)) => {
377 if old_signal.get_inner() == new_signal.get_inner() {
378 return false;
379 }
380 old_signal.get() == new_signal.get()
381 }
382 (Self::Event(_), Self::Event(_)) => true,
383 (Self::Css(old_class), Self::Css(new_class)) => {
384 old_class.get_name() == new_class.get_name()
385 }
386 (Self::CssRef(old_class), Self::CssRef(new_class)) => {
387 old_class.get_name() == new_class.get_name()
388 }
389 (Self::CssRef(old_class), Self::Css(new_class)) => {
390 old_class.get_name() == new_class.get_name()
391 }
392 (Self::Css(old_class), Self::CssRef(new_class)) => {
393 old_class.get_name() == new_class.get_name()
394 }
395 (Self::Dynamic(old_dynamic), Self::Dynamic(new_dynamic)) => old_dynamic == new_dynamic,
396 _ => false,
397 }
398 }
399}
400
401/// Visual equality comparison for attribute entries.
402///
403/// Two attribute entries are equal when their names match and their values
404/// are visually equal as defined by `AttributeValue::eq`.
405impl PartialEq for AttributeEntry {
406 /// Compares two attribute entries for visual equality.
407 ///
408 /// # Arguments
409 ///
410 /// - `&Self` - The first attribute entry.
411 /// - `&Self` - The second attribute entry.
412 ///
413 /// # Returns
414 ///
415 /// - `bool` - `true` if both names and values match.
416 fn eq(&self, other: &Self) -> bool {
417 self.get_name() == other.get_name() && self.get_value() == other.get_value()
418 }
419}
420
421/// Visual equality comparison for CSS classes.
422///
423/// Two CSS classes are considered equal when their class names match,
424/// since the name uniquely identifies the visual style rule.
425impl PartialEq for Css {
426 /// Compares two CSS classes by name.
427 ///
428 /// # Arguments
429 ///
430 /// - `&Self` - The first CSS class.
431 /// - `&Self` - The second CSS class.
432 ///
433 /// # Returns
434 ///
435 /// - `bool` - `true` if the class names match.
436 fn eq(&self, other: &Self) -> bool {
437 self.get_name() == other.get_name()
438 }
439}
440
441/// Implementation of Css construction and style injection.
442impl Css {
443 /// Parses pseudo-class/pseudo-element rules from a compact serialization string.
444 ///
445 /// The serialization format is: `:selector { key: value; key: value; }:another { ... }`
446 /// This is used by the `class!` macro for fully static class definitions
447 /// where pseudo rules can be computed at compile time.
448 ///
449 /// # Arguments
450 ///
451 /// - `I` - The serialized pseudo rules string.
452 ///
453 /// # Returns
454 ///
455 /// - `Vec<PseudoRule>` - The parsed pseudo rules.
456 pub fn parse_pseudo_rules<I>(input: I) -> Vec<PseudoRule>
457 where
458 I: AsRef<str>,
459 {
460 let mut remaining: &str = input.as_ref();
461 let mut rules: Vec<PseudoRule> = Vec::new();
462 while !remaining.is_empty() {
463 let selector_end: Option<usize> = remaining.find(CSS_RULE_OPEN);
464 let Some(selector_end_index) = selector_end else {
465 break;
466 };
467 let selector: &str = &remaining[..selector_end_index];
468 let after_selector: &str = remaining[selector_end_index..]
469 .strip_prefix(CSS_RULE_OPEN)
470 .unwrap_or_default();
471 let style_end: Option<usize> = after_selector.find(CHAR_CSS_RULE_CLOSE);
472 let Some(style_end_index) = style_end else {
473 break;
474 };
475 let style: &str = &after_selector[..style_end_index];
476 if !selector.is_empty() && !style.is_empty() {
477 rules.push(PseudoRule::new(selector.to_string(), style.to_string()));
478 }
479 remaining = after_selector[style_end_index..]
480 .strip_prefix(CHAR_CSS_RULE_CLOSE)
481 .unwrap_or_default();
482 }
483 rules
484 }
485
486 /// Parses media query rules from a compact serialization string.
487 ///
488 /// The serialization format is:
489 /// `@media query { key: value; ::selector { key: value; } }@media query2 { ... }`
490 /// This is used by the `class!` macro for fully static class definitions
491 /// where media rules can be computed at compile time.
492 /// Supports nested pseudo-element blocks inside media query blocks.
493 ///
494 /// # Arguments
495 ///
496 /// - `S` - The serialized media rules string.
497 ///
498 /// # Returns
499 ///
500 /// - `Vec<MediaRule>` - The parsed media rules.
501 pub fn parse_media_rules<S>(input: S) -> Vec<MediaRule>
502 where
503 S: AsRef<str>,
504 {
505 let input: &str = input.as_ref();
506 let mut rules: Vec<MediaRule> = Vec::new();
507 let mut remaining: &str = input;
508 while !remaining.is_empty() {
509 if !remaining.starts_with(CSS_MEDIA_PREFIX) {
510 break;
511 }
512 let after_prefix: &str = remaining.strip_prefix(CSS_MEDIA_PREFIX).unwrap_or_default();
513 let query_end: Option<usize> = after_prefix.find(CSS_RULE_OPEN);
514 let Some(query_end_index) = query_end else {
515 break;
516 };
517 let query: &str = &after_prefix[..query_end_index];
518 let after_query: &str = after_prefix[query_end_index..]
519 .strip_prefix(CSS_RULE_OPEN)
520 .unwrap_or_default();
521 let mut depth: usize = 1;
522 let mut close_pos: usize = 0;
523 for (index, char_value) in after_query.char_indices() {
524 if char_value == '{' {
525 depth += 1;
526 } else if char_value == '}' {
527 depth -= 1;
528 if depth == 0 {
529 close_pos = index;
530 break;
531 }
532 }
533 }
534 if close_pos == 0 {
535 break;
536 }
537 let body: &str = &after_query[..close_pos];
538 let (style, pseudo_rules): (String, Vec<PseudoRule>) = Self::parse_media_body(body);
539 if !query.is_empty() && (!style.is_empty() || !pseudo_rules.is_empty()) {
540 rules.push(MediaRule::new(query.to_string(), style, pseudo_rules));
541 }
542 remaining = after_query[close_pos..]
543 .strip_prefix(CHAR_CSS_RULE_CLOSE)
544 .unwrap_or_default();
545 }
546 rules
547 }
548
549 /// Parses the body of a media rule, separating top-level style declarations
550 /// from nested pseudo-element blocks.
551 ///
552 /// # Arguments
553 ///
554 /// - `&str` - The media rule body content (between the outer braces).
555 ///
556 /// # Returns
557 ///
558 /// - `(String, Vec<PseudoRule>)` - A tuple of the style string and pseudo rules.
559 fn parse_media_body(body: &str) -> (String, Vec<PseudoRule>) {
560 let mut style_parts: String = String::new();
561 let mut pseudo_rules: Vec<PseudoRule> = Vec::new();
562 let mut remaining: &str = body;
563 while !remaining.is_empty() {
564 let brace_pos: Option<usize> = remaining.find('{');
565 match brace_pos {
566 Some(pos) => {
567 let before_brace: &str = remaining[..pos].trim();
568 if before_brace.starts_with("::") || before_brace.starts_with(':') {
569 let selector: &str = before_brace;
570 let after_brace: &str = &remaining[pos + 1..];
571 let mut depth: usize = 1;
572 let mut close_pos: usize = 0;
573 for (index, char_value) in after_brace.char_indices() {
574 if char_value == '{' {
575 depth += 1;
576 } else if char_value == '}' {
577 depth -= 1;
578 if depth == 0 {
579 close_pos = index;
580 break;
581 }
582 }
583 }
584 if close_pos > 0 {
585 let inner_style: &str = after_brace[..close_pos].trim();
586 if !selector.is_empty() && !inner_style.is_empty() {
587 pseudo_rules.push(PseudoRule::new(
588 selector.to_string(),
589 inner_style.to_string(),
590 ));
591 }
592 remaining = after_brace[close_pos + 1..].trim_start();
593 continue;
594 }
595 break;
596 } else {
597 style_parts.push_str(before_brace);
598 style_parts.push(' ');
599 let after_brace: &str = &remaining[pos + 1..];
600 let mut depth: usize = 1;
601 let mut close_pos: usize = 0;
602 for (index, char_value) in after_brace.char_indices() {
603 if char_value == '{' {
604 depth += 1;
605 } else if char_value == '}' {
606 depth -= 1;
607 if depth == 0 {
608 close_pos = index;
609 break;
610 }
611 }
612 }
613 if close_pos > 0 {
614 style_parts.push_str(after_brace[..close_pos].trim());
615 style_parts.push(' ');
616 remaining = after_brace[close_pos + 1..].trim_start();
617 continue;
618 }
619 break;
620 }
621 }
622 None => {
623 style_parts.push_str(remaining.trim());
624 break;
625 }
626 }
627 }
628 (style_parts.trim().to_string(), pseudo_rules)
629 }
630
631 /// Injects this class's styles into the DOM if not already present.
632 ///
633 /// Uses a global `HashSet` to track injected class names, avoiding the
634 /// expensive `existing_css.contains(css)` full-text search on every call.
635 /// Builds the class rule, pseudo-class rules, and media rules as CSS text,
636 /// then appends them directly to the `<style>` element via
637 /// `append_child` with a new text node — no read-modify-write of the
638 /// entire stylesheet content.
639 ///
640 /// # Panics
641 ///
642 /// Panics if `window()` or `document()` is unavailable on the current platform.
643 pub fn inject_style(&self) {
644 let class_name: &String = self.get_name();
645 if InjectedClassesCell::is_injected(class_name) {
646 return;
647 }
648 InjectedClassesCell::mark_injected(class_name);
649 let raw_name: String = self.get_name().clone();
650 let mut escaped_name: String = String::with_capacity(raw_name.len() * 2);
651 for ch in raw_name.chars() {
652 if ch.is_ascii_alphanumeric() || ch == CHAR_HYPHEN || ch == CHAR_UNDERSCORE {
653 escaped_name.push(ch);
654 } else {
655 escaped_name.push(CHAR_CSS_ESCAPE);
656 escaped_name.push(ch);
657 }
658 }
659 let mut css_text: String = format!(
660 "{CHAR_CSS_CLASS_PREFIX}{escaped_name}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
661 self.get_style()
662 );
663 for pseudo_rule in self.get_pseudo_rules() {
664 if !pseudo_rule.get_style().is_empty() {
665 css_text = format!(
666 "{css_text}{CHAR_CSS_RULE_SEPARATOR}{CHAR_CSS_CLASS_PREFIX}{}{}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
667 escaped_name,
668 pseudo_rule.get_selector(),
669 pseudo_rule.get_style()
670 );
671 }
672 }
673 for media_rule in self.get_media_rules() {
674 if !media_rule.get_query().is_empty() {
675 let mut media_body: String = format!(
676 "{CHAR_CSS_CLASS_PREFIX}{}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
677 escaped_name,
678 media_rule.get_style()
679 );
680 for pseudo_rule in media_rule.get_pseudo_rules() {
681 if !pseudo_rule.get_style().is_empty() {
682 media_body = format!(
683 "{media_body} {CHAR_CSS_CLASS_PREFIX}{}{}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
684 escaped_name,
685 pseudo_rule.get_selector(),
686 pseudo_rule.get_style()
687 );
688 }
689 }
690 css_text = format!(
691 "{css_text}{CHAR_CSS_RULE_SEPARATOR}{CSS_MEDIA_PREFIX}{}{CSS_RULE_OPEN_FORMAT}{}{CSS_RULE_CLOSE_FORMAT}",
692 media_rule.get_query(),
693 media_body
694 );
695 }
696 }
697 Self::append_css(&css_text);
698 }
699
700 /// Appends CSS text directly to the shared `<style>` element.
701 ///
702 /// Creates a new text node and appends it as a child of the `<style>`
703 /// element, avoiding the read-modify-write pattern of reading the entire
704 /// `innerText`, concatenating, and setting it back.
705 ///
706 /// # Arguments
707 ///
708 /// - `&str` - The CSS text to append.
709 ///
710 /// The `cfg!` guard matches the one `Scheduler::current_time` already
711 /// uses: `window()` reads a wasm-only imported static, so on a non-wasm
712 /// target it panics with "cannot access imported statics on non-wasm
713 /// targets" rather than returning `None`. That panic short-circuits the
714 /// graceful `match window() { None => return }` below, and it fires from
715 /// `OnceLock<Css>::get_or_init` — the first time any `c_*()` class
716 /// function is called. Every styled view component calls one, so
717 /// without this guard none of them can be rendered in a native
718 /// `cargo test` process. On wasm the guard is a constant `true` and
719 /// this function behaves exactly as before.
720 fn append_css(css_text: &str) {
721 if !cfg!(target_arch = "wasm32") {
722 return;
723 }
724 let style_id: &str = EUV_CSS_INJECTED_ID;
725 let window_value: Window = match window() {
726 Some(window_instance) => window_instance,
727 None => return,
728 };
729 let document: Document = match window_value.document() {
730 Some(document_instance) => document_instance,
731 None => return,
732 };
733 let style_element: HtmlStyleElement = match document.get_element_by_id(style_id) {
734 Some(existing_element) => match existing_element.dyn_into::<HtmlStyleElement>() {
735 Ok(element) => element,
736 Err(_err) => return,
737 },
738 None => {
739 let created: Element = match document.create_element(STYLE_TAG) {
740 Ok(element) => element,
741 Err(_err) => return,
742 };
743 let style_element_from_id: HtmlStyleElement =
744 match created.dyn_into::<HtmlStyleElement>() {
745 Ok(element) => element,
746 Err(_err) => return,
747 };
748 style_element_from_id.set_id(style_id);
749 if let Some(head) = document.head() {
750 let _: Result<Node, JsValue> = head.append_child(&style_element_from_id);
751 }
752 style_element_from_id
753 }
754 };
755 if !css_text.is_empty() {
756 let text_node: Text = document.create_text_node(css_text);
757 let _: Result<Node, JsValue> = style_element.append_child(&text_node);
758 }
759 }
760
761 /// Builds a CSS style string from an array of key-value pairs.
762 ///
763 /// This function is used by the `html!` macro to convert static `style:`
764 /// attributes into a CSS string without allocating intermediate objects.
765 ///
766 /// # Arguments
767 ///
768 /// - `&[(K, V)]` - An array of CSS property name-value pairs.
769 ///
770 /// # Returns
771 ///
772 /// - `String` - The CSS string (e.g., `"margin: 0 auto; max-width: 800px;"`).
773 pub fn style_string<K, V>(props: &[(K, V)]) -> String
774 where
775 K: AsRef<str>,
776 V: AsRef<str>,
777 {
778 // Single pre-sized `String` instead of per-prop `format!` +
779 // intermediate `Vec<String>` + `join` (was N + 2 allocations).
780 let total_len: usize = props
781 .iter()
782 .map(|(key, value): &(K, V)| {
783 key.as_ref().len() + CSS_PROP_SEPARATOR.len() + value.as_ref().len() + 2
784 })
785 .sum();
786 let mut out: String = String::with_capacity(total_len);
787 for (index, (key, value)) in props.iter().enumerate() {
788 if index > 0 {
789 out.push_str(CHAR_SPACE);
790 }
791 out.push_str(key.as_ref());
792 out.push_str(CSS_PROP_SEPARATOR);
793 out.push_str(value.as_ref());
794 out.push(CHAR_CSS_DECL_TERMINATOR);
795 }
796 out
797 }
798
799 /// Builds a stable suffix for a class name from a dynamic parameter value.
800 ///
801 /// Used by the `class!` macro when a parameter is wrapped in `{}` in the
802 /// class body. Wrapping a parameter opts it into value-dependent class
803 /// names, so each distinct value can inject its own CSS rule.
804 ///
805 /// # Arguments
806 ///
807 /// - `&str` - The dynamic parameter value.
808 ///
809 /// # Returns
810 ///
811 /// - `String` - A stable hexadecimal suffix for the class name.
812 pub fn param_class_name(value: &str) -> String {
813 let mut hash: u64 = CLASS_PARAM_HASH_FNV_OFFSET;
814 for byte in value.as_bytes() {
815 hash ^= u64::from(*byte);
816 hash = hash.wrapping_mul(CLASS_PARAM_HASH_FNV_PRIME);
817 }
818 format!("{hash:x}")
819 }
820
821 /// Builds a CSS style string from owned key-value pairs.
822 ///
823 /// Used by the `html!` macro for reactive style attributes (with `if`
824 /// conditions) where values are computed at runtime.
825 ///
826 /// # Arguments
827 ///
828 /// - `&[(String, String)]` - An array of owned CSS property name-value pairs.
829 ///
830 /// # Returns
831 ///
832 /// - `String` - The CSS string (e.g., `"margin: 0 auto; max-width: 800px;"`).
833 pub fn style_string_owned(props: &[(String, String)]) -> String {
834 // Single pre-sized `String` (same shape as `style_string`).
835 let total_len: usize = props
836 .iter()
837 .map(|(key, value): &(String, String)| {
838 key.len() + CSS_PROP_SEPARATOR.len() + value.len() + 2
839 })
840 .sum();
841 let mut out: String = String::with_capacity(total_len);
842 for (index, (key, value)) in props.iter().enumerate() {
843 if index > 0 {
844 out.push_str(CHAR_SPACE);
845 }
846 out.push_str(key);
847 out.push_str(CSS_PROP_SEPARATOR);
848 out.push_str(value);
849 out.push(CHAR_CSS_DECL_TERMINATOR);
850 }
851 out
852 }
853
854 /// Injects CSS text into the shared `<style>` element in the DOM.
855 ///
856 /// Delegates to [`Css::append_css`] for the actual DOM append.
857 /// Unlike the previous implementation, this does not read the existing
858 /// stylesheet content or perform a full-text `contains` search.
859 ///
860 /// # Arguments
861 ///
862 /// - `S` - The CSS text to inject (e.g., reset styles, keyframes, media queries).
863 ///
864 /// # Panics
865 ///
866 /// Panics if `window()` or `document()` is unavailable on the current platform.
867 pub fn inject_css<S>(css_text: S)
868 where
869 S: AsRef<str>,
870 {
871 let css_text: &str = css_text.as_ref();
872 Self::append_css(css_text);
873 }
874}
875
876/// Displays the CSS class name.
877///
878/// This enables `format!("{css}")` to produce the class name string,
879/// which is required for reactive `if` conditions in `class:` attributes.
880impl Display for Css {
881 /// Formats the CSS class as its name string.
882 ///
883 /// # Arguments
884 ///
885 /// - `&mut Formatter<'_>` - The formatter.
886 ///
887 /// # Returns
888 ///
889 /// - `fmt::Result` - The formatting result.
890 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
891 write!(formatter, "{}", self.get_name())
892 }
893}