arena.rs 6.4 KB

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