arena.rs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. let entry = self.elements.vacant_entry();
  35. let id = entry.key();
  36. entry.insert(ElementRef {
  37. template: template as *const _ as *mut _,
  38. path: ElementPath::Deep(path),
  39. });
  40. ElementId(id)
  41. }
  42. pub(crate) fn next_root(&mut self, template: &VNode, path: usize) -> ElementId {
  43. let entry = self.elements.vacant_entry();
  44. let id = entry.key();
  45. entry.insert(ElementRef {
  46. template: template as *const _ as *mut _,
  47. path: ElementPath::Root(path),
  48. });
  49. ElementId(id)
  50. }
  51. pub(crate) fn reclaim(&mut self, el: ElementId) {
  52. self.try_reclaim(el)
  53. .unwrap_or_else(|| panic!("cannot reclaim {:?}", el));
  54. }
  55. pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<ElementRef> {
  56. if el.0 == 0 {
  57. panic!(
  58. "Invalid element set to 0 - {:#?}",
  59. std::backtrace::Backtrace::force_capture()
  60. )
  61. }
  62. self.elements.try_remove(el.0)
  63. }
  64. pub(crate) fn update_template(&mut self, el: ElementId, node: &VNode) {
  65. let node: *const VNode = node as *const _;
  66. self.elements[el.0].template = unsafe { std::mem::transmute(node) };
  67. }
  68. // Drop a scope and all its children
  69. pub(crate) fn drop_scope(&mut self, id: ScopeId) {
  70. let scope = self.scopes.get(id.0).unwrap();
  71. if let Some(root) = scope.as_ref().try_root_node() {
  72. let root = unsafe { root.extend_lifetime_ref() };
  73. if let RenderReturn::Sync(Ok(node)) = root {
  74. self.drop_scope_inner(node)
  75. }
  76. }
  77. let scope = self.scopes.get_mut(id.0).unwrap();
  78. scope.props.take();
  79. // Drop all the hooks once the children are dropped
  80. // this means we'll drop hooks bottom-up
  81. for hook in scope.hook_list.get_mut().drain(..) {
  82. drop(unsafe { BumpBox::from_raw(hook) });
  83. }
  84. }
  85. fn drop_scope_inner(&mut self, node: &VNode) {
  86. for attr in node.dynamic_attrs {
  87. if let AttributeValue::Listener(l) = &attr.value {
  88. l.borrow_mut().take();
  89. }
  90. }
  91. for (idx, _) in node.template.roots.iter().enumerate() {
  92. match node.dynamic_root(idx) {
  93. Some(DynamicNode::Component(c)) => self.drop_scope(c.scope.get().unwrap()),
  94. Some(DynamicNode::Fragment(nodes)) => {
  95. for node in *nodes {
  96. self.drop_scope_inner(node);
  97. }
  98. }
  99. _ => {}
  100. }
  101. }
  102. }
  103. }
  104. impl ElementPath {
  105. pub(crate) fn is_ascendant(&self, big: &&[u8]) -> bool {
  106. match *self {
  107. ElementPath::Deep(small) => small.len() <= big.len() && small == &big[..small.len()],
  108. ElementPath::Root(r) => big.len() == 1 && big[0] == r as u8,
  109. }
  110. }
  111. }
  112. impl PartialEq<&[u8]> for ElementPath {
  113. fn eq(&self, other: &&[u8]) -> bool {
  114. match *self {
  115. ElementPath::Deep(deep) => deep.eq(*other),
  116. ElementPath::Root(r) => other.len() == 1 && other[0] == r as u8,
  117. }
  118. }
  119. }