euv-core 0.37.0

A declarative, cross-platform UI framework for Rust with virtual DOM, reactive signals, and HTML macros for WebAssembly.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use super::*;

/// Visual equality comparison for text nodes.
///
/// Only compares the text content; the backing signal is not considered
/// because it does not affect visual output.
///
/// OPT 29: `content` is `Cow<'static, str>`; compare the dereffed
/// string views (cheap for both `Borrowed` and `Owned`).
impl PartialEq for TextNode {
    /// Returns `true` when `self` and `other` are equivalent by the [`PartialEq`] contract.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The other value to compare against `self`.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `self` and `other` are equivalent by the trait contract.
    fn eq(&self, other: &Self) -> bool {
        self.get_content().as_ref() == other.get_content().as_ref()
    }
}

/// Clones a `VirtualNode<T>` by deep-copying all fields.
impl<T: Clone> Clone for VirtualNode<T> {
    /// Clones the [`VirtualNode`] by reusing shared, cheap-to-clone state where possible.
    fn clone(&self) -> Self {
        match self {
            Self::Element {
                tag,
                attributes,
                children,
                key,
                props,
            } => Self::Element {
                tag: tag.clone(),
                attributes: attributes.clone(),
                children: children.clone(),
                key: key.clone(),
                props: props.clone(),
            },
            Self::Text(text_node) => Self::Text(text_node.clone()),
            Self::Fragment(children) => Self::Fragment(children.clone()),
            Self::Dynamic(dynamic_node) => Self::Dynamic(dynamic_node.clone()),
            Self::Empty => Self::Empty,
        }
    }
}

/// Debug formatting for `VirtualNode<T>`.
///
/// Skips `Dynamic` inner details and `props` for brevity.
impl<T: Debug> Debug for VirtualNode<T> {
    /// Formats the [`VirtualNode`] via the supplied formatter.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Result of the formatting operation.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Element {
                tag,
                attributes,
                children,
                key,
                props,
            } => formatter
                .debug_struct(DEBUG_NAME_ELEMENT)
                .field(DEBUG_FIELD_TAG, tag)
                .field(DEBUG_FIELD_ATTRIBUTES, attributes)
                .field(DEBUG_FIELD_CHILDREN, children)
                .field(DEBUG_FIELD_KEY, key)
                .field(DEBUG_FIELD_PROPS, props)
                .finish(),
            Self::Text(text_node) => formatter
                .debug_tuple(DEBUG_NAME_TEXT)
                .field(text_node)
                .finish(),
            Self::Fragment(children) => formatter
                .debug_tuple(DEBUG_NAME_FRAGMENT)
                .field(children)
                .finish(),
            Self::Dynamic(_) => formatter.debug_tuple(DEBUG_NAME_DYNAMIC).finish(),
            Self::Empty => formatter.debug_tuple(DEBUG_NAME_EMPTY).finish(),
        }
    }
}

/// Default implementation returns `VirtualNode::Empty`.
impl<T> Default for VirtualNode<T> {
    /// Constructs a default [`VirtualNode`] value.
    fn default() -> Self {
        Self::Empty
    }
}

/// Visual equality comparison for virtual DOM nodes.
///
/// Used by DynamicNode re-rendering to skip unnecessary DOM patches when
/// the rendered output has not changed. Event attributes are always
/// considered equal because re-binding event listeners is handled
/// separately by the handler registry and does not affect visual output.
/// Dynamic nodes manage their own subtree re-rendering, so two Dynamic
/// variants are always considered equal — the inner renderer handles
/// patching when the dynamic content actually changes.
impl<T: PartialEq> PartialEq for VirtualNode<T> {
    /// Returns `true` when `self` and `other` are equivalent by the [`PartialEq`] contract.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The other value to compare against `self`.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `self` and `other` are equivalent by the trait contract.
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (VirtualNode::Text(old_text), VirtualNode::Text(new_text)) => old_text == new_text,
            (
                VirtualNode::Element {
                    tag: old_tag,
                    attributes: old_attrs,
                    children: old_children,
                    props: old_props,
                    ..
                },
                VirtualNode::Element {
                    tag: new_tag,
                    attributes: new_attrs,
                    children: new_children,
                    props: new_props,
                    ..
                },
            ) => {
                old_tag == new_tag
                    && old_attrs.len() == new_attrs.len()
                    && old_attrs.iter().zip(new_attrs.iter()).all(
                        |(old_attr, new_attr): (&AttributeEntry, &AttributeEntry)| {
                            old_attr == new_attr
                        },
                    )
                    && old_children.len() == new_children.len()
                    && old_children.iter().zip(new_children.iter()).all(
                        |(old_child, new_child): (&VirtualNode, &VirtualNode)| {
                            old_child == new_child
                        },
                    )
                    && old_props == new_props
            }
            (VirtualNode::Fragment(old_children), VirtualNode::Fragment(new_children)) => {
                old_children.len() == new_children.len()
                    && old_children.iter().zip(new_children.iter()).all(
                        |(old_child, new_child): (&VirtualNode, &VirtualNode)| {
                            old_child == new_child
                        },
                    )
            }
            (VirtualNode::Dynamic(_), VirtualNode::Dynamic(_)) => false,
            (VirtualNode::Empty, VirtualNode::Empty) => true,
            _ => false,
        }
    }
}

