Skip to main content

virtual_node/
vtext.rs

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