arena.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. use crate::{nodes::RenderReturn, nodes::VNode, virtual_dom::VirtualDom, DynamicNode, ScopeId};
  2. use bumpalo::boxed::Box as BumpBox;
  3. /// An Element's unique identifier.
  4. ///
  5. /// `ElementId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is
  6. /// unmounted, then the `ElementId` will be reused for a new component.
  7. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  8. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
  9. pub struct ElementId(pub usize);
  10. pub(crate) struct ElementRef {
  11. // the pathway of the real element inside the template
  12. pub path: ElementPath,
  13. // The actual template
  14. pub template: *const VNode<'static>,
  15. }
  16. #[derive(Clone, Copy)]
  17. pub enum ElementPath {
  18. Deep(&'static [u8]),
  19. Root(usize),
  20. }
  21. impl ElementRef {
  22. pub(crate) fn null() -> Self {
  23. Self {
  24. template: std::ptr::null_mut(),
  25. path: ElementPath::Root(0),
  26. }
  27. }
  28. }
  29. impl VirtualDom {
  30. pub(crate) fn next_element(&mut self, template: &VNode, path: &'static [u8]) -> ElementId {
  31. self.next(template, ElementPath::Deep(path))
  32. }
  33. pub(crate) fn next_root(&mut self, template: &VNode, path: usize) -> ElementId {
  34. self.next(template, ElementPath::Root(path))
  35. }
  36. fn next(&mut self, template: &VNode, path: ElementPath) -> ElementId {
  37. let entry = self.elements.vacant_entry();
  38. let id = entry.key();
  39. entry.insert(ElementRef {
  40. template: template as *const _ as *mut _,
  41. path,
  42. });
  43. ElementId(id)
  44. }
  45. pub(crate) fn reclaim(&mut self, el: ElementId) {
  46. self.try_reclaim(el)
  47. .unwrap_or_else(|| panic!("cannot reclaim {:?}", el));
  48. }
  49. pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<ElementRef> {
  50. if el.0 == 0 {
  51. panic!(
  52. "Cannot reclaim the root element - {:#?}",
  53. std::backtrace::Backtrace::force_capture()
  54. );
  55. }
  56. self.elements.try_remove(el.0)
  57. }
  58. pub(crate) fn update_template(&mut self, el: ElementId, node: &VNode) {
  59. let node: *const VNode = node as *const _;
  60. self.elements[el.0].template = unsafe { std::mem::transmute(node) };
  61. }
  62. // Drop a scope and all its children
  63. pub(crate) fn drop_scope(&mut self, id: ScopeId) {
  64. if let Some(root) = self.scopes[id.0].as_ref().try_root_node() {
  65. if let RenderReturn::Sync(Ok(node)) = unsafe { root.extend_lifetime_ref() } {
  66. self.drop_scope_inner(node)
  67. }
  68. }
  69. self.scopes[id.0].props.take();
  70. // Drop all the hooks once the children are dropped
  71. // this means we'll drop hooks bottom-up
  72. self.scopes[id.0]
  73. .hook_list
  74. .get_mut()
  75. .drain(..)
  76. .for_each(|hook| drop(unsafe { BumpBox::from_raw(hook) }));
  77. }
  78. fn drop_scope_inner(&mut self, node: &VNode) {
  79. node.clear_listeners();
  80. node.dynamic_nodes.iter().for_each(|node| match node {
  81. DynamicNode::Component(c) => self.drop_scope(c.scope.get().unwrap()),
  82. DynamicNode::Fragment(nodes) => nodes
  83. .into_iter()
  84. .for_each(|node| self.drop_scope_inner(node)),
  85. DynamicNode::Placeholder(t) => {
  86. self.try_reclaim(t.get());
  87. }
  88. DynamicNode::Text(t) => {
  89. self.try_reclaim(t.id.get());
  90. }
  91. });
  92. for root in node.root_ids {
  93. let id = root.get();
  94. if id.0 != 0 {
  95. self.try_reclaim(id);
  96. }
  97. }
  98. }
  99. /// Descend through the tree, removing any borrowed props and listeners
  100. pub(crate) fn ensure_drop_safety(&self, scope: ScopeId) {
  101. let node = unsafe { self.scopes[scope.0].previous_frame().try_load_node() };
  102. // And now we want to make sure the previous frame has dropped anything that borrows self
  103. if let Some(RenderReturn::Sync(Ok(node))) = node {
  104. self.ensure_drop_safety_inner(node);
  105. }
  106. }
  107. fn ensure_drop_safety_inner(&self, node: &VNode) {
  108. node.clear_listeners();
  109. node.dynamic_nodes.iter().for_each(|child| match child {
  110. // Only descend if the props are borrowed
  111. DynamicNode::Component(c) if !c.static_props => {
  112. self.ensure_drop_safety(c.scope.get().unwrap());
  113. c.props.set(None);
  114. }
  115. DynamicNode::Fragment(f) => f
  116. .iter()
  117. .for_each(|node| self.ensure_drop_safety_inner(node)),
  118. _ => {}
  119. });
  120. }
  121. }
  122. impl ElementPath {
  123. pub(crate) fn is_ascendant(&self, big: &&[u8]) -> bool {
  124. match *self {
  125. ElementPath::Deep(small) => small.len() <= big.len() && small == &big[..small.len()],
  126. ElementPath::Root(r) => big.len() == 1 && big[0] == r as u8,
  127. }
  128. }
  129. }
  130. impl PartialEq<&[u8]> for ElementPath {
  131. fn eq(&self, other: &&[u8]) -> bool {
  132. match *self {
  133. ElementPath::Deep(deep) => deep.eq(*other),
  134. ElementPath::Root(r) => other.len() == 1 && other[0] == r as u8,
  135. }
  136. }
  137. }