virtual_node/
vtext.rs

1use std::fmt;
2
3use crate::create_element::set_virtual_node_marker;
4use web_sys::Text;
5
6/// Represents a text node
7#[derive(PartialEq)]
8pub struct VText {
9    pub text: String,
10}
11
12impl VText {
13    /// Create an new `VText` instance with the specified text.
14    pub fn new<S>(text: S) -> Self
15    where
16        S: Into<String>,
17    {
18        VText { text: text.into() }
19    }
20
21    /// Return a `Text` element from a `VirtualNode`, typically right before adding it
22    /// into the DOM.
23    pub(crate) fn create_text_node(&self) -> Text {
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 VText {
34    fn from(text: &str) -> Self {
35        VText {
36            text: text.to_string(),
37        }
38    }
39}
40
41impl From<String> for VText {
42    fn from(text: String) -> Self {
43        VText { text }
44    }
45}
46
47impl fmt::Debug for VText {
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 VText {
55    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56        write!(f, "{}", self.text)
57    }
58}