This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

yew/virtual_dom/
mod.rs

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
//! This module contains Yew's implementation of a reactive virtual DOM.

#[doc(hidden)]
pub mod key;
#[doc(hidden)]
pub mod listeners;
#[doc(hidden)]
pub mod vcomp;
#[doc(hidden)]
pub mod vlist;
#[doc(hidden)]
pub mod vnode;
#[doc(hidden)]
pub mod vportal;
#[doc(hidden)]
pub mod vraw;
#[doc(hidden)]
pub mod vsuspense;
#[doc(hidden)]
pub mod vtag;
#[doc(hidden)]
pub mod vtext;

use std::hint::unreachable_unchecked;
use std::rc::Rc;

use indexmap::IndexMap;
use wasm_bindgen::JsValue;

#[doc(inline)]
pub use self::key::Key;
#[doc(inline)]
pub use self::listeners::*;
#[doc(inline)]
pub use self::vcomp::{VChild, VComp};
#[doc(inline)]
pub use self::vlist::VList;
#[doc(inline)]
pub use self::vnode::VNode;
#[doc(inline)]
pub use self::vportal::VPortal;
#[doc(inline)]
pub use self::vraw::VRaw;
#[doc(inline)]
pub use self::vsuspense::VSuspense;
#[doc(inline)]
pub use self::vtag::VTag;
#[doc(inline)]
pub use self::vtext::VText;

/// Attribute value
pub type AttrValue = implicit_clone::unsync::IString;

#[cfg(any(feature = "ssr", feature = "hydration"))]
mod feat_ssr_hydration {
    #[cfg(debug_assertions)]
    type ComponentName = &'static str;
    #[cfg(not(debug_assertions))]
    type ComponentName = std::marker::PhantomData<()>;

    #[cfg(feature = "hydration")]
    use std::borrow::Cow;

    /// A collectable.
    ///
    /// This indicates a kind that can be collected from fragment to be processed at a later time
    pub enum Collectable {
        Component(ComponentName),
        Raw,
        Suspense,
    }

    impl Collectable {
        #[cfg(not(debug_assertions))]
        #[inline(always)]
        pub fn for_component<T: 'static>() -> Self {
            use std::marker::PhantomData;
            // This suppresses the clippy lint about unused generic.
            // We inline this function
            // so the function body is copied to its caller and generics get optimised away.
            let _comp_type: PhantomData<T> = PhantomData;
            Self::Component(PhantomData)
        }

        #[cfg(debug_assertions)]
        pub fn for_component<T: 'static>() -> Self {
            let comp_name = std::any::type_name::<T>();
            Self::Component(comp_name)
        }

        pub fn open_start_mark(&self) -> &'static str {
            match self {
                Self::Component(_) => "<[",
                Self::Raw => "<#",
                Self::Suspense => "<?",
            }
        }

        pub fn close_start_mark(&self) -> &'static str {
            match self {
                Self::Component(_) => "</[",
                Self::Raw => "</#",
                Self::Suspense => "</?",
            }
        }

        pub fn end_mark(&self) -> &'static str {
            match self {
                Self::Component(_) => "]>",
                Self::Raw => ">",
                Self::Suspense => ">",
            }
        }

        #[cfg(feature = "hydration")]
        pub fn name(&self) -> Cow<'static, str> {
            match self {
                #[cfg(debug_assertions)]
                Self::Component(m) => format!("Component({m})").into(),
                #[cfg(not(debug_assertions))]
                Self::Component(_) => "Component".into(),
                Self::Raw => "Raw".into(),
                Self::Suspense => "Suspense".into(),
            }
        }
    }
}

#[cfg(any(feature = "ssr", feature = "hydration"))]
pub(crate) use feat_ssr_hydration::*;

#[cfg(feature = "ssr")]
mod feat_ssr {
    use std::fmt::Write;

    use super::*;
    use crate::platform::fmt::BufWriter;

    impl Collectable {
        pub(crate) fn write_open_tag(&self, w: &mut BufWriter) {
            let _ = w.write_str("<!--");
            let _ = w.write_str(self.open_start_mark());

            #[cfg(debug_assertions)]
            match self {
                Self::Component(type_name) => {
                    let _ = w.write_str(type_name);
                }
                Self::Raw => {}
                Self::Suspense => {}
            }

            let _ = w.write_str(self.end_mark());
            let _ = w.write_str("-->");
        }

        pub(crate) fn write_close_tag(&self, w: &mut BufWriter) {
            let _ = w.write_str("<!--");
            let _ = w.write_str(self.close_start_mark());

            #[cfg(debug_assertions)]
            match self {
                Self::Component(type_name) => {
                    let _ = w.write_str(type_name);
                }
                Self::Raw => {}
                Self::Suspense => {}
            }

            let _ = w.write_str(self.end_mark());
            let _ = w.write_str("-->");
        }
    }
}

