arena.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. if let Some(root) = self.scopes[id.0].as_ref().try_root_node() {
  68. if let RenderReturn::Sync(Ok(node)) = unsafe { root.extend_lifetime_ref() } {
  69. self.drop_scope_inner(node)
  70. }
  71. }
  72. self.scopes[id.0].props.take();
  73. let scope = &mut self.scopes[id.0];
  74. // Drop all the hooks once the children are dropped
  75. // this means we'll drop hooks bottom-up
  76. for hook in scope.hook_list.get_mut().drain(..) {
  77. drop(unsafe { BumpBox::from_raw(hook) });
  78. }
  79. }
  80. fn drop_scope_inner(&mut self, node: &VNode) {
  81. node.clear_listeners();
  82. node.dynamic_nodes.iter().for_each(|node| match node {
  83. DynamicNode::Component(c) => {
  84. if let Some(f) = c.scope.get() {
  85. self.drop_scope(f)
  86. }
  87. }
  88. DynamicNode::Fragment(nodes) => {
  89. nodes.iter().for_each(|node| self.drop_scope_inner(node))
  90. }
  91. DynamicNode::Placeholder(t) => {
  92. self.try_reclaim(t.id.get().unwrap());
  93. }
  94. DynamicNode::Text(t) => {
  95. self.try_reclaim(t.id.get().unwrap());
  96. }
  97. });
  98. for root in node.root_ids {
  99. if let Some(id) = root.get() {
  100. if id.0 != 0 {
  101. self.try_reclaim(id);
  102. }
  103. }
  104. }
  105. }
  106. /// Descend through the tree, removing any borrowed props and listeners
  107. pub(crate) fn ensure_drop_safety(&self, scope: ScopeId) {
  108. let scope = &self.scopes[scope.0];
  109. // make sure we drop all borrowed props manually to guarantee that their drop implementation is called before we
  110. // run the hooks (which hold an &mut Reference)
  111. // recursively call ensure_drop_safety on all children
  112. let mut props = scope.borrowed_props.borrow_mut();
  113. props.drain(..).for_each(|comp| {
  114. let comp = unsafe { &*comp };
  115. if let Some(scope_id) = comp.scope.get() {
  116. self.ensure_drop_safety(scope_id);
  117. }
  118. drop(comp.props.take());
  119. });
  120. // Now that all the references are gone, we can safely drop our own references in our listeners.
  121. let mut listeners = scope.listeners.borrow_mut();
  122. listeners.drain(..).for_each(|listener| {
  123. let listener = unsafe { &*listener };
  124. if let AttributeValue::Listener(l) = &listener.value {
  125. _ = l.take();
  126. }
  127. });
  128. }
  129. }
  130. impl ElementPath {
  131. pub(crate) fn is_ascendant(&self, big: &&[u8]) -> bool {
  132. match *self {
  133. ElementPath::Deep(small) => small.len() <= big.len() && small == &big[..small.len()],
  134. ElementPath::Root(r) => big.len() == 1 && big[0] == r as u8,
  135. }
  136. }
  137. }
  138. impl PartialEq<&[u8]> for ElementPath {
  139. fn eq(&self, other: &&[u8]) -> bool {
  140. match *self {
  141. ElementPath::Deep(deep) => deep.eq(*other),
  142. ElementPath::Root(r) => other.len() == 1 && other[0] == r as u8,
  143. }
  144. }
  145. }