maple_core/
noderef.rs

1use std::cell::RefCell;
2use std::fmt;
3use std::rc::Rc;
4
5use web_sys::Node;
6
7/// A reference to a [`Node`] in the DOM.
8#[derive(Clone, PartialEq, Eq)]
9pub struct NodeRef(Rc<RefCell<Option<Node>>>);
10
11impl NodeRef {
12    /// Creates an empty [`NodeRef`].
13    pub fn new() -> Self {
14        Self(Rc::new(RefCell::new(None)))
15    }
16
17    /// Gets the [`Node`] stored inside the [`NodeRef`].
18    ///
19    /// # Panics
20    /// Panics if the [`NodeRef`] is not set yet.
21    ///
22    /// For a non panicking version, see [`NodeRef::try_get`].
23    pub fn get(&self) -> Node {
24        self.try_get().expect("NodeRef is not set")
25    }
26
27    /// Tries to get the [`Node`] stored inside the [`NodeRef`] or `None` if it is not yet set.
28    ///
29    /// For a panicking version, see [`NodeRef::get`].
30    pub fn try_get(&self) -> Option<Node> {
31        self.0.borrow().clone()
32    }
33
34    /// Sets the [`NodeRef`] with the specified [`Node`].
35    pub fn set(&self, node: Node) {
36        *self.0.borrow_mut() = Some(node);
37    }
38}
39
40impl Default for NodeRef {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46impl fmt::Debug for NodeRef {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.debug_tuple("NodeRef").field(&self.0.borrow()).finish()
49    }
50}