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

yew/virtual_dom/
vtext.rs

1//! This module contains the implementation of a virtual text node `VText`.
2
3use super::AttrValue;
4use crate::html::ImplicitClone;
5
6/// A type for a virtual
7/// [`TextNode`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode)
8/// representation.
9#[derive(Clone, ImplicitClone)]
10pub struct VText {
11    /// Contains a text of the node.
12    pub text: AttrValue,
13}
14
15impl VText {
16    /// Creates new virtual text node with a content.
17    pub fn new(text: impl Into<AttrValue>) -> Self {
18        VText { text: text.into() }
19    }
20}
21
22impl std::fmt::Debug for VText {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        write!(f, "VText {{ text: \"{}\" }}", self.text)
25    }
26}
27
28impl PartialEq for VText {
29    fn eq(&self, other: &VText) -> bool {
30        self.text == other.text
31    }
32}
33
34impl<T: ToString> From<T> for VText {
35    fn from(value: T) -> Self {
36        VText::new(value.to_string())
37    }
38}
39
40#[cfg(feature = "ssr")]
41mod feat_ssr {
42
43    use std::fmt::Write;
44
45    use super::*;
46    use crate::feat_ssr::VTagKind;
47    use crate::html::AnyScope;
48    use crate::platform::fmt::BufWriter;
49
50    impl VText {
51        pub(crate) async fn render_into_stream(
52            &self,
53            w: &mut BufWriter,
54            _parent_scope: &AnyScope,
55            _hydratable: bool,
56            parent_vtag_kind: VTagKind,
57        ) {
58            _ = w.write_str(&match parent_vtag_kind {
59                VTagKind::Style => html_escape::encode_style(&self.text),
60                VTagKind::Script => html_escape::encode_script(&self.text),
61                VTagKind::Other => html_escape::encode_text(&self.text),
62            })
63        }
64    }
65}
66
67#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
68#[cfg(feature = "ssr")]
69#[cfg(test)]
70mod ssr_tests {
71    use tokio::test;
72
73    use crate::LocalServerRenderer as ServerRenderer;
74    use crate::prelude::*;
75
76    #[cfg_attr(not(target_os = "wasi"), test)]
77    #[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
78    async fn test_simple_str() {
79        #[component]
80        fn Comp() -> Html {
81            html! { "abc" }
82        }
83
84        let s = ServerRenderer::<Comp>::new()
85            .hydratable(false)
86            .render()
87            .await;
88
89        assert_eq!(s, r#"abc"#);
90    }
91}