/// Provides a default empty dynamic node with a no-op render function.
impl Default for DynamicNode {
    /// Constructs a default [`DynamicNode`] value.
    fn default() -> Self {
        let render_fn_inner: Rc<UnsafeCell<RenderFnInner>> = Rc::new(UnsafeCell::new(
            RenderFnInner::new(Box::new(|_: &mut HookContext| VirtualNode::Empty)),
        ));
        Self::new(render_fn_inner, HookContext::default())
    }
}

/// Implementation of dynamic node accessor methods.
impl DynamicNode {
    /// Invokes the render closure and returns the produced virtual node.
    ///
    /// # Safety
    ///
    /// Must only be called from the main thread. Guaranteed in WASM
    /// single-threaded context. No concurrent access is possible.
    ///
    /// # Arguments
    ///
    /// - `&mut HookContext` - The hook context to pass to the render closure.
    ///
    /// # Returns
    ///
    /// - `VirtualNode` - The virtual node produced by the render closure.
    pub(crate) fn render(&self, hook_context: &mut HookContext) -> VirtualNode {
        let inner: &mut RenderFnInner = unsafe { &mut *self.get_render_fn().get() };
        (inner.get_mut_render_fn())(hook_context)
    }
}

/// Implementation of virtual node construction and property extraction.
impl<T> VirtualNode<T> {
    /// Returns the tag name if this is an element or component node.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - The tag name, or `None` if not an element.
    pub fn try_get_tag_name(&self) -> Option<String> {
        match self {
            Self::Element { tag, .. } => match tag {
                // OPT 2: `Cow::to_string()` allocates only for the
                // `Owned` branch. The common `Borrowed("div")` path
                // performs one string slice clone (no heap).
                Tag::Element(name) => Some(name.to_string()),
                Tag::Component(name) => Some(name.to_string()),
                // Portals do not contribute a tag name to the
                // declared position in the DOM tree — their content
                // is rendered into a separate target, and the
                // marker is an internal implementation detail.
                // Returning `None` here keeps callers that use
                // `try_get_tag_name` for "what tag is this?" away
                // from the portal sentinel.
                Tag::Portal(_) => None,
            },
            _ => None,
        }
    }

    /// Returns the children of this node as a borrowed slice.
    ///
    /// Returns an empty slice for `Empty`, the children of `Element`
    /// and `Fragment` variants, and an empty slice for `Text` /
    /// `Dynamic`. Zero-copy; callers can iterate without cloning.
    ///
    /// # Returns
    ///
    /// - `&[VirtualNode]` - The children, or an empty slice.
    pub fn get_children(&self) -> &[VirtualNode] {
        match self {
            Self::Element { children, .. } => children.as_slice(),
            Self::Fragment(children) => children.as_slice(),
            _ => &[],
        }
    }

    /// Returns the first child of this node as a borrowed reference,
    /// if any.
    ///
    /// Returns `None` when there are no children; otherwise returns
    /// a reference to the first child. Zero-copy; replaces the
    /// previous `get_child_node` helper that cloned the entire
    /// children subtree per render.
    ///
    /// # Returns
    ///
    /// - `Option<&VirtualNode>` - The first child, or `None`.
    pub fn get_first_child(&self) -> Option<&VirtualNode> {
        self.get_children().first()
    }

    /// Returns `true` if this node has non-empty children.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether this node has children.
    pub fn has_children(&self) -> bool {
        !self.get_children().is_empty()
    }

    /// Clones the props of this node.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - The cloned props, or `None` if this node has no props.
    pub fn try_get_props(&self) -> Option<T>
    where
        T: Clone,
    {
        match self {
            Self::Element { props, .. } => props.as_deref().cloned(),
            _ => None,
        }
    }

    /// Returns the children of this node as a borrowed slice.
    ///
    /// Equivalent to [`Self::get_children`] but exposes the raw
    /// `Option<&[VirtualNode]>` shape for callers that want to
    /// distinguish "no children" from "empty children" (Element
    /// without children vs. Text/Dynamic/Empty).
    ///
    /// # Returns
    ///
    /// - `Option<&[VirtualNode]>` - The children, or `None`.
    pub fn try_get_children(&self) -> Option<&[VirtualNode]> {
        match self {
            Self::Element { children, .. } => Some(children.as_slice()),
            Self::Fragment(children) => Some(children.as_slice()),
            _ => None,
        }
    }

    /// Extends this node's attribute list with the given entries, then
    /// returns the node. If the node is not an `Element` variant, the
    /// entries are dropped and the node is returned unchanged.
    ///
    /// Used by the `html!` macro to splice `class` / `style` / event
    /// handler attributes onto a component-returned node without forcing
    /// a `let mut` binding in the generated code.
    ///
    /// # Arguments
    ///
    /// - `I` - The extra entries to append.
    ///
    /// # Returns
    ///
    /// - `Self` - The node with extended attributes (or unchanged).
    pub fn extend_attributes<I>(self, extra: I) -> Self
    where
        I: IntoIterator<Item = AttributeEntry>,
    {
        match self {
            Self::Element {
                tag,
                attributes,
                children,
                key,
                props,
            } => {
                let mut attrs: Vec<AttributeEntry> = attributes;
                attrs.extend(extra);
                Self::Element {
                    tag,
                    attributes: attrs,
                    children,
                    key,
                    props,
                }
            }
            other => other,
        }
    }

