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