1use crate::innerlude::ScopeOrder;
2use crate::{virtual_dom::VirtualDom, ScopeId};
3
4#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
10pub struct ElementId(pub usize);
11
12#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub(crate) struct MountId(pub(crate) usize);
19
20impl Default for MountId {
21 fn default() -> Self {
22 Self::PLACEHOLDER
23 }
24}
25
26impl MountId {
27 pub(crate) const PLACEHOLDER: Self = Self(usize::MAX);
28
29 pub(crate) fn as_usize(self) -> Option<usize> {
30 if self.mounted() {
31 Some(self.0)
32 } else {
33 None
34 }
35 }
36
37 #[allow(unused)]
38 pub(crate) fn mounted(self) -> bool {
39 self != Self::PLACEHOLDER
40 }
41}
42
43#[derive(Debug, Clone, Copy)]
44pub struct ElementRef {
45 pub(crate) path: ElementPath,
47
48 pub(crate) mount: MountId,
50}
51
52#[derive(Clone, Copy, Debug)]
53pub struct ElementPath {
54 pub(crate) path: &'static [u8],
55}
56
57impl VirtualDom {
58 pub(crate) fn next_element(&mut self) -> ElementId {
59 let mut elements = self.runtime.elements.borrow_mut();
60 ElementId(elements.insert(None))
61 }
62
63 pub(crate) fn reclaim(&mut self, el: ElementId) {
64 if !self.try_reclaim(el) {
65 tracing::error!("cannot reclaim {:?}", el);
66 }
67 }
68
69 pub(crate) fn try_reclaim(&mut self, el: ElementId) -> bool {
70 if el.0 == 0 || el.0 == usize::MAX {
72 return true;
73 }
74
75 let mut elements = self.runtime.elements.borrow_mut();
76 elements.try_remove(el.0).is_some()
77 }
78
79 pub(crate) fn drop_scope(&mut self, id: ScopeId) {
83 let height = {
84 let scope = self.scopes.remove(id.0);
85 let context = scope.state();
86 context.height
87 };
88
89 self.dirty_scopes.remove(&ScopeOrder::new(height, id));
90
91 self.resolved_scopes.retain(|s| s != &id);
93 }
94}
95
96impl ElementPath {
97 pub(crate) fn is_descendant(&self, small: &[u8]) -> bool {
98 small.len() <= self.path.len() && small == &self.path[..small.len()]
99 }
100}
101
102#[test]
103fn is_descendant() {
104 let event_path = ElementPath {
105 path: &[1, 2, 3, 4, 5],
106 };
107
108 assert!(event_path.is_descendant(&[1, 2, 3, 4, 5]));
109 assert!(event_path.is_descendant(&[1, 2, 3, 4]));
110 assert!(event_path.is_descendant(&[1, 2, 3]));
111 assert!(event_path.is_descendant(&[1, 2]));
112 assert!(event_path.is_descendant(&[1]));
113
114 assert!(!event_path.is_descendant(&[1, 2, 3, 4, 5, 6]));
115 assert!(!event_path.is_descendant(&[2, 3, 4]));
116}
117
118impl PartialEq<&[u8]> for ElementPath {
119 fn eq(&self, other: &&[u8]) -> bool {
120 self.path.eq(*other)
121 }
122}