arena.rs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. use crate::{
  2. nodes::RenderReturn, nodes::VNode, virtual_dom::VirtualDom, AttributeValue, DynamicNode,
  3. ScopeId,
  4. };
  5. use bumpalo::boxed::Box as BumpBox;
  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: *const VNode<'static>,
  18. }
  19. #[derive(Clone, Copy)]
  20. pub enum ElementPath {
  21. Deep(&'static [u8]),
  22. Root(usize),
  23. }
  24. impl ElementRef {
  25. pub(crate) fn null() -> Self {
  26. Self {
  27. template: std::ptr::null_mut(),
  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. fn next_reference(&mut self, template: &VNode, path: ElementPath) -> ElementId {
  40. let entry = self.elements.vacant_entry();
  41. let id = entry.key();
  42. entry.insert(ElementRef {
  43. template: template as *const _ as *mut _,
  44. path,
  45. });
  46. ElementId(id)
  47. }
  48. pub(crate) fn reclaim(&mut self, el: ElementId) {
  49. self.try_reclaim(el)
  50. .unwrap_or_else(|| panic!("cannot reclaim {:?}", el));
  51. }
  52. pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<ElementRef> {
  53. if el.0 == 0 {
  54. panic!(
  55. "Cannot reclaim the root element - {:#?}",
  56. std::backtrace::Backtrace::force_capture()
  57. );
  58. }
  59. self.elements.try_remove(el.0)
  60. }
  61. pub(crate) fn update_template(&mut self, el: ElementId, node: &VNode) {
  62. let node: *const VNode = node as *const _;
  63. self.elements[el.0].template = unsafe { std::mem::transmute(node) };
  64. }
  65. // Drop a scope and all its children
  66. pub(crate) fn drop_scope(&mut self, id: ScopeId) {
  67. self.ensure_drop_safety(id);
  68. if let Some(root) = self.scopes[id.0].as_ref().try_root_node() {
  69. if let RenderReturn::Sync(Ok(node)) = unsafe { root.extend_lifetime_ref() } {
  70. self.drop_scope_inner(node)
  71. }
  72. }
  73. if let Some(root) = unsafe { self.scopes[id.0].as_ref().previous_frame().try_load_node() } {
  74. if let RenderReturn::Sync(Ok(node)) = unsafe { root.extend_lifetime_ref() } {
  75. self.drop_scope_inner(node)
  76. }
  77. }
  78. self.scopes[id.0].props.take();
  79. let scope = &mut self.scopes[id.0];
  80. // Drop all the hooks once the children are dropped
  81. // this means we'll drop hooks bottom-up
  82. for hook in scope.hook_list.get_mut().drain(..) {
  83. drop(unsafe { BumpBox::from_raw(hook) });
  84. }
  85. }
  86. fn drop_scope_inner(&mut self, node: &VNode) {
  87. node.clear_listeners();
  88. node.dynamic_nodes.iter().for_each(|node| match node {
  89. DynamicNode::Component(c) => {
  90. if let Some(f) = c.scope.get() {
  91. self.drop_scope(f);
  92. }
  93. c.props.take();
  94. }
  95. DynamicNode::Fragment(nodes) => {
  96. nodes.iter().for_each(|node| self.drop_scope_inner(node))
  97. }
  98. DynamicNode::Placeholder(t) => {
  99. self.try_reclaim(t.id.get().unwrap());
  100. }
  101. DynamicNode::Text(t) => {
  102. self.try_reclaim(t.id.get().unwrap());
  103. }
  104. });
  105. for root in node.root_ids {
  106. if let Some(id) = root.get() {
  107. if id.0 != 0 {
  108. self.try_reclaim(id);
  109. }
  110. }
  111. }
  112. }
  113. /// Descend through the tree, removing any borrowed props and listeners
  114. pub(crate) fn ensure_drop_safety(&self, scope: ScopeId) {
  115. let scope = &self.scopes[scope.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. if let Some(scope_id) = comp.scope.get() {
  123. self.ensure_drop_safety(scope_id);
  124. }
  125. drop(comp.props.take());
  126. });
  127. // Now that all the references are gone, we can safely drop our own references in our listeners.
  128. let mut listeners = scope.listeners.borrow_mut();
  129. listeners.drain(..).for_each(|listener| {
  130. let listener = unsafe { &*listener };
  131. if let AttributeValue::Listener(l) = &listener.value {
  132. _ = l.0.take();
  133. }
  134. });
  135. }
  136. }
  137. impl ElementPath {
  138. pub(crate) fn is_ascendant(&self, big: &&[u8]) -> bool {
  139. match *self {
  140. ElementPath::Deep(small) => small.len() <= big.len() && small == &big[..small.len()],
  141. ElementPath::Root(r) => big.len() == 1 && big[0] == r as u8,
  142. }
  143. }
  144. }
  145. impl PartialEq<&[u8]> for ElementPath {
  146. fn eq(&self, other: &&[u8]) -> bool {
  147. match *self {
  148. ElementPath::Deep(deep) => deep.eq(*other),
  149. ElementPath::Root(r) => other.len() == 1 && other[0] == r as u8,
  150. }
  151. }
  152. }