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

yew/virtual_dom/
key.rs

1//! This module contains the implementation yew's virtual nodes' keys.
2
3use std::fmt::{self, Display, Formatter};
4use std::ops::Deref;
5use std::rc::Rc;
6
7use crate::html::ImplicitClone;
8
9/// Represents the (optional) key of Yew's virtual nodes.
10///
11/// Keys are cheap to clone.
12#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
13pub struct Key {
14    key: Rc<str>,
15}
16
17impl Display for Key {
18    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
19        self.key.fmt(f)
20    }
21}
22
23impl Deref for Key {
24    type Target = str;
25
26    fn deref(&self) -> &str {
27        self.key.as_ref()
28    }
29}
30
31impl From<Rc<str>> for Key {
32    fn from(key: Rc<str>) -> Self {
33        Self { key }
34    }
35}
36
37impl From<&'_ str> for Key {
38    fn from(key: &'_ str) -> Self {
39        let key: Rc<str> = Rc::from(key);
40        Self::from(key)
41    }
42}
43
44impl ImplicitClone for Key {}
45
46macro_rules! key_impl_from_to_string {
47    ($type:ty) => {
48        impl From<$type> for Key {
49            fn from(key: $type) -> Self {
50                Self::from(key.to_string().as_str())
51            }
52        }
53    };
54}
55
56key_impl_from_to_string!(String);
57key_impl_from_to_string!(char);
58key_impl_from_to_string!(u8);
59key_impl_from_to_string!(u16);
60key_impl_from_to_string!(u32);
61key_impl_from_to_string!(u64);
62key_impl_from_to_string!(u128);
63key_impl_from_to_string!(usize);
64key_impl_from_to_string!(i8);
65key_impl_from_to_string!(i16);
66key_impl_from_to_string!(i32);
67key_impl_from_to_string!(i64);
68key_impl_from_to_string!(i128);
69key_impl_from_to_string!(isize);
70
71#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
72#[cfg(test)]
73mod test {
74    use std::rc::Rc;
75
76    use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
77
78    use crate::html;
79
80    wasm_bindgen_test_configure!(run_in_browser);
81
82    #[test]
83    fn all_key_conversions() {
84        let _ = html! {
85            <key="string literal">
86                <img key={"String".to_owned()} />
87                <p key={Rc::<str>::from("rc")}></p>
88                <key='a'>
89                    <p key=11_usize></p>
90                    <p key=12_u8></p>
91                    <p key=13_u16></p>
92                    <p key=14_u32></p>
93                    <p key=15_u64></p>
94                    <p key=15_u128></p>
95                    <p key=21_isize></p>
96                    <p key=22_i8></p>
97                    <p key=23_i16></p>
98                    <p key=24_i32></p>
99                    <p key=25_i128></p>
100                </>
101            </>
102        };
103    }
104}