Skip to main content

euv_core/vdom/
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    fn eq(&self, other: &Self) -> bool {
11        match (self, other) {
12            (AttributeValue::Text(a_val), AttributeValue::Text(b_val)) => a_val == b_val,
13            (AttributeValue::Signal(a_sig), AttributeValue::Signal(b_sig)) => {
14                a_sig.get() == b_sig.get()
15            }
16            (AttributeValue::Signal(a_sig), AttributeValue::Text(b_val)) => a_sig.get() == *b_val,
17            (AttributeValue::Text(a_val), AttributeValue::Signal(b_sig)) => *a_val == b_sig.get(),
18            (AttributeValue::Event(_), AttributeValue::Event(_)) => true,
19            (AttributeValue::Css(a_css), AttributeValue::Css(b_css)) => {
20                a_css.get_name() == b_css.get_name()
21            }
22            (AttributeValue::Dynamic(a_dyn), AttributeValue::Dynamic(b_dyn)) => a_dyn == b_dyn,
23            _ => false,
24        }
25    }
26}
27
28/// Visual equality comparison for attribute entries.
29///
30/// Two attribute entries are equal when their names match and their values
31/// are visually equal as defined by `AttributeValue::eq`.
32impl PartialEq for AttributeEntry {
33    fn eq(&self, other: &Self) -> bool {
34        self.get_name() == other.get_name() && self.get_value() == other.get_value()
35    }
36}
37
38/// Visual equality comparison for text nodes.
39///
40/// Only compares the text content; the backing signal is not considered
41/// because it does not affect visual output.
42impl PartialEq for TextNode {
43    fn eq(&self, other: &Self) -> bool {
44        self.get_content() == other.get_content()
45    }
46}
47
48/// Visual equality comparison for CSS classes.
49///
50/// Two CSS classes are considered equal when their class names match,
51/// since the name uniquely identifies the visual style rule.
52impl PartialEq for CssClass {
53    fn eq(&self, other: &Self) -> bool {
54        self.get_name() == other.get_name()
55    }
56}
57
58/// Visual equality comparison for virtual DOM nodes.
59///
60/// Used by DynamicNode re-rendering to skip unnecessary DOM patches when
61/// the rendered output has not changed. Event attributes are always
62/// considered equal because re-binding event listeners is handled
63/// separately by the handler registry and does not affect visual output.
64/// Dynamic nodes manage their own subtree re-rendering, so two Dynamic
65/// variants are always considered equal — the inner renderer handles
66/// patching when the dynamic content actually changes.
67impl PartialEq for VirtualNode {
68    fn eq(&self, other: &Self) -> bool {
69        match (self, other) {
70            (VirtualNode::Text(a_text), VirtualNode::Text(b_text)) => a_text == b_text,
71            (
72                VirtualNode::Element {
73                    tag: a_tag,
74                    attributes: a_attrs,
75                    children: a_children,
76                    ..
77                },
78                VirtualNode::Element {
79                    tag: b_tag,
80                    attributes: b_attrs,
81                    children: b_children,
82                    ..
83                },
84            ) => {
85                a_tag == b_tag
86                    && a_attrs.len() == b_attrs.len()
87                    && a_attrs.iter().zip(b_attrs.iter()).all(|(a, b)| a == b)
88                    && a_children.len() == b_children.len()
89                    && a_children
90                        .iter()
91                        .zip(b_children.iter())
92                        .all(|(a, b)| a == b)
93            }
94            (VirtualNode::Fragment(a_children), VirtualNode::Fragment(b_children)) => {
95                a_children.len() == b_children.len()
96                    && a_children
97                        .iter()
98                        .zip(b_children.iter())
99                        .all(|(a, b)| a == b)
100            }
101            (VirtualNode::Dynamic(_), VirtualNode::Dynamic(_)) => true,
102            (VirtualNode::Empty, VirtualNode::Empty) => true,
103            _ => false,
104        }
105    }
106}
107
108/// Maps each `Attribute` variant to its corresponding DOM attribute string.
109impl Attribute {
110    /// Returns the string representation of this attribute name for DOM binding.
111    pub fn as_str(&self) -> String {
112        match self {
113            Attribute::AccessKey => "accesskey".to_string(),
114            Attribute::Action => "action".to_string(),
115            Attribute::Alt => "alt".to_string(),
116            Attribute::AriaLabel => "aria-label".to_string(),
117            Attribute::AutoComplete => "autocomplete".to_string(),
118            Attribute::AutoFocus => "autofocus".to_string(),
119            Attribute::Checked => "checked".to_string(),
120            Attribute::Class => "class".to_string(),
121            Attribute::Cols => "cols".to_string(),
122            Attribute::ContentEditable => "contenteditable".to_string(),
123            Attribute::Data(name) => format!("data-{}", name),
124            Attribute::Dir => "dir".to_string(),
125            Attribute::Disabled => "disabled".to_string(),
126            Attribute::Draggable => "draggable".to_string(),
127            Attribute::EncType => "enctype".to_string(),
128            Attribute::For => "for".to_string(),
129            Attribute::Form => "form".to_string(),
130            Attribute::Height => "height".to_string(),
131            Attribute::Hidden => "hidden".to_string(),
132            Attribute::Href => "href".to_string(),
133            Attribute::Id => "id".to_string(),
134            Attribute::Lang => "lang".to_string(),
135            Attribute::Max => "max".to_string(),
136            Attribute::MaxLength => "maxlength".to_string(),
137            Attribute::Method => "method".to_string(),
138            Attribute::Min => "min".to_string(),
139            Attribute::MinLength => "minlength".to_string(),
140            Attribute::Multiple => "multiple".to_string(),
141            Attribute::Name => "name".to_string(),
142            Attribute::Pattern => "pattern".to_string(),
143            Attribute::Placeholder => "placeholder".to_string(),
144            Attribute::ReadOnly => "readonly".to_string(),
145            Attribute::Required => "required".to_string(),
146            Attribute::Rows => "rows".to_string(),
147            Attribute::Selected => "selected".to_string(),
148            Attribute::Size => "size".to_string(),
149            Attribute::SpellCheck => "spellcheck".to_string(),
150            Attribute::Src => "src".to_string(),
151            Attribute::Step => "step".to_string(),
152            Attribute::Style => "style".to_string(),
153            Attribute::TabIndex => "tabindex".to_string(),
154            Attribute::Target => "target".to_string(),
155            Attribute::Title => "title".to_string(),
156            Attribute::Type => "type".to_string(),
157            Attribute::Value => "value".to_string(),
158            Attribute::Width => "width".to_string(),
159            Attribute::Other(name) => name.clone(),
160        }
161    }
162}
163
164/// Clones a `DynamicNode` by cloning its `HookContext` (Copy) and `render_fn` (Rc).
165impl Clone for DynamicNode {
166    fn clone(&self) -> Self {
167        DynamicNode {
168            render_fn: Rc::clone(&self.render_fn),
169            hook_context: self.hook_context,
170        }
171    }
172}
173
174/// Converts a `VirtualNode` reference into an owned node.
175impl AsNode for VirtualNode {
176    fn as_node(&self) -> Option<VirtualNode> {
177        Some(self.clone())
178    }
179}
180
181/// Converts a `VirtualNode` reference into an owned node.
182impl AsNode for &VirtualNode {
183    fn as_node(&self) -> Option<VirtualNode> {
184        Some((*self).clone())
185    }
186}
187
188/// Converts a `String` into a text virtual node.
189impl AsNode for String {
190    fn as_node(&self) -> Option<VirtualNode> {
191        Some(VirtualNode::Text(TextNode::new(self.clone(), None)))
192    }
193}
194
195/// Converts a string slice into a text virtual node.
196impl AsNode for &str {
197    fn as_node(&self) -> Option<VirtualNode> {
198        Some(VirtualNode::Text(TextNode::new(self.to_string(), None)))
199    }
200}
201
202/// Converts an `i32` into a text virtual node.
203impl AsNode for i32 {
204    fn as_node(&self) -> Option<VirtualNode> {
205        Some(VirtualNode::Text(TextNode::new(self.to_string(), None)))
206    }
207}
208
209/// Converts an `i64` into a text virtual node.
210impl AsNode for i64 {
211    fn as_node(&self) -> Option<VirtualNode> {
212        Some(VirtualNode::Text(TextNode::new(self.to_string(), None)))
213    }
214}
215
216/// Converts a `usize` into a text virtual node.
217impl AsNode for usize {
218    fn as_node(&self) -> Option<VirtualNode> {
219        Some(VirtualNode::Text(TextNode::new(self.to_string(), None)))
220    }
221}
222
223/// Converts an `f32` into a text virtual node.
224impl AsNode for f32 {
225    fn as_node(&self) -> Option<VirtualNode> {
226        Some(VirtualNode::Text(TextNode::new(self.to_string(), None)))
227    }
228}
229
230/// Converts an `f64` into a text virtual node.
231impl AsNode for f64 {
232    fn as_node(&self) -> Option<VirtualNode> {
233        Some(VirtualNode::Text(TextNode::new(self.to_string(), None)))
234    }
235}
236
237/// Converts a `bool` into a text virtual node.
238impl AsNode for bool {
239    fn as_node(&self) -> Option<VirtualNode> {
240        Some(VirtualNode::Text(TextNode::new(self.to_string(), None)))
241    }
242}
243
244/// Converts a signal into a reactive text virtual node.
245impl<T> AsNode for Signal<T>
246where
247    T: Clone + PartialEq + std::fmt::Display + 'static,
248{
249    fn as_node(&self) -> Option<VirtualNode> {
250        Some(self.as_reactive_text())
251    }
252}
253
254/// Converts a `VirtualNode` into itself via `IntoNode`.
255impl IntoNode for VirtualNode {
256    fn into_node(self) -> VirtualNode {
257        self
258    }
259}
260
261/// Wraps a `FnMut() -> VirtualNode` closure into a `DynamicNode` via `IntoNode`.
262///
263/// This enables writing `{move || html! { ... }}` directly in HTML markup
264/// without explicit `DynamicNode` construction.
265impl<F> IntoNode for F
266where
267    F: FnMut() -> VirtualNode + 'static,
268{
269    fn into_node(self) -> VirtualNode {
270        VirtualNode::Dynamic(DynamicNode {
271            render_fn: Rc::new(RefCell::new(self)),
272            hook_context: crate::reactive::create_hook_context(),
273        })
274    }
275}
276
277/// Converts a `String` into a text virtual node via `IntoNode`.
278impl IntoNode for String {
279    fn into_node(self) -> VirtualNode {
280        VirtualNode::Text(TextNode::new(self, None))
281    }
282}
283
284/// Converts a `&str` into a text virtual node via `IntoNode`.
285impl IntoNode for &str {
286    fn into_node(self) -> VirtualNode {
287        VirtualNode::Text(TextNode::new(self.to_string(), None))
288    }
289}
290
291/// Converts an `i32` into a text virtual node via `IntoNode`.
292impl IntoNode for i32 {
293    fn into_node(self) -> VirtualNode {
294        VirtualNode::Text(TextNode::new(self.to_string(), None))
295    }
296}
297
298/// Converts a `usize` into a text virtual node via `IntoNode`.
299impl IntoNode for usize {
300    fn into_node(self) -> VirtualNode {
301        VirtualNode::Text(TextNode::new(self.to_string(), None))
302    }
303}
304
305/// Converts a `bool` into a text virtual node via `IntoNode`.
306impl IntoNode for bool {
307    fn into_node(self) -> VirtualNode {
308        VirtualNode::Text(TextNode::new(self.to_string(), None))
309    }
310}
311
312/// Converts a signal into a reactive text virtual node via `IntoNode`.
313impl<T> IntoNode for Signal<T>
314where
315    T: Clone + PartialEq + std::fmt::Display + 'static,
316{
317    fn into_node(self) -> VirtualNode {
318        self.as_reactive_text()
319    }
320}
321
322/// Implementation of virtual node construction and property extraction.
323impl VirtualNode {
324    /// Creates a new element node with the given tag name.
325    pub fn get_element_node(tag_name: &str) -> Self {
326        VirtualNode::Element {
327            tag: Tag::Element(tag_name.to_string()),
328            attributes: Vec::new(),
329            children: Vec::new(),
330            key: None,
331        }
332    }
333
334    /// Creates a new text node with the given content.
335    pub fn get_text_node(content: &str) -> Self {
336        VirtualNode::Text(TextNode::new(content.to_string(), None))
337    }
338
339    /// Adds an attribute to this node if it is an element.
340    pub fn with_attribute(mut self, name: &str, value: AttributeValue) -> Self {
341        if let VirtualNode::Element {
342            ref mut attributes, ..
343        } = self
344        {
345            attributes.push(AttributeEntry::new(name.to_string(), value));
346        }
347        self
348    }
349
350    /// Adds a child node to this node if it is an element.
351    pub fn with_child(mut self, child: VirtualNode) -> Self {
352        if let VirtualNode::Element {
353            ref mut children, ..
354        } = self
355        {
356            children.push(child);
357        }
358        self
359    }
360
361    /// Returns true if this node is a component node.
362    pub fn is_component(&self) -> bool {
363        matches!(
364            self,
365            VirtualNode::Element {
366                tag: Tag::Component(_),
367                ..
368            }
369        )
370    }
371
372    /// Returns the tag name if this is an element or component node.
373    pub fn tag_name(&self) -> Option<String> {
374        match self {
375            VirtualNode::Element { tag, .. } => match tag {
376                Tag::Element(name) => Some(name.clone()),
377                Tag::Component(name) => Some(name.clone()),
378            },
379            _ => None,
380        }
381    }
382
383    /// Extracts a string property from this node if it is an element with the named attribute.
384    pub fn try_get_prop(&self, name: &Attribute) -> Option<String> {
385        let name_str: String = name.as_str();
386        if let VirtualNode::Element { attributes, .. } = self {
387            for attr in attributes {
388                if attr.get_name() == &name_str {
389                    match attr.get_value() {
390                        AttributeValue::Text(value) => return Some(value.clone()),
391                        AttributeValue::Signal(signal) => return Some(signal.get()),
392                        _ => {}
393                    }
394                }
395            }
396        }
397        None
398    }
399
400    /// Extracts a signal property from this node if it is an element with the named attribute.
401    ///
402    /// Returns the raw `Signal<String>` so components can reactively read the current value
403    /// and subscribe to future changes, rather than receiving a snapshot string.
404    pub fn try_get_signal_prop(&self, name: &Attribute) -> Option<Signal<String>> {
405        let name_str: String = name.as_str();
406        if let VirtualNode::Element { attributes, .. } = self {
407            for attr in attributes {
408                if attr.get_name() == &name_str
409                    && let AttributeValue::Signal(signal) = attr.get_value()
410                {
411                    return Some(*signal);
412                }
413            }
414        }
415        None
416    }
417
418    /// Extracts children from this node if it is an element.
419    pub fn get_children(&self) -> Vec<VirtualNode> {
420        if let VirtualNode::Element { children, .. } = self {
421            children.clone()
422        } else {
423            Vec::new()
424        }
425    }
426
427    /// Extracts text content from this node.
428    pub fn try_get_text(&self) -> Option<String> {
429        match self {
430            VirtualNode::Text(text_node) => Some(text_node.get_content().clone()),
431            VirtualNode::Element { children, .. } => {
432                children.first().and_then(VirtualNode::try_get_text)
433            }
434            _ => None,
435        }
436    }
437
438    /// Extracts an event handler from this node if it is an element with the named event attribute.
439    pub fn try_get_event(
440        &self,
441        name: &NativeEventName,
442    ) -> Option<crate::event::NativeEventHandler> {
443        let name_str: String = name.as_str();
444        if let VirtualNode::Element { attributes, .. } = self {
445            for attr in attributes {
446                if attr.get_name() == &name_str
447                    && let AttributeValue::Event(handler) = attr.get_value()
448                {
449                    return Some(handler.clone());
450                }
451            }
452        }
453        None
454    }
455
456    /// Extracts an event handler from this node by a custom attribute name.
457    pub fn try_get_callback(&self, name: &str) -> Option<crate::event::NativeEventHandler> {
458        if let VirtualNode::Element { attributes, .. } = self {
459            for attr in attributes {
460                if attr.get_name() == name
461                    && let AttributeValue::Event(handler) = attr.get_value()
462                {
463                    return Some(handler.clone());
464                }
465            }
466        }
467        None
468    }
469}
470
471/// Converts a signal into a reactive text node with listener wiring.
472impl<T> AsReactiveText for Signal<T>
473where
474    T: Clone + PartialEq + std::fmt::Display + 'static,
475{
476    fn as_reactive_text(&self) -> VirtualNode {
477        let signal: Signal<T> = *self;
478        let initial: String = signal.get().to_string();
479        let string_signal: Signal<String> = {
480            let boxed: Box<SignalInner<String>> = Box::new(SignalInner::new(initial.clone()));
481            Signal::from_inner(Box::leak(boxed) as *mut SignalInner<String>)
482        };
483        let source_signal: Signal<T> = *self;
484        let string_signal_clone: Signal<String> = string_signal;
485        source_signal.subscribe({
486            let source_signal: Signal<T> = source_signal;
487            move || {
488                let new_value: String = source_signal.get().to_string();
489                string_signal_clone.set(new_value);
490            }
491        });
492        VirtualNode::Text(TextNode::new(initial, Some(string_signal)))
493    }
494}
495
496/// Implementation of style CSS serialization.
497impl Style {
498    /// Adds a style property.
499    ///
500    /// Property names are automatically converted from snake_case to kebab-case
501    /// (e.g., `flex_direction` becomes `flex-direction`).
502    pub fn property<N, V>(mut self, name: N, value: V) -> Self
503    where
504        N: AsRef<str>,
505        V: AsRef<str>,
506    {
507        self.get_mut_properties().push(StyleProperty::new(
508            name.as_ref().replace('_', "-"),
509            value.as_ref().to_string(),
510        ));
511        self
512    }
513
514    /// Converts the style to a CSS string.
515    pub fn to_css_string(&self) -> String {
516        self.get_properties()
517            .iter()
518            .map(|p| format!("{}: {};", p.get_name(), p.get_value()))
519            .collect::<Vec<String>>()
520            .join(" ")
521    }
522}
523
524/// Provides a default empty style.
525impl Default for Style {
526    fn default() -> Self {
527        Self::new(Vec::new())
528    }
529}
530
531/// Implementation of StyleProperty construction.
532impl StyleProperty {
533    /// Creates a new style property with the given name and value.
534    pub fn new(name: String, value: String) -> Self {
535        let mut prop: StyleProperty = StyleProperty::default();
536        prop.set_name(name);
537        prop.set_value(value);
538        prop
539    }
540}
541
542/// Implementation of CssClass construction and style injection.
543impl CssClass {
544    /// Creates a new CSS class with the given name and style declarations.
545    ///
546    /// Automatically injects the styles into the DOM upon creation.
547    pub fn new(name: String, style: String) -> Self {
548        let mut css_class: CssClass = CssClass::default();
549        css_class.set_name(name);
550        css_class.set_style(style);
551        css_class.inject_style();
552        css_class
553    }
554
555    /// Injects this class's styles into the DOM if not already present.
556    ///
557    /// Creates a `<style>` element with id `euv-css-injected` on first call,
558    /// then appends the class rule. Subsequent calls for the same class name
559    /// are no-ops. On first creation, also injects global CSS keyframes
560    /// required by built-in animations.
561    pub fn inject_style(&self) {
562        #[cfg(target_arch = "wasm32")]
563        {
564            let style_id: &str = "euv-css-injected";
565            let document: web_sys::Document = web_sys::window()
566                .expect("no global window exists")
567                .document()
568                .expect("no document exists");
569            let style_element: web_sys::HtmlStyleElement = match document
570                .get_element_by_id(style_id)
571            {
572                Some(el) => el.dyn_into::<web_sys::HtmlStyleElement>().unwrap(),
573                None => {
574                    let el: web_sys::HtmlStyleElement = document
575                        .create_element("style")
576                        .unwrap()
577                        .dyn_into::<web_sys::HtmlStyleElement>()
578                        .unwrap();
579                    el.set_id(style_id);
580                    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); } }";
581                    let global: &str = "html, body, #app { height: 100%; margin: 0; padding: 0; overflow: hidden; } * { -webkit-tap-highlight-color: transparent; }";
582                    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 16px 0 0; position: fixed; bottom: 0; left: 16px; height: 80vh; animation: euv-slide-up 0.25s ease; } .c_modal_overlay { align-items: flex-end; } .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; } }";
583                    el.set_inner_text(&format!("{} {} {}", global, keyframes, media_queries));
584                    document.head().unwrap().append_child(&el).unwrap();
585                    el
586                }
587            };
588            let existing_css: String = style_element.inner_text();
589            let class_rule: String = format!(".{} {{ {} }}", self.get_name(), self.get_style());
590            if !existing_css.contains(&class_rule) {
591                let new_css: String = if existing_css.is_empty() {
592                    class_rule
593                } else {
594                    format!("{}\n{}", existing_css, class_rule)
595                };
596                style_element.set_inner_text(&new_css);
597            }
598        }
599    }
600}
601
602/// Displays the CSS class name.
603///
604/// This enables `format!("{}", css_class)` to produce the class name string,
605/// which is required for reactive `if` conditions in `class:` attributes.
606impl std::fmt::Display for CssClass {
607    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
608        write!(f, "{}", self.get_name())
609    }
610}