/// Defines if the [`Attributes`] is set as element's attribute or property and its value.
#[allow(missing_docs)]
#[derive(PartialEq, Clone, Debug)]
pub enum AttributeOrProperty {
    // This exists as a workaround to support Rust <1.72
    // Previous versions of Rust did not See
    // `AttributeOrProperty::Attribute(AttrValue::Static(_))` as `'static` that html! macro
    // used, and thus failed with "temporary value dropped while borrowed"
    //
    // See: https://github.com/yewstack/yew/pull/3458#discussion_r1350362215
    Static(&'static str),
    Attribute(AttrValue),
    Property(JsValue),
}

/// A collection of attributes for an element
#[derive(PartialEq, Clone, Debug)]
pub enum Attributes {
    /// Static list of attributes.
    ///
    /// Allows optimizing comparison to a simple pointer equality check and reducing allocations,
    /// if the attributes do not change on a node.
    Static(&'static [(&'static str, AttributeOrProperty)]),

    /// Static list of attribute keys with possibility to exclude attributes and dynamic attribute
    /// values.
    ///
    /// Allows optimizing comparison to a simple pointer equality check and reducing allocations,
    /// if the attributes keys do not change on a node.
    Dynamic {
        /// Attribute keys. Includes both always set and optional attribute keys.
        keys: &'static [&'static str],

        /// Attribute values. Matches [keys](Attributes::Dynamic::keys). Optional attributes are
        /// designated by setting [None].
        values: Box<[Option<AttributeOrProperty>]>,
    },

    /// IndexMap is used to provide runtime attribute deduplication in cases where the html! macro
    /// was not used to guarantee it.
    IndexMap(Rc<IndexMap<AttrValue, AttributeOrProperty>>),
}

impl Attributes {
    /// Construct a default Attributes instance
    pub fn new() -> Self {
        Self::default()
    }

    /// Return iterator over attribute key-value pairs.
    /// This function is suboptimal and does not inline well. Avoid on hot paths.
    ///
    /// This function only returns attributes
    pub fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a str, &'a str)> + 'a> {
        match self {
            Self::Static(arr) => Box::new(arr.iter().filter_map(|(k, v)| match v {
                AttributeOrProperty::Attribute(v) => Some((*k, v.as_ref())),
                AttributeOrProperty::Property(_) => None,
                AttributeOrProperty::Static(v) => Some((*k, v)),
            })),
            Self::Dynamic { keys, values } => {
                Box::new(keys.iter().zip(values.iter()).filter_map(|(k, v)| match v {
                    Some(AttributeOrProperty::Attribute(v)) => Some((*k, v.as_ref())),
                    _ => None,
                }))
            }
            Self::IndexMap(m) => Box::new(m.iter().filter_map(|(k, v)| match v {
                AttributeOrProperty::Attribute(v) => Some((k.as_ref(), v.as_ref())),
                _ => None,
            })),
        }
    }

    /// Get a mutable reference to the underlying `IndexMap`.
    /// If the attributes are stored in the `Vec` variant, it will be converted.
    pub fn get_mut_index_map(&mut self) -> &mut IndexMap<AttrValue, AttributeOrProperty> {
        macro_rules! unpack {
            () => {
                match self {
                    Self::IndexMap(m) => Rc::make_mut(m),
                    // SAFETY: unreachable because we set self to the `IndexMap` variant above.
                    _ => unsafe { unreachable_unchecked() },
                }
            };
        }

        match self {
            Self::IndexMap(m) => Rc::make_mut(m),
            Self::Static(arr) => {
                *self = Self::IndexMap(Rc::new(
                    arr.iter().map(|(k, v)| ((*k).into(), v.clone())).collect(),
                ));
                unpack!()
            }
            Self::Dynamic { keys, values } => {
                *self = Self::IndexMap(Rc::new(
                    std::mem::take(values)
                        .iter_mut()
                        .zip(keys.iter())
                        .filter_map(|(v, k)| v.take().map(|v| (AttrValue::from(*k), v)))
                        .collect(),
                ));
                unpack!()
            }
        }
    }
}

impl From<IndexMap<AttrValue, AttrValue>> for Attributes {
    fn from(map: IndexMap<AttrValue, AttrValue>) -> Self {
        let v = map
            .into_iter()
            .map(|(k, v)| (k, AttributeOrProperty::Attribute(v)))
            .collect();
        Self::IndexMap(Rc::new(v))
    }
}

impl From<IndexMap<&'static str, AttrValue>> for Attributes {
    fn from(v: IndexMap<&'static str, AttrValue>) -> Self {
        let v = v
            .into_iter()
            .map(|(k, v)| (AttrValue::Static(k), (AttributeOrProperty::Attribute(v))))
            .collect();
        Self::IndexMap(Rc::new(v))
    }
}

impl From<IndexMap<&'static str, JsValue>> for Attributes {
    fn from(v: IndexMap<&'static str, JsValue>) -> Self {
        let v = v
            .into_iter()
            .map(|(k, v)| (AttrValue::Static(k), (AttributeOrProperty::Property(v))))
            .collect();
        Self::IndexMap(Rc::new(v))
    }
}

impl Default for Attributes {
    fn default() -> Self {
        Self::Static(&[])
    }
}