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