Skip to main content

virtual_node/
vtext.rs

1use std::fmt;
2
3
4/// Represents a text node
5#[derive(PartialEq)]
6pub struct VText {
7    pub text: String,
8}
9
10impl VText {
11    /// Create an new `VText` instance with the specified text.
12    pub fn new<S>(text: S) -> Self
13    where
14        S: Into<String>,
15    {
16        VText { text: text.into() }
17    }
18
19    /// Return a `Text` element from a `VirtualNode`, typically right before adding it
20    /// into the DOM.
21    #[cfg(feature = "web")]
22    pub(crate) fn create_text_node(&self) -> web_sys::Text {
23        use crate::create_element::set_virtual_node_marker;
24
25        let document = web_sys::window().unwrap().document().unwrap();
26        let text = document.create_text_node(&self.text);
27
28        set_virtual_node_marker(&text);
29
30        text
31    }
32}
33
34impl From<&str> for VText {
35    fn from(text: &str) -> Self {
36        VText {
37            text: text.to_string(),
38        }
39    }
40}
41
42impl From<String> for VText {
43    fn from(text: String) -> Self {
44        VText { text }
45    }
46}
47
48impl fmt::Debug for VText {
49    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50        write!(f, "Text({})", self.text)
51    }
52}
53
54// Turn a VText into an HTML string
55impl fmt::Display for VText {
56    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57        write!(f, "{}", self.text)
58    }
59}