arena.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. use std::ptr::NonNull;
  2. use crate::{
  3. innerlude::DirtyScope, nodes::RenderReturn, nodes::VNode, virtual_dom::VirtualDom,
  4. AttributeValue, DynamicNode, ScopeId,
  5. };
  6. /// An Element's unique identifier.
  7. ///
  8. /// `ElementId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is
  9. /// unmounted, then the `ElementId` will be reused for a new component.
  10. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  11. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
  12. pub struct ElementId(pub usize);
  13. pub(crate) struct ElementRef {
  14. // the pathway of the real element inside the template
  15. pub path: ElementPath,
  16. // The actual template
  17. pub template: Option<NonNull<VNode<'static>>>,
  18. }
  19. #[derive(Clone, Copy, Debug)]
  20. pub enum ElementPath {
  21. Deep(&'static [u8]),
  22. Root(usize),
  23. }
  24. impl ElementRef {
  25. pub(crate) fn none() -> Self {
  26. Self {
  27. template: None,
  28. path: ElementPath::Root(0),
  29. }
  30. }
  31. }
  32. impl VirtualDom {
  33. pub(crate) fn next_element(&mut self, template: &VNode, path: &'static [u8]) -> ElementId {
  34. self.next_reference(template, ElementPath::Deep(path))
  35. }
  36. pub(crate) fn next_root(&mut self, template: &VNode, path: usize) -> ElementId {
  37. self.next_reference(template, ElementPath::Root(path))
  38. }
  39. pub(crate) fn next_null(&mut self) -> ElementId {
  40. let entry = self.elements.vacant_entry();
  41. let id = entry.key();
  42. entry.insert(ElementRef::none());
  43. ElementId(id)
  44. }
  45. fn next_reference(&mut self, template: &VNode, path: ElementPath) -> ElementId {
  46. let entry = self.elements.vacant_entry();
  47. let id = entry.key();
  48. entry.insert(ElementRef {
  49. // We know this is non-null because it comes from a reference
  50. template: Some(unsafe { NonNull::new_unchecked(template as *const _ as *mut _) }),
  51. path,
  52. });
  53. ElementId(id)
  54. }
  55. pub(crate) fn reclaim(&mut self, el: ElementId) {
  56. self.try_reclaim(el)
  57. .unwrap_or_else(|| panic!("cannot reclaim {:?}", el));
  58. }
  59. pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<ElementRef> {
  60. if el.0 == 0 {
  61. panic!(
  62. "Cannot reclaim the root element - {:#?}",
  63. std::backtrace::Backtrace::force_capture()
  64. );
  65. }
  66. self.elements.try_remove(el.0)
  67. }
  68. pub(crate) fn update_template(&mut self, el: ElementId, node: &VNode) {
  69. let node: *const VNode = node as *const _;
  70. self.elements[el.0].template = unsafe { std::mem::transmute(node) };
  71. }
  72. // Drop a scope and all its children
  73. //
  74. // Note: This will not remove any ids from the arena
  75. pub(crate) fn drop_scope(&mut self, id: ScopeId, recursive: bool) {
  76. self.dirty_scopes.remove(&DirtyScope {
  77. height: self.scopes[id.0].height,
  78. id,
  79. });
  80. self.ensure_drop_safety(id);
  81. if recursive {
  82. if let Some(root) = self.scopes[id.0].try_root_node() {
  83. if let RenderReturn::Ready(node) = unsafe { root.extend_lifetime_ref() } {
  84. self.drop_scope_inner(node)
  85. }
  86. }
  87. }
  88. let scope = &mut self.scopes[id.0];
  89. // Drop all the hooks once the children are dropped
  90. // this means we'll drop hooks bottom-up
  91. scope.hooks.get_mut().clear();
  92. // Drop all the futures once the hooks are dropped
  93. for task_id in scope.spawned_tasks.borrow_mut().drain() {
  94. scope.tasks.remove(task_id);
  95. }
  96. self.scopes.remove(id.0);
  97. }
  98. fn drop_scope_inner(&mut self, node: &VNode) {
  99. node.dynamic_nodes.iter().for_each(|node| match node {
  100. DynamicNode::Component(c) => {
  101. if let Some(f) = c.scope.get() {
  102. self.drop_scope(f, true);
  103. }
  104. c.props.take();
  105. }
  106. DynamicNode::Fragment(nodes) => {
  107. nodes.iter().for_each(|node| self.drop_scope_inner(node))
  108. }
  109. DynamicNode::Placeholder(_) => {}
  110. DynamicNode::Text(_) => {}
  111. });
  112. }
  113. /// Descend through the tree, removing any borrowed props and listeners
  114. pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
  115. let scope = &self.scopes[scope_id.0];
  116. // make sure we drop all borrowed props manually to guarantee that their drop implementation is called before we
  117. // run the hooks (which hold an &mut Reference)
  118. // recursively call ensure_drop_safety on all children
  119. let mut props = scope.borrowed_props.borrow_mut();
  120. props.drain(..).for_each(|comp| {
  121. let comp = unsafe { &*comp };
  122. match comp.scope.get() {
  123. Some(child) if child != scope_id => self.ensure_drop_safety(child),
  124. _ => (),
  125. }
  126. if let Ok(mut props) = comp.props.try_borrow_mut() {
  127. *props = None;
  128. }
  129. });
  130. // Now that all the references are gone, we can safely drop our own references in our listeners.
  131. let mut listeners = scope.attributes_to_drop.borrow_mut();
  132. listeners.drain(..).for_each(|listener| {
  133. let listener = unsafe { &*listener };
  134. match &listener.value {
  135. AttributeValue::Listener(l) => {
  136. _ = l.take();
  137. }
  138. AttributeValue::Any(a) => {
  139. _ = a.take();
  140. }
  141. _ => (),
  142. }
  143. });
  144. }
  145. }
  146. impl ElementPath {
  147. pub(crate) fn is_decendant(&self, small: &&[u8]) -> bool {
  148. match *self {
  149. ElementPath::Deep(big) => small.len() <= big.len() && *small == &big[..small.len()],
  150. ElementPath::Root(r) => small.len() == 1 && small[0] == r as u8,
  151. }
  152. }
  153. }
  154. impl PartialEq<&[u8]> for ElementPath {
  155. fn eq(&self, other: &&[u8]) -> bool {
  156. match *self {
  157. ElementPath::Deep(deep) => deep.eq(*other),
  158. ElementPath::Root(r) => other.len() == 1 && other[0] == r as u8,
  159. }
  160. }
  161. }