    /// Returns the diffing key of this node, if it has one.
    ///
    /// Recognizes keys on `Element` variants. Other variants
    /// (`Text`, `Fragment`, `Dynamic`, `Empty`) do not have keys.
    /// This matches the renderer's `get_node_key` semantics
    /// in `core/src/renderer/render/impl.rs`.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - The key, or `None` if this node has no key
    ///   or is not an `Element` variant.
    pub fn key(&self) -> Option<&str> {
        match self {
            Self::Element { key, .. } => key.as_deref(),
            _ => None,
        }
    }

    /// Returns `true` if this node has a non-`None` diffing key.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if `key()` returns `Some`, `false` otherwise.
    pub fn has_key(&self) -> bool {
        self.key().is_some()
    }
}

/// Implementation of virtual node construction for `VirtualNode<()>`.
impl VirtualNode<()> {
    /// Creates a dynamic node with the given render function.
    ///
    /// # Arguments
    ///
    /// - `F` - The render function.
    ///
    /// # Returns
    ///
    /// - `Self` - The dynamic node.
    pub fn create_dynamic<F>(render_fn: F) -> Self
    where
        F: FnMut(&mut HookContext) -> Self + 'static,
    {
        let hook_context: HookContext = HookContext::default();
        let inner: Rc<UnsafeCell<RenderFnInner>> =
            Rc::new(UnsafeCell::new(RenderFnInner::new(Box::new(render_fn))));
        Self::Dynamic(DynamicNode::new(inner, hook_context))
    }
}

/// Inherent implementation of [`CowText`].
impl CowText {
    /// Builds component text from an owned or borrowed value.
    ///
    /// # Arguments
    ///
    /// - `T` - The value convertible into a static cow.
    ///
    /// # Returns
    ///
    /// - `CowText` - The component text.
    pub fn from_text<T>(text: T) -> Self
    where
        T: Into<Cow<'static, str>>,
    {
        Self(text.into())
    }

    /// Returns the text as a borrowed string slice.
    ///
    /// # Returns
    ///
    /// - `&str` - The text.
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }

    /// Copies the text into a new owned string.
    ///
    /// # Returns
    ///
    /// - `String` - An owned copy of the text.
    pub fn to_string_owned(&self) -> String {
        self.0.to_string()
    }
}

/// Formats component text as its contents.
impl Display for CowText {
    /// Writes the text to the formatter.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - The formatter receiving the text.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Whether formatting succeeded.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.0, formatter)
    }
}

/// Borrows component text as a string slice.
impl Deref for CowText {
    /// The borrowed string slice type.
    type Target = str;

    /// Returns the text contents.
    ///
    /// # Returns
    ///
    /// - `&Self::Target` - The text.
    fn deref(&self) -> &Self::Target {
        self.0.as_ref()
    }
}

/// Converts an owned string into component text.
impl From<String> for CowText {
    /// Stores the string without copying it.
    ///
    /// # Arguments
    ///
    /// - `String` - The owned text.
    ///
    /// # Returns
    ///
    /// - `CowText` - The component text.
    fn from(text: String) -> Self {
        Self(Cow::Owned(text))
    }
}

/// Converts a static string slice into component text.
impl From<&'static str> for CowText {
    /// Borrows the static text without allocating.
    ///
    /// # Arguments
    ///
    /// - `&'static str` - The static text.
    ///
    /// # Returns
    ///
    /// - `CowText` - The component text.
    fn from(text: &'static str) -> Self {
        Self(Cow::Borrowed(text))
    }
}

/// Converts a static cow into component text.
impl From<Cow<'static, str>> for CowText {
    /// Stores the cow without copying it.
    ///
    /// # Arguments
    ///
    /// - `Cow<'static, str>` - The text.
    ///
    /// # Returns
    ///
    /// - `CowText` - The component text.
    fn from(text: Cow<'static, str>) -> Self {
        Self(text)
    }
}

/// Extracts the cow stored in component text.
impl From<CowText> for Cow<'static, str> {
    /// Returns the owned or borrowed cow.
    ///
    /// # Arguments
    ///
    /// - `CowText` - The text wrapper.
    ///
    /// # Returns
    ///
    /// - `Cow<'static, str>` - The stored text.
    fn from(text: CowText) -> Self {
        text.0
    }
}

/// Converts component text into a virtual text node.
impl From<CowText> for VirtualNode {
    /// Constructs a text node from the stored cow.
    ///
    /// # Arguments
    ///
    /// - `CowText` - The text wrapper.
    ///
    /// # Returns
    ///
    /// - `VirtualNode` - The text node.
    fn from(text: CowText) -> Self {
        VirtualNode::Text(TextNode::new(text.0, None))
    }
}