Merge branch 'master' into cli-serde-default

This commit is contained in:
Evan Almloff committed 2023-09-17 19:00:13 -05:00
commit 070ef6aec9
465 files changed
+5887 -14677

No files matched your search

+2 -1
View File
@@ -28,7 +28,7 @@ slab = { workspace = true }
futures-channel = { workspace = true }
smallbox = "0.8.1"
log = { workspace = true }
tracing = { workspace = true }
# Serialize the Edits for use in Webview/Liveview instances
serde = { version = "1", features = ["derive"], optional = true }
@@ -39,6 +39,7 @@ dioxus = { workspace = true }
pretty_assertions = "1.3.0"
rand = "0.8.5"
dioxus-ssr = { workspace = true }
trybuild = "1.0"
[features]
default = []
@@ -0,0 +1,32 @@
use dioxus::prelude::*;
fn main() {}
fn app(cx: Scope) -> Element {
let count: &RefCell<Vec<Element>> = cx.use_hook(|| RefCell::new(Vec::new()));
render! {
unsafe_child_component {
borrowed: count
}
}
}
#[derive(Props)]
struct Testing<'a> {
borrowed: &'a RefCell<Vec<Element<'a>>>,
}
fn unsafe_child_component<'a>(cx: Scope<'a, Testing<'a>>) -> Element<'a> {
let Testing { borrowed } = cx.props;
let borrowed_temporary_data =
cx.use_hook(|| String::from("This data is only valid for the lifetime of the child"));
borrowed
.borrow_mut()
.push(render! {"{borrowed_temporary_data}"});
cx.render(rsx! {
div { "Hello, world!" }
})
}
@@ -0,0 +1,20 @@
error[E0521]: borrowed data escapes outside of function
--> compile_tests/props_safety.rs:8:5
|
5 | fn app(cx: Scope) -> Element {
| --
| |
| `cx` is a reference that is only valid in the function body
| has type `&'1 Scoped<'1>`
...
8 | / render! {
9 | | unsafe_child_component {
10 | | borrowed: count
11 | | }
12 | | }
| | ^
| | |
| |_____`cx` escapes the function body here
| argument requires that `'1` must outlive `'static`
|
= note: this error originates in the macro `render` (in Nightly builds, run with -Z macro-backtrace for more info)
@@ -0,0 +1,24 @@
use dioxus::prelude::*;
fn main() {}
fn app(cx: Scope) -> Element {
let count = vec![1, 2, 3];
render! {
unsafe_child_component {
borrowed: &count
}
}
}
#[derive(Props)]
struct Testing<'a> {
borrowed: &'a Vec<u32>,
}
fn unsafe_child_component<'a>(cx: Scope<'a, Testing<'a>>) -> Element<'a> {
cx.render(rsx! {
div { "{cx.props.borrowed:?}" }
})
}
@@ -0,0 +1,12 @@
error[E0515]: cannot return value referencing local variable `count`
--> compile_tests/props_safety_temporary_values.rs:8:5
|
8 | / render! {
9 | | unsafe_child_component {
10 | | borrowed: &count
| | ------ `count` is borrowed here
11 | | }
12 | | }
| |_____^ returns a value referencing data owned by the current function
|
= note: this error originates in the macro `render` (in Nightly builds, run with -Z macro-backtrace for more info)
+1 -1
View File
@@ -68,7 +68,7 @@ unsafe impl<'a, P> AnyProps<'a> for VProps<'a, P> {
Ok(None) => RenderReturn::default(),
Err(err) => {
let component_name = cx.name();
log::error!("Error while rendering component `{component_name}`: {err:?}");
tracing::error!("Error while rendering component `{component_name}`: {err:?}");
RenderReturn::default()
}
}
+13 -4
View File
@@ -19,6 +19,9 @@ pub(crate) struct ElementRef {
// The actual template
pub template: Option<NonNull<VNode<'static>>>,
// The scope the element belongs to
pub scope: ScopeId,
}
#[derive(Clone, Copy, Debug)]
@@ -32,6 +35,7 @@ impl ElementRef {
Self {
template: None,
path: ElementPath::Root(0),
scope: ScopeId::ROOT,
}
}
}
@@ -56,11 +60,13 @@ impl VirtualDom {
fn next_reference(&mut self, template: &VNode, path: ElementPath) -> ElementId {
let entry = self.elements.vacant_entry();
let id = entry.key();
let scope = self.runtime.current_scope_id().unwrap_or(ScopeId::ROOT);
entry.insert(ElementRef {
// We know this is non-null because it comes from a reference
template: Some(unsafe { NonNull::new_unchecked(template as *const _ as *mut _) }),
path,
scope,
});
ElementId(id)
}
@@ -91,7 +97,7 @@ impl VirtualDom {
// Note: This will not remove any ids from the arena
pub(crate) fn drop_scope(&mut self, id: ScopeId, recursive: bool) {
self.dirty_scopes.remove(&DirtyScope {
height: self.scopes[id.0].height,
height: self.scopes[id.0].height(),
id,
});
@@ -110,10 +116,13 @@ impl VirtualDom {
// Drop all the hooks once the children are dropped
// this means we'll drop hooks bottom-up
scope.hooks.get_mut().clear();
{
let context = scope.context();
// Drop all the futures once the hooks are dropped
for task_id in scope.spawned_tasks.borrow_mut().drain() {
scope.tasks.remove(task_id);
// Drop all the futures once the hooks are dropped
for task_id in context.spawned_tasks.borrow_mut().drain() {
context.tasks.remove(task_id);
}
}
self.scopes.remove(id.0);
+11 -7
View File
@@ -66,10 +66,10 @@ impl<'b> VirtualDom {
///
/// This method pushes the ScopeID to the internal scopestack and returns the number of nodes created.
pub(crate) fn create_scope(&mut self, scope: ScopeId, template: &'b VNode<'b>) -> usize {
self.scope_stack.push(scope);
let out = self.create(template);
self.scope_stack.pop();
out
self.runtime.scope_stack.borrow_mut().push(scope);
let nodes = self.create(template);
self.runtime.scope_stack.borrow_mut().pop();
nodes
}
/// Create this template and write its mutations
@@ -87,8 +87,12 @@ impl<'b> VirtualDom {
}
}
// Intialize the root nodes slice
*node.root_ids.borrow_mut() = vec![ElementId(0); node.template.get().roots.len()];
// Initialize the root nodes slice
{
let mut nodes_mut = node.root_ids.borrow_mut();
let len = node.template.get().roots.len();
nodes_mut.resize(len, ElementId::default());
};
// The best renderers will have templates prehydrated and registered
// Just in case, let's create the template using instructions anyways
@@ -522,7 +526,7 @@ impl<'b> VirtualDom {
.take()
.map(|props| {
let unbounded_props: Box<dyn AnyProps> = unsafe { std::mem::transmute(props) };
self.new_scope(unbounded_props, component.name).id
self.new_scope(unbounded_props, component.name).context().id
})
.unwrap_or_else(|| component.scope.get().unwrap())
}
+43 -13
View File
@@ -15,9 +15,8 @@ use DynamicNode::*;
impl<'b> VirtualDom {
pub(super) fn diff_scope(&mut self, scope: ScopeId) {
let scope_state = &mut self.scopes[scope.0];
self.scope_stack.push(scope);
self.runtime.scope_stack.borrow_mut().push(scope);
let scope_state = &mut self.get_scope(scope).unwrap();
unsafe {
// Load the old and new bump arenas
let old = scope_state
@@ -47,7 +46,7 @@ impl<'b> VirtualDom {
(Aborted(l), Ready(r)) => self.replace_placeholder(l, [r]),
};
}
self.scope_stack.pop();
self.runtime.scope_stack.borrow_mut().pop();
}
fn diff_ok_to_err(&mut self, l: &'b VNode<'b>, p: &'b VPlaceholder) {
@@ -129,7 +128,13 @@ impl<'b> VirtualDom {
});
// Make sure the roots get transferred over while we're here
*right_template.root_ids.borrow_mut() = left_template.root_ids.borrow().clone();
{
let mut right = right_template.root_ids.borrow_mut();
right.clear();
for &element in left_template.root_ids.borrow().iter() {
right.push(element);
}
}
let root_ids = right_template.root_ids.borrow();
@@ -191,7 +196,8 @@ impl<'b> VirtualDom {
right.scope.set(Some(scope_id));
// copy out the box for both
let old = self.scopes[scope_id.0].props.as_ref();
let old_scope = &self.scopes[scope_id.0];
let old = old_scope.props.as_ref();
let new: Box<dyn AnyProps> = right.props.take().unwrap();
let new: Box<dyn AnyProps> = unsafe { std::mem::transmute(new) };
@@ -199,6 +205,11 @@ impl<'b> VirtualDom {
// The target scopestate still has the reference to the old props, so there's no need to update anything
// This also implicitly drops the new props since they're not used
if left.static_props && unsafe { old.as_ref().unwrap().memoize(new.as_ref()) } {
tracing::trace!(
"Memoized props for component {:#?} ({})",
scope_id,
old_scope.context().name
);
return;
}
@@ -210,7 +221,7 @@ impl<'b> VirtualDom {
self.diff_scope(scope_id);
self.dirty_scopes.remove(&DirtyScope {
height: self.scopes[scope_id.0].height,
height: self.runtime.get_context(scope_id).unwrap().height,
id: scope_id,
});
}
@@ -572,8 +583,7 @@ impl<'b> VirtualDom {
}
// 4. Compute the LIS of this list
let mut lis_sequence = Vec::default();
lis_sequence.reserve(new_index_to_old_index.len());
let mut lis_sequence = Vec::with_capacity(new_index_to_old_index.len());
let mut predecessors = vec![0; new_index_to_old_index.len()];
let mut starts = vec![0; new_index_to_old_index.len()];
@@ -714,7 +724,12 @@ impl<'b> VirtualDom {
Component(comp) => {
let scope = comp.scope.get().unwrap();
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
match unsafe {
self.get_scope(scope)
.unwrap()
.root_node()
.extend_lifetime_ref()
} {
RenderReturn::Ready(node) => self.push_all_real_nodes(node),
RenderReturn::Aborted(_node) => todo!(),
}
@@ -915,7 +930,12 @@ impl<'b> VirtualDom {
.expect("VComponents to always have a scope");
// Remove the component from the dom
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
match unsafe {
self.get_scope(scope)
.unwrap()
.root_node()
.extend_lifetime_ref()
} {
RenderReturn::Ready(t) => self.remove_node(t, gen_muts),
RenderReturn::Aborted(placeholder) => self.remove_placeholder(placeholder, gen_muts),
};
@@ -936,7 +956,12 @@ impl<'b> VirtualDom {
Some(Placeholder(t)) => t.id.get().unwrap(),
Some(Component(comp)) => {
let scope = comp.scope.get().unwrap();
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
match unsafe {
self.get_scope(scope)
.unwrap()
.root_node()
.extend_lifetime_ref()
} {
RenderReturn::Ready(t) => self.find_first_element(t),
_ => todo!("cannot handle nonstandard nodes"),
}
@@ -952,7 +977,12 @@ impl<'b> VirtualDom {
Some(Placeholder(t)) => t.id.get().unwrap(),
Some(Component(comp)) => {
let scope = comp.scope.get().unwrap();
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
match unsafe {
self.get_scope(scope)
.unwrap()
.root_node()
.extend_lifetime_ref()
} {
RenderReturn::Ready(t) => self.find_last_element(t),
_ => todo!("cannot handle nonstandard nodes"),
}
+12 -15
View File
@@ -49,17 +49,16 @@ impl ErrorBoundary {
/// A trait to allow results to be thrown upwards to the nearest Error Boundary
///
/// The canonical way of using this trait is to throw results from hooks, aborting rendering
/// through question mark synax. The throw method returns an option that evalutes to None
/// through question mark syntax. The throw method returns an option that evaluates to None
/// if there is an error, injecting the error to the nearest error boundary.
///
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
///
/// The call stack is saved for this component and provided to the error boundary
///
/// ```rust, ignore
///
/// #[inline_props]
/// fn app(cx: Scope, count: String) -> Element {
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
///
/// cx.render(rsx! {
@@ -71,9 +70,9 @@ pub trait Throw<S = ()>: Sized {
/// The value that will be returned in if the given value is `Ok`.
type Out;
/// Returns an option that evalutes to None if there is an error, injecting the error to the nearest error boundary.
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
///
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
///
/// The call stack is saved for this component and provided to the error boundary
///
@@ -83,9 +82,8 @@ pub trait Throw<S = ()>: Sized {
///
///
/// ```rust, ignore
///
/// #[inline_props]
/// fn app(cx: Scope, count: String) -> Element {
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
///
/// cx.render(rsx! {
@@ -95,9 +93,9 @@ pub trait Throw<S = ()>: Sized {
/// ```
fn throw(self, cx: &ScopeState) -> Option<Self::Out>;
/// Returns an option that evalutes to None if there is an error, injecting the error to the nearest error boundary.
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
///
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
///
/// The call stack is saved for this component and provided to the error boundary
///
@@ -107,9 +105,8 @@ pub trait Throw<S = ()>: Sized {
///
///
/// ```rust, ignore
///
/// #[inline_props]
/// fn app(cx: Scope, count: String) -> Element {
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
///
/// cx.render(rsx! {
+10 -1
View File
@@ -1,3 +1,4 @@
use crate::{runtime::with_runtime, ScopeId};
use std::{
cell::{Cell, RefCell},
rc::Rc,
@@ -117,7 +118,7 @@ impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> {
///
/// ```rust, ignore
/// rsx!{
/// MyComponent { onclick: move |evt| log::info!("clicked") }
/// MyComponent { onclick: move |evt| tracing::debug!("clicked") }
/// }
///
/// #[derive(Props)]
@@ -135,12 +136,14 @@ impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> {
///
/// ```
pub struct EventHandler<'bump, T = ()> {
pub(crate) origin: ScopeId,
pub(super) callback: RefCell<Option<ExternalListenerCallback<'bump, T>>>,
}
impl<T> Default for EventHandler<'_, T> {
fn default() -> Self {
Self {
origin: ScopeId::ROOT,
callback: Default::default(),
}
}
@@ -154,7 +157,13 @@ impl<T> EventHandler<'_, T> {
/// This borrows the event using a RefCell. Recursively calling a listener will cause a panic.
pub fn call(&self, event: T) {
if let Some(callback) = self.callback.borrow_mut().as_mut() {
with_runtime(|rt| {
rt.scope_stack.borrow_mut().push(self.origin);
});
callback(event);
with_runtime(|rt| {
rt.scope_stack.borrow_mut().pop();
});
}
}
+15 -7
View File
@@ -14,8 +14,10 @@ mod lazynodes;
mod mutations;
mod nodes;
mod properties;
mod runtime;
mod scheduler;
mod scope_arena;
mod scope_context;
mod scopes;
mod virtual_dom;
@@ -30,7 +32,9 @@ pub(crate) mod innerlude {
pub use crate::nodes::RenderReturn;
pub use crate::nodes::*;
pub use crate::properties::*;
pub use crate::runtime::{in_runtime, override_runtime, Runtime};
pub use crate::scheduler::*;
pub use crate::scope_context::*;
pub use crate::scopes::*;
pub use crate::virtual_dom::*;
@@ -70,10 +74,11 @@ pub(crate) mod innerlude {
}
pub use crate::innerlude::{
fc_to_builder, AnyValue, Attribute, AttributeValue, BorrowedAttributeValue, CapturedError,
Component, DynamicNode, Element, ElementId, Event, Fragment, IntoDynNode, LazyNodes, Mutation,
Mutations, Properties, RenderReturn, Scope, ScopeId, ScopeState, Scoped, TaskId, Template,
TemplateAttribute, TemplateNode, VComponent, VNode, VPlaceholder, VText, VirtualDom,
fc_to_builder, vdom_is_rendering, AnyValue, Attribute, AttributeValue, BorrowedAttributeValue,
CapturedError, Component, DynamicNode, Element, ElementId, Event, Fragment, IntoDynNode,
LazyNodes, Mutation, Mutations, Properties, RenderReturn, Scope, ScopeId, ScopeState, Scoped,
TaskId, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VPlaceholder, VText,
VirtualDom,
};
/// The purpose of this module is to alleviate imports of many common types
@@ -81,9 +86,12 @@ pub use crate::innerlude::{
/// This includes types like [`Scope`], [`Element`], and [`Component`].
pub mod prelude {
pub use crate::innerlude::{
fc_to_builder, AnyValue, Component, Element, Event, EventHandler, Fragment,
IntoAttributeValue, LazyNodes, Properties, Scope, ScopeId, ScopeState, Scoped, TaskId,
Template, TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
consume_context, consume_context_from_scope, current_scope_id, fc_to_builder, has_context,
in_runtime, override_runtime, provide_context, provide_context_to_scope,
provide_root_context, push_future, remove_future, schedule_update_any, spawn,
spawn_forever, suspend, throw, AnyValue, Component, Element, Event, EventHandler, Fragment,
IntoAttributeValue, LazyNodes, Properties, Runtime, Scope, ScopeId, ScopeState, Scoped,
TaskId, Template, TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
};
}
+9 -9
View File
@@ -54,7 +54,7 @@ pub struct VNode<'a> {
/// The IDs for the roots of this template - to be used when moving the template around and removing it from
/// the actual Dom
pub root_ids: RefCell<Vec<ElementId>>,
pub root_ids: RefCell<bumpalo::collections::Vec<'a, ElementId>>,
/// The dynamic parts of the template
pub dynamic_nodes: &'a [DynamicNode<'a>],
@@ -65,11 +65,11 @@ pub struct VNode<'a> {
impl<'a> VNode<'a> {
/// Create a template with no nodes that will be skipped over during diffing
pub fn empty() -> Element<'a> {
pub fn empty(cx: &'a ScopeState) -> Element<'a> {
Some(VNode {
key: None,
parent: None,
root_ids: Default::default(),
root_ids: RefCell::new(bumpalo::collections::Vec::new_in(cx.bump())),
dynamic_nodes: &[],
dynamic_attrs: &[],
template: Cell::new(Template {
@@ -691,14 +691,14 @@ impl<'a> IntoDynNode<'a> for &Element<'a> {
impl<'a, 'b> IntoDynNode<'a> for LazyNodes<'a, 'b> {
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::Fragment(cx.bump().alloc([self.call(cx)]))
DynamicNode::Fragment(cx.bump().alloc([cx.render(self).unwrap()]))
}
}
impl<'a, 'b> IntoDynNode<'b> for &'a str {
fn into_vnode(self, cx: &'b ScopeState) -> DynamicNode<'b> {
DynamicNode::Text(VText {
value: bumpalo::collections::String::from_str_in(self, cx.bump()).into_bump_str(),
value: cx.bump().alloc_str(self),
id: Default::default(),
})
}
@@ -741,16 +741,16 @@ impl<'a> IntoTemplate<'a> for VNode<'a> {
}
}
impl<'a> IntoTemplate<'a> for Element<'a> {
fn into_template(self, _cx: &'a ScopeState) -> VNode<'a> {
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
match self {
Some(val) => val.into_template(_cx),
_ => VNode::empty().unwrap(),
Some(val) => val.into_template(cx),
_ => VNode::empty(cx).unwrap(),
}
}
}
impl<'a, 'b> IntoTemplate<'a> for LazyNodes<'a, 'b> {
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
self.call(cx)
cx.render(self).unwrap()
}
}
+8
View File
@@ -73,3 +73,11 @@ impl EmptyBuilder {
pub fn fc_to_builder<'a, T: Properties + 'a>(_: fn(Scope<'a, T>) -> Element<'a>) -> T::Builder {
T::builder()
}
#[cfg(not(miri))]
#[test]
fn unsafe_props_fail() {
let t = trybuild::TestCases::new();
t.compile_fail("compile_tests/props_safety.rs");
t.compile_fail("compile_tests/props_safety_temporary_values.rs");
}
+159
View File
@@ -0,0 +1,159 @@
use std::cell::{Cell, Ref, RefCell};
use crate::{innerlude::Scheduler, scope_context::ScopeContext, scopes::ScopeId};
use std::rc::Rc;
thread_local! {
static RUNTIMES: RefCell<Vec<Rc<Runtime>>> = RefCell::new(vec![]);
}
/// Run some code within a runtime
pub fn in_runtime<R>(runtime: Rc<Runtime>, f: impl FnOnce() -> R) -> R {
let _guard = RuntimeGuard::new(runtime);
f()
}
/// Override the current runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime.
///
/// ```rust
/// use dioxus::prelude::*;
///
/// fn main() {
/// let virtual_dom = VirtualDom::new(app);
/// }
///
/// fn app(cx: Scope) -> Element {
/// render!{ Component { runtime: Runtime::current().unwrap() } }
/// }
///
/// // In a dynamic library
/// #[derive(Props)]
/// struct ComponentProps {
/// runtime: std::rc::Rc<Runtime>,
/// }
///
/// impl PartialEq for ComponentProps {
/// fn eq(&self, _other: &Self) -> bool {
/// true
/// }
/// }
///
/// fn Component(cx: Scope<ComponentProps>) -> Element {
/// cx.use_hook(|| override_runtime(cx.props.runtime.clone()));
///
/// render! { div {} }
/// }
/// ```
pub fn override_runtime(runtime: Rc<Runtime>) {
RUNTIMES.with(|stack| {
let mut stack = stack.borrow_mut();
stack.pop();
stack.push(runtime);
});
}
/// Pushes a new scope onto the stack
pub(crate) fn push_runtime(runtime: Rc<Runtime>) {
RUNTIMES.with(|stack| stack.borrow_mut().push(runtime));
}
/// Pops a scope off the stack
pub(crate) fn pop_runtime() {
RUNTIMES.with(|stack| stack.borrow_mut().pop());
}
/// Runs a function with the current runtime
pub(crate) fn with_runtime<F, R>(f: F) -> Option<R>
where
F: FnOnce(&Runtime) -> R,
{
RUNTIMES.with(|stack| {
let stack = stack.borrow();
stack.last().map(|r| f(r))
})
}
/// Runs a function with the current scope
pub(crate) fn with_current_scope<F, R>(f: F) -> Option<R>
where
F: FnOnce(&ScopeContext) -> R,
{
with_runtime(|runtime| {
runtime
.current_scope_id()
.and_then(|scope| runtime.get_context(scope).map(|sc| f(&sc)))
})
.flatten()
}
/// A global runtime that is shared across all scopes that provides the async runtime and context API
pub struct Runtime {
pub(crate) scope_contexts: RefCell<Vec<Option<ScopeContext>>>,
pub(crate) scheduler: Rc<Scheduler>,
// We use this to track the current scope
pub(crate) scope_stack: RefCell<Vec<ScopeId>>,
pub(crate) rendering: Cell<bool>,
}
impl Runtime {
pub(crate) fn new(scheduler: Rc<Scheduler>) -> Rc<Self> {
Rc::new(Self {
scheduler,
scope_contexts: Default::default(),
scope_stack: Default::default(),
rendering: Cell::new(true),
})
}
/// Get the current runtime
pub fn current() -> Option<Rc<Self>> {
RUNTIMES.with(|stack| stack.borrow().last().cloned())
}
/// Create a scope context. This slab is synchronized with the scope slab.
pub(crate) fn create_context_at(&self, id: ScopeId, context: ScopeContext) {
let mut contexts = self.scope_contexts.borrow_mut();
if contexts.len() <= id.0 {
contexts.resize_with(id.0 + 1, Default::default);
}
contexts[id.0] = Some(context);
}
pub(crate) fn remove_context(&self, id: ScopeId) {
self.scope_contexts.borrow_mut()[id.0] = None;
}
/// Get the current scope id
pub(crate) fn current_scope_id(&self) -> Option<ScopeId> {
self.scope_stack.borrow().last().copied()
}
/// Get the context for any scope given its ID
///
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
pub(crate) fn get_context(&self, id: ScopeId) -> Option<Ref<'_, ScopeContext>> {
Ref::filter_map(self.scope_contexts.borrow(), |contexts| {
contexts.get(id.0).and_then(|f| f.as_ref())
})
.ok()
}
}
pub(crate) struct RuntimeGuard(Rc<Runtime>);
impl RuntimeGuard {
pub(crate) fn new(runtime: Rc<Runtime>) -> Self {
push_runtime(runtime.clone());
Self(runtime)
}
}
impl Drop for RuntimeGuard {
fn drop(&mut self) {
pop_runtime();
}
}
+13 -4
View File
@@ -1,4 +1,4 @@
use crate::{TaskId, VirtualDom};
use crate::{runtime::RuntimeGuard, TaskId, VirtualDom};
use std::task::Context;
impl VirtualDom {
@@ -7,7 +7,8 @@ impl VirtualDom {
/// This is precise, meaning we won't poll every task, just tasks that have woken up as notified to use by the
/// queue
pub(crate) fn handle_task_wakeup(&mut self, id: TaskId) {
let mut tasks = self.scheduler.tasks.borrow_mut();
let _runtime = RuntimeGuard::new(self.runtime.clone());
let mut tasks = self.runtime.scheduler.tasks.borrow_mut();
let task = match tasks.get(id.0) {
Some(task) => task,
@@ -17,14 +18,22 @@ impl VirtualDom {
let mut cx = Context::from_waker(&task.waker);
// update the scope stack
self.runtime.scope_stack.borrow_mut().push(task.scope);
self.runtime.rendering.set(false);
// If the task completes...
if task.task.borrow_mut().as_mut().poll(&mut cx).is_ready() {
// Remove it from the scope so we dont try to double drop it when the scope dropes
let scope = &self.scopes[task.scope.0];
scope.spawned_tasks.borrow_mut().remove(&id);
let scope = &self.get_scope(task.scope).unwrap();
scope.context().spawned_tasks.borrow_mut().remove(&id);
// Remove it from the scheduler
tasks.try_remove(id.0);
}
// Remove the scope from the stack
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
}
}
+34 -26
View File
@@ -3,6 +3,7 @@ use crate::{
bump_frame::BumpFrame,
innerlude::DirtyScope,
nodes::RenderReturn,
scope_context::ScopeContext,
scopes::{ScopeId, ScopeState},
virtual_dom::VirtualDom,
};
@@ -13,48 +14,49 @@ impl VirtualDom {
props: Box<dyn AnyProps<'static>>,
name: &'static str,
) -> &ScopeState {
let parent = self.acquire_current_scope_raw();
let parent_id = self.runtime.current_scope_id();
let height = parent_id
.and_then(|parent_id| self.get_scope(parent_id).map(|f| f.context().height + 1))
.unwrap_or(0);
let entry = self.scopes.vacant_entry();
let height = unsafe { parent.map(|f| (*f).height + 1).unwrap_or(0) };
let id = ScopeId(entry.key());
entry.insert(Box::new(ScopeState {
parent,
id,
height,
name,
let scope = entry.insert(Box::new(ScopeState {
runtime: self.runtime.clone(),
context_id: id,
props: Some(props),
tasks: self.scheduler.clone(),
node_arena_1: BumpFrame::new(0),
node_arena_2: BumpFrame::new(0),
spawned_tasks: Default::default(),
suspended: Default::default(),
render_cnt: Default::default(),
hooks: Default::default(),
hook_idx: Default::default(),
shared_contexts: Default::default(),
borrowed_props: Default::default(),
attributes_to_drop: Default::default(),
}))
}
}));
fn acquire_current_scope_raw(&self) -> Option<*const ScopeState> {
let id = self.scope_stack.last().copied()?;
let scope = self.scopes.get(id.0)?;
Some(scope.as_ref())
let context =
ScopeContext::new(name, id, parent_id, height, self.runtime.scheduler.clone());
self.runtime.create_context_at(id, context);
scope
}
pub(crate) fn run_scope(&mut self, scope_id: ScopeId) -> &RenderReturn {
self.runtime.scope_stack.borrow_mut().push(scope_id);
// Cycle to the next frame and then reset it
// This breaks any latent references, invalidating every pointer referencing into it.
// Remove all the outdated listeners
self.ensure_drop_safety(scope_id);
let new_nodes = unsafe {
self.scopes[scope_id.0].previous_frame().bump_mut().reset();
let scope = &self.scopes[scope_id.0];
scope.suspended.set(false);
scope.previous_frame().bump_mut().reset();
scope.context().suspended.set(false);
scope.hook_idx.set(0);
@@ -62,6 +64,7 @@ impl VirtualDom {
let props: &dyn AnyProps = scope.props.as_ref().unwrap().as_ref();
let props: &dyn AnyProps = std::mem::transmute(props);
let _span = tracing::trace_span!("render", scope = %scope.context().name);
props.render(scope).extend_lifetime()
};
@@ -77,21 +80,26 @@ impl VirtualDom {
// And move the render generation forward by one
scope.render_cnt.set(scope.render_cnt.get() + 1);
let context = scope.context();
// remove this scope from dirty scopes
self.dirty_scopes.remove(&DirtyScope {
height: scope.height,
id: scope.id,
height: context.height,
id: context.id,
});
if scope.suspended.get() {
if context.suspended.get() {
if matches!(allocated, RenderReturn::Aborted(_)) {
self.suspended_scopes.insert(scope.id);
self.suspended_scopes.insert(context.id);
}
} else if !self.suspended_scopes.is_empty() {
_ = self.suspended_scopes.remove(&scope.id);
_ = self.suspended_scopes.remove(&context.id);
}
// rebind the lifetime now that its stored internally
unsafe { allocated.extend_lifetime_ref() }
let result = unsafe { allocated.extend_lifetime_ref() };
self.runtime.scope_stack.borrow_mut().pop();
result
}
}
+362
View File
@@ -0,0 +1,362 @@
use crate::{
innerlude::{ErrorBoundary, Scheduler, SchedulerMsg},
runtime::{with_current_scope, with_runtime},
Element, ScopeId, TaskId,
};
use rustc_hash::FxHashSet;
use std::{
any::Any,
cell::{Cell, RefCell},
fmt::Debug,
future::Future,
rc::Rc,
sync::Arc,
};
/// A component's state separate from its props.
///
/// This struct exists to provide a common interface for all scopes without relying on generics.
pub(crate) struct ScopeContext {
pub(crate) name: &'static str,
pub(crate) id: ScopeId,
pub(crate) parent_id: Option<ScopeId>,
pub(crate) height: u32,
pub(crate) suspended: Cell<bool>,
pub(crate) shared_contexts: RefCell<Vec<Box<dyn Any>>>,
pub(crate) tasks: Rc<Scheduler>,
pub(crate) spawned_tasks: RefCell<FxHashSet<TaskId>>,
}
impl ScopeContext {
pub(crate) fn new(
name: &'static str,
id: ScopeId,
parent_id: Option<ScopeId>,
height: u32,
tasks: Rc<Scheduler>,
) -> Self {
Self {
name,
id,
parent_id,
height,
suspended: Cell::new(false),
shared_contexts: RefCell::new(vec![]),
tasks,
spawned_tasks: RefCell::new(FxHashSet::default()),
}
}
pub fn parent_id(&self) -> Option<ScopeId> {
self.parent_id
}
pub fn scope_id(&self) -> ScopeId {
self.id
}
/// Create a subscription that schedules a future render for the reference component
///
/// ## Notice: you should prefer using [`Self::schedule_update_any`] and [`Self::scope_id`]
pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
let (chan, id) = (self.tasks.sender.clone(), self.scope_id());
Arc::new(move || drop(chan.unbounded_send(SchedulerMsg::Immediate(id))))
}
/// Schedule an update for any component given its [`ScopeId`].
///
/// A component's [`ScopeId`] can be obtained from `use_hook` or the [`ScopeState::scope_id`] method.
///
/// This method should be used when you want to schedule an update for a component
pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> {
let chan = self.tasks.sender.clone();
Arc::new(move |id| {
chan.unbounded_send(SchedulerMsg::Immediate(id)).unwrap();
})
}
/// Mark this scope as dirty, and schedule a render for it.
pub fn needs_update(&self) {
self.needs_update_any(self.scope_id());
}
/// Get the [`ScopeId`] of a mounted component.
///
/// `ScopeId` is not unique for the lifetime of the [`crate::VirtualDom`] - a [`ScopeId`] will be reused if a component is unmounted.
pub fn needs_update_any(&self, id: ScopeId) {
self.tasks
.sender
.unbounded_send(SchedulerMsg::Immediate(id))
.expect("Scheduler to exist if scope exists");
}
/// Return any context of type T if it exists on this scope
pub fn has_context<T: 'static + Clone>(&self) -> Option<T> {
self.shared_contexts
.borrow()
.iter()
.find_map(|any| any.downcast_ref::<T>())
.cloned()
}
/// Try to retrieve a shared state with type `T` from any parent scope.
///
/// Clones the state if it exists.
pub fn consume_context<T: 'static + Clone>(&self) -> Option<T> {
tracing::trace!(
"looking for context {} ({:?}) in {}",
std::any::type_name::<T>(),
std::any::TypeId::of::<T>(),
self.name
);
if let Some(this_ctx) = self.has_context() {
return Some(this_ctx);
}
let mut search_parent = self.parent_id;
match with_runtime(|runtime: &crate::runtime::Runtime| {
while let Some(parent_id) = search_parent {
let parent = runtime.get_context(parent_id).unwrap();
tracing::trace!(
"looking for context {} ({:?}) in {}",
std::any::type_name::<T>(),
std::any::TypeId::of::<T>(),
parent.name
);
if let Some(shared) = parent.shared_contexts.borrow().iter().find_map(|any| {
tracing::trace!("found context {:?}", (**any).type_id());
any.downcast_ref::<T>()
}) {
return Some(shared.clone());
}
search_parent = parent.parent_id;
}
None
})
.flatten()
{
Some(ctx) => Some(ctx),
None => {
tracing::trace!(
"context {} ({:?}) not found",
std::any::type_name::<T>(),
std::any::TypeId::of::<T>()
);
None
}
}
}
/// Expose state to children further down the [`crate::VirtualDom`] Tree. Requires `Clone` on the context to allow getting values down the tree.
///
/// This is a "fundamental" operation and should only be called during initialization of a hook.
///
/// For a hook that provides the same functionality, use `use_provide_context` and `use_context` instead.
///
/// # Example
///
/// ```rust, ignore
/// struct SharedState(&'static str);
///
/// static App: Component = |cx| {
/// cx.use_hook(|| cx.provide_context(SharedState("world")));
/// render!(Child {})
/// }
///
/// static Child: Component = |cx| {
/// let state = cx.consume_state::<SharedState>();
/// render!(div { "hello {state.0}" })
/// }
/// ```
pub fn provide_context<T: 'static + Clone>(&self, value: T) -> T {
tracing::trace!(
"providing context {} ({:?}) in {}",
std::any::type_name::<T>(),
std::any::TypeId::of::<T>(),
self.name
);
let mut contexts = self.shared_contexts.borrow_mut();
// If the context exists, swap it out for the new value
for ctx in contexts.iter_mut() {
// Swap the ptr directly
if let Some(ctx) = ctx.downcast_mut::<T>() {
std::mem::swap(ctx, &mut value.clone());
return value;
}
}
// Else, just push it
contexts.push(Box::new(value.clone()));
value
}
/// Provide a context to the root and then consume it
///
/// This is intended for "global" state management solutions that would rather be implicit for the entire app.
/// Things like signal runtimes and routers are examples of "singletons" that would benefit from lazy initialization.
///
/// Note that you should be checking if the context existed before trying to provide a new one. Providing a context
/// when a context already exists will swap the context out for the new one, which may not be what you want.
pub fn provide_root_context<T: 'static + Clone>(&self, context: T) -> T {
with_runtime(|runtime| {
runtime
.get_context(ScopeId::ROOT)
.unwrap()
.provide_context(context)
})
.expect("Runtime to exist")
}
/// Pushes the future onto the poll queue to be polled after the component renders.
pub fn push_future(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
let id = self.tasks.spawn(self.id, fut);
self.spawned_tasks.borrow_mut().insert(id);
id
}
/// Spawns the future but does not return the [`TaskId`]
pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) {
self.push_future(fut);
}
/// Spawn a future that Dioxus won't clean up when this component is unmounted
///
/// This is good for tasks that need to be run after the component has been dropped.
pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
// The root scope will never be unmounted so we can just add the task at the top of the app
let id = self.tasks.spawn(ScopeId::ROOT, fut);
// wake up the scheduler if it is sleeping
self.tasks
.sender
.unbounded_send(SchedulerMsg::TaskNotified(id))
.expect("Scheduler should exist");
self.spawned_tasks.borrow_mut().insert(id);
id
}
/// Informs the scheduler that this task is no longer needed and should be removed.
///
/// This drops the task immediately.
pub fn remove_future(&self, id: TaskId) {
self.tasks.remove(id);
}
/// Inject an error into the nearest error boundary and quit rendering
///
/// The error doesn't need to implement Error or any specific traits since the boundary
/// itself will downcast the error into a trait object.
pub fn throw(&self, error: impl Debug + 'static) -> Option<()> {
if let Some(cx) = self.consume_context::<Rc<ErrorBoundary>>() {
cx.insert_error(self.scope_id(), Box::new(error));
}
// Always return none during a throw
None
}
/// Mark this component as suspended and then return None
pub fn suspend(&self) -> Option<Element> {
self.suspended.set(true);
None
}
}
/// Schedule an update for any component given its [`ScopeId`].
///
/// A component's [`ScopeId`] can be obtained from `use_hook` or the [`crate::scopes::ScopeState::scope_id`] method.
///
/// This method should be used when you want to schedule an update for a component
pub fn schedule_update_any() -> Option<Arc<dyn Fn(ScopeId) + Send + Sync>> {
with_current_scope(|cx| cx.schedule_update_any())
}
/// Get the current scope id
pub fn current_scope_id() -> Option<ScopeId> {
with_runtime(|rt| rt.current_scope_id()).flatten()
}
#[doc(hidden)]
/// Check if the virtual dom is currently inside of the body of a component
pub fn vdom_is_rendering() -> bool {
with_runtime(|rt| rt.rendering.get()).unwrap_or_default()
}
/// Consume context from the current scope
pub fn consume_context<T: 'static + Clone>() -> Option<T> {
with_current_scope(|cx| cx.consume_context::<T>()).flatten()
}
/// Consume context from the current scope
pub fn consume_context_from_scope<T: 'static + Clone>(scope_id: ScopeId) -> Option<T> {
with_runtime(|rt| {
rt.get_context(scope_id)
.and_then(|cx| cx.consume_context::<T>())
})
.flatten()
}
/// Check if the current scope has a context
pub fn has_context<T: 'static + Clone>() -> Option<T> {
with_current_scope(|cx| cx.has_context::<T>()).flatten()
}
/// Provide context to the current scope
pub fn provide_context<T: 'static + Clone>(value: T) -> Option<T> {
with_current_scope(|cx| cx.provide_context(value))
}
/// Provide context to the the given scope
pub fn provide_context_to_scope<T: 'static + Clone>(scope_id: ScopeId, value: T) -> Option<T> {
with_runtime(|rt| rt.get_context(scope_id).map(|cx| cx.provide_context(value))).flatten()
}
/// Provide a context to the root scope
pub fn provide_root_context<T: 'static + Clone>(value: T) -> Option<T> {
with_current_scope(|cx| cx.provide_root_context(value))
}
/// Suspends the current component
pub fn suspend() -> Option<Element<'static>> {
with_current_scope(|cx| {
cx.suspend();
});
None
}
/// Throw an error into the nearest error boundary
pub fn throw(error: impl Debug + 'static) -> Option<()> {
with_current_scope(|cx| cx.throw(error)).flatten()
}
/// Pushes the future onto the poll queue to be polled after the component renders.
pub fn push_future(fut: impl Future<Output = ()> + 'static) -> Option<TaskId> {
with_current_scope(|cx| cx.push_future(fut))
}
/// Spawns the future but does not return the [`TaskId`]
pub fn spawn(fut: impl Future<Output = ()> + 'static) {
with_current_scope(|cx| cx.spawn(fut));
}
/// Spawn a future that Dioxus won't clean up when this component is unmounted
///
/// This is good for tasks that need to be run after the component has been dropped.
pub fn spawn_forever(fut: impl Future<Output = ()> + 'static) -> Option<TaskId> {
with_current_scope(|cx| cx.spawn_forever(fut))
}
/// Informs the scheduler that this task is no longer needed and should be removed.
///
/// This drops the task immediately.
pub fn remove_future(id: TaskId) {
with_current_scope(|cx| cx.remove_future(id));
}
+61 -103
View File
@@ -2,17 +2,18 @@ use crate::{
any_props::AnyProps,
any_props::VProps,
bump_frame::BumpFrame,
innerlude::ErrorBoundary,
innerlude::{DynamicNode, EventHandler, VComponent, VText},
innerlude::{ErrorBoundary, Scheduler, SchedulerMsg},
lazynodes::LazyNodes,
nodes::{IntoAttributeValue, IntoDynNode, RenderReturn},
runtime::Runtime,
scope_context::ScopeContext,
AnyValue, Attribute, AttributeValue, Element, Event, Properties, TaskId,
};
use bumpalo::{boxed::Box as BumpBox, Bump};
use rustc_hash::FxHashSet;
use std::{
any::{Any, TypeId},
cell::{Cell, RefCell, UnsafeCell},
any::Any,
cell::{Cell, Ref, RefCell, UnsafeCell},
fmt::{Arguments, Debug},
future::Future,
rc::Rc,
@@ -62,37 +63,53 @@ impl<'a, T> std::ops::Deref for Scoped<'a, T> {
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub struct ScopeId(pub usize);
impl ScopeId {
/// The root ScopeId.
///
/// This scope will last for the entire duration of your app, making it convenient for long-lived state
/// that is created dynamically somewhere down the component tree.
///
/// # Example
///
/// ```rust, ignore
/// use dioxus_signals::*;
/// let my_persistent_state = Signal::new_in_scope(ScopeId::ROOT, String::new());
/// ```
pub const ROOT: ScopeId = ScopeId(0);
}
/// A component's state separate from its props.
///
/// This struct exists to provide a common interface for all scopes without relying on generics.
pub struct ScopeState {
pub(crate) runtime: Rc<Runtime>,
pub(crate) context_id: ScopeId,
pub(crate) render_cnt: Cell<usize>,
pub(crate) name: &'static str,
pub(crate) node_arena_1: BumpFrame,
pub(crate) node_arena_2: BumpFrame,
pub(crate) parent: Option<*const ScopeState>,
pub(crate) id: ScopeId,
pub(crate) height: u32,
pub(crate) suspended: Cell<bool>,
pub(crate) hooks: RefCell<Vec<Box<UnsafeCell<dyn Any>>>>,
pub(crate) hook_idx: Cell<usize>,
pub(crate) shared_contexts: RefCell<Vec<(TypeId, Box<dyn Any>)>>,
pub(crate) tasks: Rc<Scheduler>,
pub(crate) spawned_tasks: RefCell<FxHashSet<TaskId>>,
pub(crate) borrowed_props: RefCell<Vec<*const VComponent<'static>>>,
pub(crate) attributes_to_drop: RefCell<Vec<*const Attribute<'static>>>,
pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
}
impl Drop for ScopeState {
fn drop(&mut self) {
self.runtime.remove_context(self.context_id);
}
}
impl<'src> ScopeState {
pub(crate) fn context(&self) -> Ref<'_, ScopeContext> {
self.runtime.get_context(self.context_id).unwrap()
}
pub(crate) fn current_frame(&self) -> &BumpFrame {
match self.render_cnt.get() % 2 {
0 => &self.node_arena_1,
@@ -111,7 +128,7 @@ impl<'src> ScopeState {
/// Get the name of this component
pub fn name(&self) -> &str {
self.name
self.context().name
}
/// Get the current render since the inception of this component
@@ -174,7 +191,7 @@ impl<'src> ScopeState {
/// assert_eq!(base.height(), 0);
/// ```
pub fn height(&self) -> u32 {
self.height
self.context().height
}
/// Get the Parent of this [`Scope`] within this Dioxus [`crate::VirtualDom`].
@@ -195,7 +212,7 @@ impl<'src> ScopeState {
/// ```
pub fn parent(&self) -> Option<ScopeId> {
// safety: the pointer to our parent is *always* valid thanks to the bump arena
self.parent.map(|p| unsafe { &*p }.id)
self.context().parent_id()
}
/// Get the ID of this Scope within this Dioxus [`crate::VirtualDom`].
@@ -212,15 +229,14 @@ impl<'src> ScopeState {
/// assert_eq!(base.scope_id(), 0);
/// ```
pub fn scope_id(&self) -> ScopeId {
self.id
self.context().scope_id()
}
/// Create a subscription that schedules a future render for the reference component
///
/// ## Notice: you should prefer using [`Self::schedule_update_any`] and [`Self::scope_id`]
pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
let (chan, id) = (self.tasks.sender.clone(), self.scope_id());
Arc::new(move || drop(chan.unbounded_send(SchedulerMsg::Immediate(id))))
self.context().schedule_update()
}
/// Schedule an update for any component given its [`ScopeId`].
@@ -229,61 +245,31 @@ impl<'src> ScopeState {
///
/// This method should be used when you want to schedule an update for a component
pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> {
let chan = self.tasks.sender.clone();
Arc::new(move |id| {
chan.unbounded_send(SchedulerMsg::Immediate(id)).unwrap();
})
self.context().schedule_update_any()
}
/// Mark this scope as dirty, and schedule a render for it.
pub fn needs_update(&self) {
self.needs_update_any(self.scope_id());
self.context().needs_update()
}
/// Get the [`ScopeId`] of a mounted component.
///
/// `ScopeId` is not unique for the lifetime of the [`crate::VirtualDom`] - a [`ScopeId`] will be reused if a component is unmounted.
pub fn needs_update_any(&self, id: ScopeId) {
self.tasks
.sender
.unbounded_send(SchedulerMsg::Immediate(id))
.expect("Scheduler to exist if scope exists");
self.context().needs_update_any(id)
}
/// Return any context of type T if it exists on this scope
pub fn has_context<T: 'static + Clone>(&self) -> Option<T> {
self.shared_contexts
.borrow()
.iter()
.find(|(k, _)| *k == TypeId::of::<T>())
.map(|(_, v)| v)?
.downcast_ref::<T>()
.cloned()
self.context().has_context()
}
/// Try to retrieve a shared state with type `T` from any parent scope.
///
/// Clones the state if it exists.
pub fn consume_context<T: 'static + Clone>(&self) -> Option<T> {
if let Some(this_ctx) = self.has_context() {
return Some(this_ctx);
}
let mut search_parent = self.parent;
while let Some(parent_ptr) = search_parent {
// safety: all parent pointers are valid thanks to the bump arena
let parent = unsafe { &*parent_ptr };
if let Some(shared) = parent
.shared_contexts
.borrow()
.iter()
.find(|(k, _)| *k == TypeId::of::<T>())
{
return shared.1.downcast_ref::<T>().cloned();
}
search_parent = parent.parent;
}
None
self.context().consume_context()
}
/// Expose state to children further down the [`crate::VirtualDom`] Tree. Requires `Clone` on the context to allow getting values down the tree.
@@ -308,21 +294,7 @@ impl<'src> ScopeState {
/// }
/// ```
pub fn provide_context<T: 'static + Clone>(&self, value: T) -> T {
let mut contexts = self.shared_contexts.borrow_mut();
// If the context exists, swap it out for the new value
for ctx in contexts.iter_mut() {
// Swap the ptr directly
if let Some(ctx) = ctx.1.downcast_mut::<T>() {
std::mem::swap(ctx, &mut value.clone());
return value;
}
}
// Else, just push it
contexts.push((TypeId::of::<T>(), Box::new(value.clone())));
value
self.context().provide_context(value)
}
/// Provide a context to the root and then consume it
@@ -333,52 +305,31 @@ impl<'src> ScopeState {
/// Note that you should be checking if the context existed before trying to provide a new one. Providing a context
/// when a context already exists will swap the context out for the new one, which may not be what you want.
pub fn provide_root_context<T: 'static + Clone>(&self, context: T) -> T {
let mut parent = self;
// Walk upwards until there is no more parent - and tada we have the root
while let Some(next_parent) = parent.parent {
parent = unsafe { &*next_parent };
debug_assert_eq!(parent.scope_id(), ScopeId(0));
}
parent.provide_context(context)
self.context().provide_root_context(context)
}
/// Pushes the future onto the poll queue to be polled after the component renders.
pub fn push_future(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
let id = self.tasks.spawn(self.id, fut);
self.spawned_tasks.borrow_mut().insert(id);
id
self.context().push_future(fut)
}
/// Spawns the future but does not return the [`TaskId`]
pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) {
self.push_future(fut);
self.context().spawn(fut);
}
/// Spawn a future that Dioxus won't clean up when this component is unmounted
///
/// This is good for tasks that need to be run after the component has been dropped.
pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
// The root scope will never be unmounted so we can just add the task at the top of the app
let id = self.tasks.spawn(ScopeId(0), fut);
// wake up the scheduler if it is sleeping
self.tasks
.sender
.unbounded_send(SchedulerMsg::TaskNotified(id))
.expect("Scheduler should exist");
self.spawned_tasks.borrow_mut().insert(id);
id
self.context().spawn_forever(fut)
}
/// Informs the scheduler that this task is no longer needed and should be removed.
///
/// This drops the task immediately.
pub fn remove_future(&self, id: TaskId) {
self.tasks.remove(id);
self.context().remove_future(id);
}
/// Take a lazy [`crate::VNode`] structure and actually build it with the context of the efficient [`bumpalo::Bump`] allocator.
@@ -481,19 +432,22 @@ impl<'src> ScopeState {
/// fn(Scope<Props>) -> Element;
/// async fn(Scope<Props<'_>>) -> Element;
/// ```
pub fn component<P>(
pub fn component<'child, P>(
&'src self,
component: fn(Scope<'src, P>) -> Element<'src>,
component: fn(Scope<'child, P>) -> Element<'child>,
props: P,
fn_name: &'static str,
) -> DynamicNode<'src>
where
// The properties must be valid until the next bump frame
P: Properties + 'src,
// The current bump allocator frame must outlive the child's borrowed props
'src: 'child,
{
let vcomp = VProps::new(component, P::memoize, props);
// cast off the lifetime of the render return
let as_dyn: Box<dyn AnyProps<'src> + '_> = Box::new(vcomp);
let as_dyn: Box<dyn AnyProps<'child> + '_> = Box::new(vcomp);
let extended: Box<dyn AnyProps<'src> + 'src> = unsafe { std::mem::transmute(as_dyn) };
DynamicNode::Component(VComponent {
@@ -510,7 +464,10 @@ impl<'src> ScopeState {
let handler: &mut dyn FnMut(T) = self.bump().alloc(f);
let caller = unsafe { BumpBox::from_raw(handler as *mut dyn FnMut(T)) };
let callback = RefCell::new(Some(caller));
EventHandler { callback }
EventHandler {
callback,
origin: self.context().id,
}
}
/// Create a new [`AttributeValue`] with the listener variant from a callback
@@ -564,7 +521,8 @@ impl<'src> ScopeState {
/// Mark this component as suspended and then return None
pub fn suspend(&self) -> Option<Element> {
self.suspended.set(true);
let cx = self.context();
cx.suspend();
None
}
+57 -30
View File
@@ -9,6 +9,7 @@ use crate::{
mutations::Mutation,
nodes::RenderReturn,
nodes::{Template, TemplateId},
runtime::{Runtime, RuntimeGuard},
scopes::{ScopeId, ScopeState},
AttributeValue, Element, Event, Scope,
};
@@ -51,6 +52,7 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
///
/// static ROUTES: &str = "";
///
/// #[component]
/// fn App(cx: Scope<AppProps>) -> Element {
/// cx.render(rsx!(
/// NavBar { routes: ROUTES }
@@ -59,18 +61,19 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
/// ))
/// }
///
/// #[inline_props]
/// #[component]
/// fn NavBar(cx: Scope, routes: &'static str) -> Element {
/// cx.render(rsx! {
/// div { "Routes: {routes}" }
/// })
/// }
///
/// #[component]
/// fn Footer(cx: Scope) -> Element {
/// cx.render(rsx! { div { "Footer" } })
/// }
///
/// #[inline_props]
/// #[component]
/// fn Title<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
/// cx.render(rsx! {
/// div { id: "title", children }
@@ -121,13 +124,14 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
///
/// Putting everything together, you can build an event loop around Dioxus by using the methods outlined above.
/// ```rust, ignore
/// fn app(cx: Scope) -> Element {
/// #[component]
/// fn App(cx: Scope) -> Element {
/// cx.render(rsx! {
/// div { "Hello World" }
/// })
/// }
///
/// let dom = VirtualDom::new(app);
/// let dom = VirtualDom::new(App);
///
/// real_dom.apply(dom.rebuild());
///
@@ -174,24 +178,24 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
/// }
/// ```
pub struct VirtualDom {
pub(crate) scopes: Slab<Box<ScopeState>>,
pub(crate) dirty_scopes: BTreeSet<DirtyScope>,
// Maps a template path to a map of byteindexes to templates
pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template<'static>>>,
pub(crate) scopes: Slab<Box<ScopeState>>,
pub(crate) dirty_scopes: BTreeSet<DirtyScope>,
pub(crate) scheduler: Rc<Scheduler>,
// Every element is actually a dual reference - one to the template and the other to the dynamic node in that template
pub(crate) elements: Slab<ElementRef>,
// While diffing we need some sort of way of breaking off a stream of suspended mutations.
pub(crate) scope_stack: Vec<ScopeId>,
pub(crate) mutations: Mutations<'static>,
pub(crate) runtime: Rc<Runtime>,
// Currently suspended scopes
pub(crate) suspended_scopes: FxHashSet<ScopeId>,
pub(crate) rx: futures_channel::mpsc::UnboundedReceiver<SchedulerMsg>,
pub(crate) mutations: Mutations<'static>,
}
impl VirtualDom {
@@ -251,16 +255,16 @@ impl VirtualDom {
/// ```
pub fn new_with_props<P: 'static>(root: fn(Scope<P>) -> Element, root_props: P) -> Self {
let (tx, rx) = futures_channel::mpsc::unbounded();
let scheduler = Scheduler::new(tx);
let mut dom = Self {
rx,
scheduler: Scheduler::new(tx),
templates: Default::default(),
runtime: Runtime::new(scheduler),
scopes: Default::default(),
dirty_scopes: Default::default(),
templates: Default::default(),
elements: Default::default(),
scope_stack: Vec::new(),
dirty_scopes: BTreeSet::new(),
suspended_scopes: FxHashSet::default(),
mutations: Mutations::default(),
suspended_scopes: Default::default(),
};
let root = dom.new_scope(
@@ -269,7 +273,7 @@ impl VirtualDom {
);
// Unlike react, we provide a default error boundary that just renders the error as a string
root.provide_context(Rc::new(ErrorBoundary::new(ScopeId(0))));
root.provide_context(Rc::new(ErrorBoundary::new(ScopeId::ROOT)));
// the root element is always given element ID 0 since it's the container for the entire tree
dom.elements.insert(ElementRef::none());
@@ -281,14 +285,14 @@ impl VirtualDom {
///
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
self.scopes.get(id.0).map(|f| f.as_ref())
self.scopes.get(id.0).map(|s| &**s)
}
/// Get the single scope at the top of the VirtualDom tree that will always be around
///
/// This scope has a ScopeId of 0 and is the root of the tree
pub fn base_scope(&self) -> &ScopeState {
self.get_scope(ScopeId(0)).unwrap()
self.get_scope(ScopeId::ROOT).unwrap()
}
/// Build the virtualdom with a global context inserted into the base scope
@@ -301,10 +305,11 @@ impl VirtualDom {
/// Manually mark a scope as requiring a re-render
///
/// Whenever the VirtualDom "works", it will re-render this scope
/// Whenever the Runtime "works", it will re-render this scope
pub fn mark_dirty(&mut self, id: ScopeId) {
if let Some(scope) = self.get_scope(id) {
let height = scope.height;
let height = scope.height();
tracing::trace!("Marking scope {:?} ({}) as dirty", id, scope.context().name);
self.dirty_scopes.insert(DirtyScope { height, id });
}
}
@@ -325,6 +330,8 @@ impl VirtualDom {
element: ElementId,
bubbles: bool,
) {
let _runtime = RuntimeGuard::new(self.runtime.clone());
/*
------------------------
The algorithm works by walking through the list of dynamic attributes, checking their paths, and breaking when
@@ -387,9 +394,14 @@ impl VirtualDom {
// We check the bubble state between each call to see if the event has been stopped from bubbling
for listener in listeners.drain(..).rev() {
if let AttributeValue::Listener(listener) = listener {
let origin = el_ref.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
if !uievent.propagates.get() {
return;
@@ -418,9 +430,14 @@ impl VirtualDom {
// Only call the listener if this is the exact target element.
if attr.name.trim_start_matches("on") == name && target_path == this_path {
if let AttributeValue::Listener(listener) = &attr.value {
let origin = el_ref.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
break;
}
@@ -501,10 +518,11 @@ impl VirtualDom {
if sync.template.get().name.rsplit_once(':').unwrap().0
== template.name.rsplit_once(':').unwrap().0
{
let height = scope.height;
let context = scope.context();
let height = context.height;
self.dirty_scopes.insert(DirtyScope {
height,
id: scope.id,
id: context.id,
});
}
}
@@ -532,10 +550,11 @@ impl VirtualDom {
/// apply_edits(edits);
/// ```
pub fn rebuild(&mut self) -> Mutations {
match unsafe { self.run_scope(ScopeId(0)).extend_lifetime_ref() } {
let _runtime = RuntimeGuard::new(self.runtime.clone());
match unsafe { self.run_scope(ScopeId::ROOT).extend_lifetime_ref() } {
// Rebuilding implies we append the created elements to the root
RenderReturn::Ready(node) => {
let m = self.create_scope(ScopeId(0), node);
let m = self.create_scope(ScopeId::ROOT, node);
self.mutations.edits.push(Mutation::AppendChildren {
id: ElementId(0),
m,
@@ -543,7 +562,7 @@ impl VirtualDom {
}
// If an error occurs, we should try to render the default error component and context where the error occured
RenderReturn::Aborted(placeholder) => {
log::info!("Ran into suspended or aborted scope during rebuild");
tracing::debug!("Ran into suspended or aborted scope during rebuild");
let id = self.next_null();
placeholder.id.set(Some(id));
self.mutations.push(Mutation::CreatePlaceholder { id });
@@ -610,9 +629,12 @@ impl VirtualDom {
continue;
}
// Run the scope and get the mutations
self.run_scope(dirty.id);
self.diff_scope(dirty.id);
{
let _runtime = RuntimeGuard::new(self.runtime.clone());
// Run the scope and get the mutations
self.run_scope(dirty.id);
self.diff_scope(dirty.id);
}
}
// If there's more work, then just continue, plenty of work to do
@@ -640,11 +662,16 @@ impl VirtualDom {
fn finalize(&mut self) -> Mutations {
std::mem::take(&mut self.mutations)
}
/// Get the current runtime
pub fn runtime(&self) -> Rc<Runtime> {
self.runtime.clone()
}
}
impl Drop for VirtualDom {
fn drop(&mut self) {
// Simply drop this scope which drops all of its children
self.drop_scope(ScopeId(0), true);
self.drop_scope(ScopeId::ROOT, true);
}
}
+4 -4
View File
@@ -34,7 +34,7 @@ fn attrs_cycle() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -56,7 +56,7 @@ fn attrs_cycle() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -65,7 +65,7 @@ fn attrs_cycle() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -88,7 +88,7 @@ fn attrs_cycle() {
);
// we take the node taken by attributes since we reused it
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
+1 -1
View File
@@ -24,7 +24,7 @@ fn bubbles_error() {
let _edits = dom.rebuild().santize();
}
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
+3 -3
View File
@@ -27,11 +27,11 @@ fn state_shares() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
assert_eq!(dom.base_scope().consume_context::<i32>().unwrap(), 1);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
assert_eq!(dom.base_scope().consume_context::<i32>().unwrap(), 2);
@@ -41,7 +41,7 @@ fn state_shares() {
[SetText { value: "Value is 2", id: ElementId(1,) },]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
dom.mark_dirty(ScopeId(2));
let edits = dom.render_immediate();
assert_eq!(
+19 -16
View File
@@ -5,11 +5,12 @@ use dioxus_core::ElementId;
/// Should push the text node onto the stack and modify it
#[test]
fn nested_passthru_creates() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx! {
pass_thru {
pass_thru {
pass_thru {
PassThru {
PassThru {
PassThru {
div { "hi" }
}
}
@@ -17,12 +18,12 @@ fn nested_passthru_creates() {
})
}
#[inline_props]
fn pass_thru<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
#[component]
fn PassThru<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
cx.render(rsx!(children))
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
let edits = dom.rebuild().santize();
assert_eq!(
@@ -39,13 +40,14 @@ fn nested_passthru_creates() {
/// Take note on how we don't spit out the template for child_comp since it's entirely dynamic
#[test]
fn nested_passthru_creates_add() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx! {
child_comp {
ChildComp {
"1"
child_comp {
ChildComp {
"2"
child_comp {
ChildComp {
"3"
div {
"hi"
@@ -56,12 +58,12 @@ fn nested_passthru_creates_add() {
})
}
#[inline_props]
fn child_comp<'a>(cx: Scope, children: Element<'a>) -> Element {
#[component]
fn ChildComp<'a>(cx: Scope, children: Element<'a>) -> Element {
cx.render(rsx! { children })
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
assert_eq!(
dom.rebuild().santize().edits,
@@ -82,13 +84,14 @@ fn nested_passthru_creates_add() {
/// note that the template is all dynamic roots - so it doesn't actually get cached as a template
#[test]
fn dynamic_node_as_root() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
let a = 123;
let b = 456;
cx.render(rsx! { "{a}" "{b}" })
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
let edits = dom.rebuild().santize();
// Since the roots were all dynamic, they should not cause any template muations
+3 -3
View File
@@ -23,7 +23,7 @@ fn cycling_elements() {
);
}
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -33,7 +33,7 @@ fn cycling_elements() {
);
// notice that the IDs cycle back to ElementId(1), preserving a minimal memory footprint
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -42,7 +42,7 @@ fn cycling_elements() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
+3 -3
View File
@@ -75,7 +75,7 @@ fn component_swap() {
);
}
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -84,7 +84,7 @@ fn component_swap() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -93,7 +93,7 @@ fn component_swap() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
+7 -7
View File
@@ -12,19 +12,19 @@ fn text_diff() {
let mut vdom = VirtualDom::new(app);
_ = vdom.rebuild();
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().edits,
[SetText { value: "hello 1", id: ElementId(2) }]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().edits,
[SetText { value: "hello 2", id: ElementId(2) }]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().edits,
[SetText { value: "hello 3", id: ElementId(2) }]
@@ -46,7 +46,7 @@ fn element_swap() {
let mut vdom = VirtualDom::new(app);
_ = vdom.rebuild();
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().santize().edits,
[
@@ -55,7 +55,7 @@ fn element_swap() {
]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().santize().edits,
[
@@ -64,7 +64,7 @@ fn element_swap() {
]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().santize().edits,
[
@@ -73,7 +73,7 @@ fn element_swap() {
]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().santize().edits,
[
+12 -12
View File
@@ -39,7 +39,7 @@ fn keyed_diffing_out_of_order() {
);
}
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -64,7 +64,7 @@ fn keyed_diffing_out_of_order_adds() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -90,7 +90,7 @@ fn keyed_diffing_out_of_order_adds_3() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -116,7 +116,7 @@ fn keyed_diffing_out_of_order_adds_4() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -142,7 +142,7 @@ fn keyed_diffing_out_of_order_adds_5() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -167,7 +167,7 @@ fn keyed_diffing_additions() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -192,7 +192,7 @@ fn keyed_diffing_additions_and_moves_on_ends() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -222,7 +222,7 @@ fn keyed_diffing_additions_and_moves_in_middle() {
_ = dom.rebuild();
// LIS: 4, 5, 6
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -256,7 +256,7 @@ fn controlled_keyed_diffing_out_of_order() {
_ = dom.rebuild();
// LIS: 5, 6
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -289,7 +289,7 @@ fn controlled_keyed_diffing_out_of_order_max_test() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -318,7 +318,7 @@ fn remove_list() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -343,7 +343,7 @@ fn no_common_keys() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
+18 -18
View File
@@ -27,7 +27,7 @@ fn list_creates_one_by_one() {
);
// Rendering the first item should replace the placeholder with an element
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -38,7 +38,7 @@ fn list_creates_one_by_one() {
);
// Rendering the next item should insert after the previous
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -49,7 +49,7 @@ fn list_creates_one_by_one() {
);
// ... and again!
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -60,7 +60,7 @@ fn list_creates_one_by_one() {
);
// once more
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -107,14 +107,14 @@ fn removes_one_by_one() {
// Remove div(3)
// Rendering the first item should replace the placeholder with an element
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[Remove { id: ElementId(6) }]
);
// Remove div(2)
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[Remove { id: ElementId(4) }]
@@ -122,7 +122,7 @@ fn removes_one_by_one() {
// Remove div(1) and replace with a placeholder
// todo: this should just be a remove with no placeholder
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -133,7 +133,7 @@ fn removes_one_by_one() {
// load the 3 and replace the placeholder
// todo: this should actually be append to, but replace placeholder is fine for now
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -170,7 +170,7 @@ fn list_shrink_multiroot() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -182,7 +182,7 @@ fn list_shrink_multiroot() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -194,7 +194,7 @@ fn list_shrink_multiroot() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -249,19 +249,19 @@ fn removes_one_by_one_multiroot() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[Remove { id: ElementId(10) }, Remove { id: ElementId(12) }]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[Remove { id: ElementId(6) }, Remove { id: ElementId(8) }]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -328,7 +328,7 @@ fn remove_many() {
}
{
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate().santize();
assert_eq!(
edits.edits,
@@ -341,7 +341,7 @@ fn remove_many() {
}
{
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate().santize();
assert_eq!(
edits.edits,
@@ -360,7 +360,7 @@ fn remove_many() {
}
{
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate().santize();
assert_eq!(
edits.edits,
@@ -376,7 +376,7 @@ fn remove_many() {
}
{
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate().santize();
assert_eq!(
edits.edits,
+2 -2
View File
@@ -179,7 +179,7 @@ fn create_random_dynamic_node(cx: &ScopeState, depth: usize) -> DynamicNode {
node_paths: &[&[0]],
attr_paths: &[],
}),
root_ids: Default::default(),
root_ids: bumpalo::collections::Vec::new_in(cx.bump()).into(),
dynamic_nodes: cx.bump().alloc([cx.component(
create_random_element,
DepthProps { depth, root: false },
@@ -276,7 +276,7 @@ fn create_random_element(cx: Scope<DepthProps>) -> Element {
key: None,
parent: None,
template: Cell::new(template),
root_ids: Default::default(),
root_ids: bumpalo::collections::Vec::new_in(cx.bump()).into(),
dynamic_nodes: {
let dynamic_nodes: Vec<_> = dynamic_node_types
.iter()
+8 -8
View File
@@ -58,7 +58,7 @@ fn events_generate() {
dom.handle_event("click", Rc::new(MouseData::default()), ElementId(1), true);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate();
assert_eq!(
@@ -107,7 +107,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateElement { root: Some(2), tag: "div", children: 0 },
// ReplaceWith { root: Some(1), nodes: vec![2] }
@@ -115,7 +115,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateTextNode { root: Some(1), text: "Text2" },
// ReplaceWith { root: Some(2), nodes: vec![1] }
@@ -124,7 +124,7 @@ fn events_generate() {
// // child {}
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateElement { root: Some(2), tag: "h1", children: 0 },
// ReplaceWith { root: Some(1), nodes: vec![2] }
@@ -133,7 +133,7 @@ fn events_generate() {
// // placeholder
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreatePlaceholder { root: Some(1) },
// ReplaceWith { root: Some(2), nodes: vec![1] }
@@ -141,7 +141,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateTextNode { root: Some(2), text: "text 3" },
// ReplaceWith { root: Some(1), nodes: vec![2] }
@@ -149,7 +149,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateTextNode { text: "text 0", root: Some(1) },
// CreateTextNode { text: "text 1", root: Some(3) },
@@ -158,7 +158,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateElement { tag: "h1", root: Some(2), children: 0 },
// ReplaceWith { root: Some(1), nodes: vec![2] },
+6 -5
View File
@@ -4,7 +4,7 @@ use std::rc::Rc;
#[test]
fn miri_rollover() {
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
@@ -15,7 +15,8 @@ fn miri_rollover() {
}
}
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
let mut idx = use_state(cx, || 0);
let onhover = |_| println!("go!");
@@ -31,15 +32,15 @@ fn app(cx: Scope) -> Element {
button { onclick: move |_| idx -= 1, "-" }
ul {
(0..**idx).map(|i| rsx! {
child_example { i: i, onhover: onhover }
ChildExample { i: i, onhover: onhover }
})
}
}
})
}
#[inline_props]
fn child_example<'a>(cx: Scope<'a>, i: i32, onhover: EventHandler<'a, MouseEvent>) -> Element {
#[component]
fn ChildExample<'a>(cx: Scope<'a>, i: i32, onhover: EventHandler<'a, MouseEvent>) -> Element {
cx.render(rsx! {
li {
onmouseover: move |e| onhover.call(e),
+30 -24
View File
@@ -2,22 +2,24 @@ use dioxus::prelude::*;
#[test]
fn app_drops() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx! {
div {}
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
#[test]
fn hooks_drop() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.use_hook(|| String::from("asd"));
cx.use_hook(|| String::from("asd"));
cx.use_hook(|| String::from("asd"));
@@ -28,26 +30,28 @@ fn hooks_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
#[test]
fn contexts_drop() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.provide_context(String::from("asd"));
cx.render(rsx! {
div {
child_comp {}
ChildComp {}
}
})
}
fn child_comp(cx: Scope) -> Element {
#[component]
fn ChildComp(cx: Scope) -> Element {
let el = cx.consume_context::<String>().unwrap();
cx.render(rsx! {
@@ -55,16 +59,17 @@ fn contexts_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
#[test]
fn tasks_drop() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.spawn(async {
// tokio::time::sleep(std::time::Duration::from_millis(100000)).await;
});
@@ -74,10 +79,10 @@ fn tasks_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
@@ -91,37 +96,38 @@ fn root_props_drop() {
);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
#[test]
fn diffing_drops_old() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx! {
div {
match cx.generation() % 2 {
0 => rsx!( child_comp1 { name: "asdasd".to_string() }),
1 => rsx!( child_comp2 { name: "asdasd".to_string() }),
0 => rsx!( ChildComp1 { name: "asdasd".to_string() }),
1 => rsx!( ChildComp2 { name: "asdasd".to_string() }),
_ => todo!()
}
}
})
}
#[inline_props]
fn child_comp1(cx: Scope, name: String) -> Element {
#[component]
fn ChildComp1(cx: Scope, name: String) -> Element {
cx.render(rsx! { "Hello {name}" })
}
#[inline_props]
fn child_comp2(cx: Scope, name: String) -> Element {
#[component]
fn ChildComp2(cx: Scope, name: String) -> Element {
cx.render(rsx! { "Goodbye {name}" })
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
+8 -8
View File
@@ -62,7 +62,7 @@ fn test_memory_leak() {
_ = dom.rebuild();
for _ in 0..5 {
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
}
@@ -97,13 +97,13 @@ fn memo_works_properly() {
_ = dom.rebuild();
// todo!()
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
}
#[test]