scope_arena.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. use crate::{
  2. any_props::{AnyProps, BoxedAnyProps},
  3. innerlude::{DirtyScope, ScopeState},
  4. nodes::RenderReturn,
  5. scope_context::Scope,
  6. scopes::ScopeId,
  7. virtual_dom::VirtualDom,
  8. };
  9. impl VirtualDom {
  10. pub(super) fn new_scope(&mut self, props: BoxedAnyProps, name: &'static str) -> &ScopeState {
  11. let parent_id = self.runtime.current_scope_id();
  12. let height = parent_id
  13. .and_then(|parent_id| self.runtime.get_state(parent_id).map(|f| f.height + 1))
  14. .unwrap_or(0);
  15. let entry = self.scopes.vacant_entry();
  16. let id = ScopeId(entry.key());
  17. let scope = entry.insert(ScopeState {
  18. runtime: self.runtime.clone(),
  19. context_id: id,
  20. props,
  21. last_rendered_node: Default::default(),
  22. });
  23. self.runtime
  24. .create_scope(Scope::new(name, id, parent_id, height));
  25. scope
  26. }
  27. pub(crate) fn run_scope(&mut self, scope_id: ScopeId) -> RenderReturn {
  28. debug_assert!(
  29. crate::Runtime::current().is_some(),
  30. "Must be in a dioxus runtime"
  31. );
  32. self.runtime.scope_stack.borrow_mut().push(scope_id);
  33. let scope = &self.scopes[scope_id.0];
  34. let new_nodes = {
  35. let context = scope.state();
  36. context.suspended.set(false);
  37. context.hook_index.set(0);
  38. // Run all pre-render hooks
  39. for pre_run in context.before_render.borrow_mut().iter_mut() {
  40. pre_run();
  41. }
  42. // safety: due to how we traverse the tree, we know that the scope is not currently aliased
  43. let props: &dyn AnyProps = &*scope.props;
  44. let span = tracing::trace_span!("render", scope = %scope.state().name);
  45. span.in_scope(|| props.render())
  46. };
  47. let context = scope.state();
  48. // Run all post-render hooks
  49. for post_run in context.after_render.borrow_mut().iter_mut() {
  50. post_run();
  51. }
  52. // And move the render generation forward by one
  53. context.render_count.set(context.render_count.get() + 1);
  54. // remove this scope from dirty scopes
  55. self.dirty_scopes.remove(&DirtyScope {
  56. height: context.height,
  57. id: context.id,
  58. });
  59. if context.suspended.get() {
  60. if matches!(new_nodes, RenderReturn::Aborted(_)) {
  61. self.suspended_scopes.insert(context.id);
  62. }
  63. } else if !self.suspended_scopes.is_empty() {
  64. _ = self.suspended_scopes.remove(&context.id);
  65. }
  66. self.runtime.scope_stack.borrow_mut().pop();
  67. new_nodes
  68. }
  69. }