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 From<String> for Key {
45    fn from(key: String) -> Self {
46        Self::from(key.as_str())
47    }
48}
49
50impl ImplicitClone for Key {}
51
52macro_rules! key_impl_from_to_string {
53    ($type:ty) => {
54        impl From<$type> for Key {
55            fn from(key: $type) -> Self {
56                Self::from(key.to_string().as_str())
57            }
58        }
59    };
60}
61
62key_impl_from_to_string!(char);
63key_impl_from_to_string!(u8);
64key_impl_from_to_string!(u16);
65key_impl_from_to_string!(u32);
66key_impl_from_to_string!(u64);
67key_impl_from_to_string!(u128);
68key_impl_from_to_string!(usize);
69key_impl_from_to_string!(i8);
70key_impl_from_to_string!(i16);
71key_impl_from_to_string!(i32);
72key_impl_from_to_string!(i64);
73key_impl_from_to_string!(i128);
74key_impl_from_to_string!(isize);
75
76#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
77#[cfg(test)]
78mod test {
79    use std::rc::Rc;
80
81    use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
82
83    use crate::html;
84
85    wasm_bindgen_test_configure!(run_in_browser);
86
87    #[test]
88    fn all_key_conversions() {
89        let _ = html! {
90            <key="string literal">
91                <img key={"String".to_owned()} />
92                <p key={Rc::<str>::from("rc")}></p>
93                <key='a'>
94                    <p key=11_usize></p>
95                    <p key=12_u8></p>
96                    <p key=13_u16></p>
97                    <p key=14_u32></p>
98                    <p key=15_u64></p>
99                    <p key=15_u128></p>
100                    <p key=21_isize></p>
101                    <p key=22_i8></p>
102                    <p key=23_i16></p>
103                    <p key=24_i32></p>
104                    <p key=25_i128></p>
105                </>
106            </>
107        };
108    }
109}