paddle/display/text/
text_node.rs

1use web_sys::HtmlElement;
2
3use crate::{JsError, PaddleResult};
4
5#[derive(Debug)]
6pub struct TextNode {
7    dom_node: HtmlElement,
8    text: String,
9    dirty: bool,
10    z: i16,
11}
12
13impl TextNode {
14    pub fn new(dom_node: HtmlElement, text: String) -> Self {
15        TextNode {
16            text,
17            dom_node,
18            dirty: true,
19            z: 0,
20        }
21    }
22    /// Update the inner text (without redrawing it)
23    /// Performs string comparison and also a string copy when necessary
24    pub fn update(&mut self, text: &str) {
25        if self.dirty || text != self.text {
26            self.text.clear();
27            self.text.push_str(text);
28            self.dirty = true;
29        }
30    }
31    /// Same as `update` but takes ownership of string and avoids copying the string content
32    pub fn update_owned(&mut self, text: String) {
33        if self.dirty || text != self.text {
34            self.text = text;
35            self.dirty = true;
36        }
37    }
38    pub fn draw(&mut self) {
39        if self.dirty {
40            self.dom_node.set_text_content(Some(&self.text));
41            self.dirty = false;
42        }
43    }
44    pub fn delete(&self) -> Result<(), &'static str> {
45        if let Some(parent) = self.dom_node.parent_node() {
46            return parent
47                .remove_child(&self.dom_node)
48                .map(|_| ())
49                .map_err(|_| "Child vanished");
50        }
51        Ok(())
52    }
53    pub fn set_z(&self, z: i16) -> PaddleResult<()> {
54        if self.z != z {
55            self.dom_node
56                .style()
57                .set_property("z", &z.to_string())
58                .map_err(JsError::from_js_value)?;
59        }
60        Ok(())
61    }
62}