From 04cdb14e5bbe624a4f083ec9d6a805677f1c7634 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 13:53:05 -0700 Subject: [PATCH 01/39] improve signal copy runtime --- packages/core/src/arena.rs | 7 +- packages/core/src/create.rs | 6 +- packages/core/src/diff.rs | 37 +++- packages/core/src/lib.rs | 11 +- packages/core/src/runtime.rs | 87 ++++++++ packages/core/src/scheduler/wait.rs | 6 +- packages/core/src/scope_arena.rs | 47 ++--- packages/core/src/scope_context.rs | 288 ++++++++++++++++++++++++++ packages/core/src/scopes.rs | 131 +++--------- packages/core/src/virtual_dom.rs | 36 ++-- packages/signals/Cargo.toml | 1 + packages/signals/src/copy.rs | 301 ++++++++++++++++++++++++++++ packages/signals/src/lib.rs | 99 ++++----- packages/signals/src/rt.rs | 140 ++++--------- 14 files changed, 878 insertions(+), 319 deletions(-) create mode 100644 packages/core/src/runtime.rs create mode 100644 packages/core/src/scope_context.rs create mode 100644 packages/signals/src/copy.rs diff --git a/packages/core/src/arena.rs b/packages/core/src/arena.rs index b6254136d..25b040643 100644 --- a/packages/core/src/arena.rs +++ b/packages/core/src/arena.rs @@ -91,7 +91,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 +110,11 @@ 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); + for task_id in context.spawned_tasks.borrow_mut().drain() { + context.tasks.remove(task_id); } self.scopes.remove(id.0); diff --git a/packages/core/src/create.rs b/packages/core/src/create.rs index 6159c882b..f332760a5 100644 --- a/packages/core/src/create.rs +++ b/packages/core/src/create.rs @@ -66,9 +66,9 @@ 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); + self.runtime.scope_stack.borrow_mut().push(scope); let out = self.create(template); - self.scope_stack.pop(); + self.runtime.scope_stack.borrow_mut().pop(); out } @@ -522,7 +522,7 @@ impl<'b> VirtualDom { .take() .map(|props| { let unbounded_props: Box = 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()) } diff --git a/packages/core/src/diff.rs b/packages/core/src/diff.rs index 7865224aa..da1716e70 100644 --- a/packages/core/src/diff.rs +++ b/packages/core/src/diff.rs @@ -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) { @@ -210,7 +209,7 @@ impl<'b> VirtualDom { self.diff_scope(scope_id); self.dirty_scopes.remove(&DirtyScope { - height: self.scopes[scope_id.0].height, + height: self.runtime.scope_contexts[scope_id.0].height, id: scope_id, }); } @@ -714,7 +713,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 +919,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 +945,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 +966,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"), } diff --git a/packages/core/src/lib.rs b/packages/core/src/lib.rs index 565ae12be..b65eaa86a 100644 --- a/packages/core/src/lib.rs +++ b/packages/core/src/lib.rs @@ -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; @@ -31,6 +33,7 @@ pub(crate) mod innerlude { pub use crate::nodes::*; pub use crate::properties::*; pub use crate::scheduler::*; + pub use crate::scope_context::*; pub use crate::scopes::*; pub use crate::virtual_dom::*; @@ -81,9 +84,11 @@ 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, current_scope_id, fc_to_builder, has_context, provide_context, + provide_root_context, schedule_update_any, suspend, throw, AnyValue, Component, Element, + Event, EventHandler, Fragment, IntoAttributeValue, LazyNodes, Properties, Scope, ScopeId, + ScopeState, Scoped, TaskId, Template, TemplateAttribute, TemplateNode, Throw, VNode, + VirtualDom, }; } diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs new file mode 100644 index 000000000..7a9921e99 --- /dev/null +++ b/packages/core/src/runtime.rs @@ -0,0 +1,87 @@ +use std::cell::RefCell; + +use crate::{ + innerlude::{DirtyScope, Scheduler, SchedulerMsg}, + scope_context::ScopeContext, + scopes::{ScopeId, ScopeState}, +}; +use rustc_hash::FxHashSet; +use slab::Slab; +use std::{collections::BTreeSet, rc::Rc}; + +thread_local! { + static RUNTIMES: RefCell> = RefCell::new(vec![]); +} + +/// Pushes a new scope onto the stack +pub(crate) fn push_runtime(runtime: 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: F) -> Option +where + F: FnOnce(&Runtime) -> R, +{ + RUNTIMES.with(|stack| { + let stack = stack.borrow(); + stack.last().map(f) + }) +} + +/// Runs a function with the current scope +pub(crate) fn with_current_scope(f: F) -> Option +where + F: FnOnce(&ScopeContext) -> R, +{ + with_runtime(|runtime| { + runtime + .current_scope_id() + .and_then(|scope| runtime.get_context(scope).map(f)) + }) + .flatten() +} + +pub struct Runtime { + pub(crate) scope_contexts: Slab, + pub(crate) scheduler: Rc, + + // While diffing we need some sort of way of breaking off a stream of suspended mutations. + pub(crate) scope_stack: RefCell>, +} + +impl Runtime { + pub(crate) fn new(scheduler: Rc) -> Rc { + Rc::new(Self { + scheduler, + + scope_contexts: Default::default(), + + scope_stack: Default::default(), + }) + } + + /// Get the current scope id + pub fn current_scope_id(&self) -> Option { + self.scope_stack.borrow().last().copied() + } + + /// Get the state for any scope given its ID + /// + /// This is useful for inserting or removing contexts from a scope, or rendering out its root node + pub fn get_context(&self, id: ScopeId) -> Option<&ScopeContext> { + self.scope_contexts.get(id.0).map(|f| &*f) + } + + /// Get the single scope at the top of the Runtime tree that will always be around + /// + /// This scope has a ScopeId of 0 and is the root of the tree + pub fn base_context(&self) -> &ScopeContext { + self.get_context(ScopeId(0)).unwrap() + } +} diff --git a/packages/core/src/scheduler/wait.rs b/packages/core/src/scheduler/wait.rs index b475c6751..a04bf2730 100644 --- a/packages/core/src/scheduler/wait.rs +++ b/packages/core/src/scheduler/wait.rs @@ -7,7 +7,7 @@ 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 mut tasks = self.runtime.scheduler.tasks.borrow_mut(); let task = match tasks.get(id.0) { Some(task) => task, @@ -20,8 +20,8 @@ impl VirtualDom { // 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); diff --git a/packages/core/src/scope_arena.rs b/packages/core/src/scope_arena.rs index b298a8996..1a64612bf 100644 --- a/packages/core/src/scope_arena.rs +++ b/packages/core/src/scope_arena.rs @@ -13,35 +13,29 @@ impl VirtualDom { props: Box>, 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, + entry.insert(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()) + }) } pub(crate) fn run_scope(&mut self, scope_id: ScopeId) -> &RenderReturn { @@ -51,10 +45,10 @@ impl VirtualDom { 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); @@ -77,18 +71,19 @@ 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 diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs new file mode 100644 index 000000000..e1a64bc2b --- /dev/null +++ b/packages/core/src/scope_context.rs @@ -0,0 +1,288 @@ +use crate::{ + innerlude::{ErrorBoundary, Scheduler, SchedulerMsg}, + runtime::{with_current_scope, with_runtime}, + Element, ScopeId, TaskId, +}; +use rustc_hash::FxHashSet; +use std::{ + any::{Any, TypeId}, + 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 struct ScopeContext { + pub(crate) name: &'static str, + + pub(crate) id: ScopeId, + pub(crate) parent_id: Option, + + pub(crate) height: u32, + pub(crate) suspended: Cell, + + pub(crate) shared_contexts: RefCell)>>, + + pub(crate) tasks: Rc, + pub(crate) spawned_tasks: RefCell>, +} + +impl ScopeContext { + pub fn name(&self) -> &str { + self.name + } + + pub fn height(&self) -> u32 { + self.height + } + + pub fn parent_id(&self) -> Option { + 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 { + 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 { + 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(&self) -> Option { + self.shared_contexts + .borrow() + .iter() + .find(|(k, _)| *k == TypeId::of::()) + .map(|(_, v)| v)? + .downcast_ref::() + .cloned() + } + + /// Try to retrieve a shared state with type `T` from any parent scope. + /// + /// Clones the state if it exists. + pub fn consume_context(&self) -> Option { + if let Some(this_ctx) = self.has_context() { + return Some(this_ctx); + } + + let mut search_parent = self.parent_id; + with_runtime(|runtime| { + let mut result = None; + while let Some(parent_id) = search_parent { + let parent = runtime.get_context(parent_id).unwrap(); + if let Some(shared) = parent + .shared_contexts + .borrow() + .iter() + .find(|(k, _)| *k == TypeId::of::()) + { + result = shared.1.downcast_ref::().cloned(); + break; + } + search_parent = parent.parent_id; + } + result + }) + .flatten() + } + + /// 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::(); + /// render!(div { "hello {state.0}" }) + /// } + /// ``` + pub fn provide_context(&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::() { + std::mem::swap(ctx, &mut value.clone()); + return value; + } + } + + // Else, just push it + contexts.push((TypeId::of::(), 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(&self, context: T) -> T { + with_runtime(|runtime| { + // Walk upwards until there is no more parent - and tada we have the root + let mut parent = runtime.get_context(self.scope_id()).unwrap(); + while let Some(next_parent) = parent.parent_id { + parent = runtime.get_context(next_parent).unwrap(); + } + debug_assert_eq!(parent.scope_id(), ScopeId(0)); + + parent.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 + '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 + '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 + '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 + } + + /// 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::>() { + 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 { + 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 [`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> { + with_current_scope(|cx| cx.schedule_update_any()) +} + +/// Get the current scope id +pub fn current_scope_id() -> Option { + with_runtime(|rt| rt.current_scope_id()).flatten() +} + +/// Consume context from the current scope +pub fn consume_context() -> Option { + with_current_scope(|cx| cx.consume_context::()).flatten() +} + +/// Check if the current scope has a context +pub fn has_context() -> Option { + with_current_scope(|cx| cx.has_context::()).flatten() +} + +/// Provide context to the current scope +pub fn provide_context(value: T) -> Option { + with_current_scope(|cx| cx.provide_context(value)) +} + +/// Provide a context to the root scope +pub fn provide_root_context(value: T) -> Option { + with_current_scope(|cx| cx.provide_root_context(value)) +} + +/// Suspends the current component +pub fn suspend() -> Option> { + 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() +} diff --git a/packages/core/src/scopes.rs b/packages/core/src/scopes.rs index 9470c3d0d..d1897331a 100644 --- a/packages/core/src/scopes.rs +++ b/packages/core/src/scopes.rs @@ -2,16 +2,17 @@ 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}, + any::Any, cell::{Cell, RefCell, UnsafeCell}, fmt::{Arguments, Debug}, future::Future, @@ -66,26 +67,17 @@ pub struct ScopeId(pub usize); /// /// This struct exists to provide a common interface for all scopes without relying on generics. pub struct ScopeState { + pub(crate) runtime: Rc, + pub(crate) context_id: ScopeId, + pub(crate) render_cnt: Cell, - 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, - pub(crate) hooks: RefCell>>>, pub(crate) hook_idx: Cell, - pub(crate) shared_contexts: RefCell)>>, - - pub(crate) tasks: Rc, - pub(crate) spawned_tasks: RefCell>, - pub(crate) borrowed_props: RefCell>>, pub(crate) attributes_to_drop: RefCell>>, @@ -93,6 +85,10 @@ pub struct ScopeState { } impl<'src> ScopeState { + pub(crate) fn context(&self) -> &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 +107,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 +170,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`]. @@ -193,9 +189,9 @@ impl<'src> ScopeState { /// /// assert_eq!(base.parent(), None); /// ``` - pub fn parent(&self) -> Option { + pub fn parent_id(&self) -> Option { // 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 +208,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 { - 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 +224,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 { - 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(&self) -> Option { - self.shared_contexts - .borrow() - .iter() - .find(|(k, _)| *k == TypeId::of::()) - .map(|(_, v)| v)? - .downcast_ref::() - .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(&self) -> Option { - 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::()) - { - return shared.1.downcast_ref::().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 +273,7 @@ impl<'src> ScopeState { /// } /// ``` pub fn provide_context(&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::() { - std::mem::swap(ctx, &mut value.clone()); - return value; - } - } - - // Else, just push it - contexts.push((TypeId::of::(), Box::new(value.clone()))); - - value + self.context().provide_context(value) } /// Provide a context to the root and then consume it @@ -333,52 +284,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(&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 + '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 + '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 + '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,7 +411,7 @@ impl<'src> ScopeState { /// fn(Scope) -> Element; /// async fn(Scope>) -> Element; /// ``` - pub fn component

( + pub fn component( &'src self, component: fn(Scope<'src, P>) -> Element<'src>, props: P, @@ -564,8 +494,7 @@ impl<'src> ScopeState { /// Mark this component as suspended and then return None pub fn suspend(&self) -> Option { - self.suspended.set(true); - None + self.context().suspend() } /// Store a value between renders. The foundational hook for all other hooks. diff --git a/packages/core/src/virtual_dom.rs b/packages/core/src/virtual_dom.rs index dce5415f6..0d22cbeea 100644 --- a/packages/core/src/virtual_dom.rs +++ b/packages/core/src/virtual_dom.rs @@ -9,6 +9,7 @@ use crate::{ mutations::Mutation, nodes::RenderReturn, nodes::{Template, TemplateId}, + runtime::Runtime, scopes::{ScopeId, ScopeState}, AttributeValue, Element, Event, Scope, }; @@ -174,24 +175,24 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc}; /// } /// ``` pub struct VirtualDom { + pub(crate) scopes: Slab, + + pub(crate) dirty_scopes: BTreeSet, + // Maps a template path to a map of byteindexes to templates pub(crate) templates: FxHashMap>>, - pub(crate) scopes: Slab>, - pub(crate) dirty_scopes: BTreeSet, - pub(crate) scheduler: Rc, // 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, - // While diffing we need some sort of way of breaking off a stream of suspended mutations. - pub(crate) scope_stack: Vec, + pub(crate) mutations: Mutations<'static>, + + pub(crate) runtime: Rc, // Currently suspended scopes pub(crate) suspended_scopes: FxHashSet, pub(crate) rx: futures_channel::mpsc::UnboundedReceiver, - - pub(crate) mutations: Mutations<'static>, } impl VirtualDom { @@ -251,16 +252,16 @@ impl VirtualDom { /// ``` pub fn new_with_props(root: fn(Scope

) -> 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( @@ -281,7 +282,7 @@ 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) } /// Get the single scope at the top of the VirtualDom tree that will always be around @@ -301,10 +302,10 @@ 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(); self.dirty_scopes.insert(DirtyScope { height, id }); } } @@ -501,10 +502,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, }); } } diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index a0c3534b0..bfa16363b 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -9,3 +9,4 @@ edition = "2018" [dependencies] dioxus-core = { workspace = true } slab = { workspace = true } +bumpalo = { version = "3.6" } diff --git a/packages/signals/src/copy.rs b/packages/signals/src/copy.rs new file mode 100644 index 000000000..a10540429 --- /dev/null +++ b/packages/signals/src/copy.rs @@ -0,0 +1,301 @@ +use std::{ + cell::{Cell, Ref, RefCell, RefMut}, + marker::PhantomData, + rc::Rc, +}; + +use bumpalo::Bump; + +/// # Example +/// +/// ```compile_fail +/// let data = String::from("hello world"); +/// let store = Store::default(); +/// let owner = store.owner(); +/// let key = owner.insert(&data); +/// drop(data); +/// assert_eq!(*key.read(), "hello world"); +/// ``` +#[allow(unused)] +fn compile_fail() {} + +#[test] +fn reused() { + let store = Store::default(); + let first_ptr; + { + let owner = store.owner(); + first_ptr = owner.insert(1).raw.data.as_ptr(); + drop(owner); + } + { + let owner = store.owner(); + let second_ptr = owner.insert(1234).raw.data.as_ptr(); + assert_eq!(first_ptr, second_ptr); + drop(owner); + } +} + +#[test] +fn leaking_is_ok() { + let data = String::from("hello world"); + let store = Store::default(); + let key; + { + // create an owner + let owner = store.owner(); + // insert data into the store + key = owner.insert(data); + // don't drop the owner + std::mem::forget(owner); + } + assert_eq!(key.try_read().as_deref(), Some(&"hello world".to_string())); +} + +#[test] +fn drops() { + let data = String::from("hello world"); + let store = Store::default(); + let key; + { + // create an owner + let owner = store.owner(); + // insert data into the store + key = owner.insert(data); + // drop the owner + } + assert!(key.try_read().is_none()); +} + +#[test] +fn works() { + let store = Store::default(); + let owner = store.owner(); + let key = owner.insert(1); + + assert_eq!(*key.read(), 1); +} + +#[test] +fn insert_while_reading() { + let store = Store::default(); + let owner = store.owner(); + let key; + { + let data: String = "hello world".to_string(); + key = owner.insert(data); + } + let value = key.read(); + owner.insert(&1); + assert_eq!(*value, "hello world"); +} + +#[test] +#[should_panic] +fn panics() { + let store = Store::default(); + let owner = store.owner(); + let key = owner.insert(1); + drop(owner); + + assert_eq!(*key.read(), 1); +} + +#[test] +fn fuzz() { + fn maybe_owner_scope( + store: &Store, + valid_keys: &mut Vec>, + invalid_keys: &mut Vec>, + path: &mut Vec, + ) { + let branch_cutoff = 5; + let children = if path.len() < branch_cutoff { + rand::random::() % 4 + } else { + rand::random::() % 2 + }; + + for i in 0..children { + let owner = store.owner(); + let key = owner.insert(format!("hello world {path:?}")); + valid_keys.push(key); + path.push(i); + // read all keys + println!("{:?}", path); + for key in valid_keys.iter() { + let value = key.read(); + println!("{:?}", value); + assert!(value.starts_with("hello world")); + } + #[cfg(debug_assertions)] + for key in invalid_keys.iter() { + assert!(!key.validate()); + } + maybe_owner_scope(store, valid_keys, invalid_keys, path); + invalid_keys.push(valid_keys.pop().unwrap()); + path.pop(); + } + } + + for _ in 0..10 { + let store = Store::default(); + maybe_owner_scope(&store, &mut Vec::new(), &mut Vec::new(), &mut Vec::new()); + } +} + +pub struct CopyHandle { + raw: MemoryLocation, + #[cfg(debug_assertions)] + generation: u32, + _marker: PhantomData, +} + +impl CopyHandle { + #[inline(always)] + fn validate(&self) -> bool { + #[cfg(debug_assertions)] + { + self.raw.generation.get() == self.generation + } + #[cfg(not(debug_assertions))] + { + true + } + } + + pub fn try_read(&self) -> Option> { + self.validate() + .then(|| { + Ref::filter_map(self.raw.data.borrow(), |any| { + any.as_ref()?.downcast_ref::() + }) + .ok() + }) + .flatten() + } + + pub fn read(&self) -> Ref<'_, T> { + self.try_read().unwrap() + } + + pub fn try_write(&self) -> Option> { + self.validate() + .then(|| { + RefMut::filter_map(self.raw.data.borrow_mut(), |any| { + any.as_mut()?.downcast_mut::() + }) + .ok() + }) + .flatten() + } + + pub fn write(&self) -> RefMut<'_, T> { + self.try_write().unwrap() + } +} + +impl Copy for CopyHandle {} + +impl Clone for CopyHandle { + fn clone(&self) -> Self { + *self + } +} + +#[derive(Clone, Copy)] +struct MemoryLocation { + data: &'static RefCell>>, + #[cfg(debug_assertions)] + generation: &'static Cell, +} + +impl MemoryLocation { + #[allow(unused)] + fn drop(&self) { + let old = self.data.borrow_mut().take(); + #[cfg(debug_assertions)] + if old.is_some() { + let new_generation = self.generation.get() + 1; + self.generation.set(new_generation); + } + } + + fn replace(&mut self, value: T) -> CopyHandle { + let mut inner_mut = self.data.borrow_mut(); + + let raw = Box::new(value); + let old = inner_mut.replace(raw); + assert!(old.is_none()); + CopyHandle { + raw: *self, + #[cfg(debug_assertions)] + generation: self.generation.get(), + _marker: PhantomData, + } + } +} + +#[derive(Clone)] +pub struct Store { + bump: &'static Bump, + recycled: Rc>>, +} + +impl Default for Store { + fn default() -> Self { + Self { + bump: Box::leak(Box::new(Bump::new())), + recycled: Default::default(), + } + } +} + +impl Store { + fn recycle(&self, location: MemoryLocation) { + location.drop(); + self.recycled.borrow_mut().push(location); + } + + fn claim(&self) -> MemoryLocation { + if let Some(location) = self.recycled.borrow_mut().pop() { + location + } else { + let data: &'static RefCell<_> = self.bump.alloc(RefCell::new(None)); + MemoryLocation { + data, + #[cfg(debug_assertions)] + generation: self.bump.alloc(Cell::new(0)), + } + } + } + + pub fn owner(&self) -> Owner { + Owner { + store: self.clone(), + owned: Default::default(), + } + } +} + +pub struct Owner { + store: Store, + owned: Rc>>, +} + +impl Owner { + pub fn insert(&self, value: T) -> CopyHandle { + let mut location = self.store.claim(); + let key = location.replace(value); + self.owned.borrow_mut().push(location); + key + } +} + +impl Drop for Owner { + fn drop(&mut self) { + for location in self.owned.borrow().iter() { + self.store.recycle(*location) + } + } +} diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index 5b6a740cf..803d07a61 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -1,70 +1,65 @@ use std::{ cell::{Ref, RefMut}, fmt::Display, - marker::PhantomData, ops::{Add, Div, Mul, Sub}, + sync::Arc, }; +mod copy; mod rt; - -use dioxus_core::ScopeState; pub use rt::*; -pub fn use_init_signal_rt(cx: &ScopeState) { - cx.use_hook(|| { - let rt = claim_rt(cx.schedule_update_any()); - cx.provide_context(rt); - }); -} +use dioxus_core::{ + prelude::{current_scope_id, schedule_update_any}, + ScopeId, ScopeState, +}; pub fn use_signal(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal { - cx.use_hook(|| { - let rt: &'static SignalRt = match cx.consume_context() { - Some(rt) => rt, - None => cx.provide_context(claim_rt(cx.schedule_update_any())), - }; - - let id = rt.init(f()); - rt.subscribe(id, cx.scope_id()); - - struct SignalHook { - signal: Signal, - } - - impl Drop for SignalHook { - fn drop(&mut self) { - self.signal.rt.remove(self.signal.id); - } - } - - SignalHook { - signal: Signal { - id, - rt, - t: PhantomData, - }, - } - }) - .signal + *cx.use_hook(|| Signal::new(f())) } -pub struct Signal { - id: usize, - rt: &'static SignalRt, - t: PhantomData, +struct SignalData { + subscribers: Vec, + update_any: Arc, + value: T, +} + +pub struct Signal { + inner: CopyValue>, } impl Signal { + pub fn new(value: T) -> Self { + Self { + inner: CopyValue::new(SignalData { + subscribers: Vec::new(), + update_any: schedule_update_any().expect("in a virtual dom"), + value, + }), + } + } + pub fn read(&self) -> Ref { - self.rt.read(self.id) + if let Some(current_scope_id) = current_scope_id() { + let mut inner = self.inner.write(); + if !inner.subscribers.contains(¤t_scope_id) { + inner.subscribers.push(current_scope_id); + } + } + Ref::map(self.inner.read(), |v| &v.value) } pub fn write(&self) -> RefMut { - self.rt.write(self.id) + let inner = self.inner.write(); + for &scope_id in &inner.subscribers { + (inner.update_any)(scope_id); + } + + RefMut::map(inner, |v| &mut v.value) } pub fn set(&mut self, value: T) { - self.rt.set(self.id, value); + *self.write() = value; } pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { @@ -72,23 +67,15 @@ impl Signal { f(&*write) } - pub fn update(&self, _f: impl FnOnce(&mut T) -> O) -> O { + pub fn update(&self, f: impl FnOnce(&mut T) -> O) -> O { let mut write = self.write(); - _f(&mut *write) + f(&mut *write) } } impl Signal { pub fn get(&self) -> T { - self.rt.get(self.id) - } -} - -impl std::ops::Deref for Signal { - type Target = dyn Fn() -> T; - - fn deref(&self) -> &Self::Target { - self.rt.getter(self.id) + self.read().clone() } } @@ -102,7 +89,7 @@ impl Copy for Signal {} impl Display for Signal { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.rt.with::(self.id, |v| T::fmt(v, f)) + self.with(|v| Display::fmt(v, f)) } } diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index e849f9008..def6666b1 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -1,121 +1,65 @@ -use std::{any::Any, cell::RefCell, sync::Arc}; +use std::cell::{Ref, RefMut}; -use dioxus_core::ScopeId; -use slab::Slab; +use std::rc::Rc; -thread_local! { - // we cannot drop these since any future might be using them - static RUNTIMES: RefCell> = RefCell::new(Vec::new()); -} +use dioxus_core::prelude::{consume_context, provide_root_context}; -/// Provide the runtime for signals -/// -/// This will reuse dead runtimes -pub fn claim_rt(update_any: Arc) -> &'static SignalRt { - RUNTIMES.with(|runtimes| { - if let Some(rt) = runtimes.borrow_mut().pop() { - return rt; +use crate::copy::{CopyHandle, Owner, Store}; + +fn current_store() -> Store { + match consume_context() { + Some(rt) => rt, + None => { + let store = Store::default(); + provide_root_context(store).expect("in a virtual dom") } - - Box::leak(Box::new(SignalRt { - signals: RefCell::new(Slab::new()), - update_any, - })) - }) + } } -/// Push this runtime into the global runtime list -pub fn reclam_rt(_rt: &'static SignalRt) { - RUNTIMES.with(|runtimes| { - runtimes.borrow_mut().push(_rt); - }); +fn current_owner() -> Rc { + match consume_context() { + Some(rt) => rt, + None => { + let owner = Rc::new(current_store().owner()); + provide_root_context(owner).expect("in a virtual dom") + } + } } -pub struct SignalRt { - pub(crate) signals: RefCell>, - pub(crate) update_any: Arc, +impl Copy for CopyValue {} + +impl Clone for CopyValue { + fn clone(&self) -> Self { + *self + } } -impl SignalRt { - pub fn init(&'static self, val: T) -> usize { - self.signals.borrow_mut().insert(Inner { - value: Box::new(val), - subscribers: Vec::new(), - getter: None, - }) - } +pub struct CopyValue { + pub value: CopyHandle, +} - pub fn subscribe(&self, id: usize, subscriber: ScopeId) { - self.signals.borrow_mut()[id].subscribers.push(subscriber); - } +impl CopyValue { + pub fn new(value: T) -> Self { + let owner = current_owner(); - pub fn get(&self, id: usize) -> T { - self.signals.borrow()[id] - .value - .downcast_ref::() - .cloned() - .unwrap() - } - - pub fn set(&self, id: usize, value: T) { - let mut signals = self.signals.borrow_mut(); - let inner = &mut signals[id]; - inner.value = Box::new(value); - - for subscriber in inner.subscribers.iter() { - (self.update_any)(*subscriber); + Self { + value: owner.insert(value), } } - pub fn remove(&self, id: usize) { - self.signals.borrow_mut().remove(id); + pub fn try_read(&self) -> Option> { + self.value.try_read() } - pub fn with(&self, id: usize, f: impl FnOnce(&T) -> O) -> O { - let signals = self.signals.borrow(); - let inner = &signals[id]; - let inner = inner.value.downcast_ref::().unwrap(); - f(inner) + pub fn read(&self) -> Ref<'_, T> { + self.value.read() } - pub(crate) fn read(&self, id: usize) -> std::cell::Ref { - let signals = self.signals.borrow(); - std::cell::Ref::map(signals, |signals| { - signals[id].value.downcast_ref::().unwrap() - }) + pub fn try_write(&self) -> Option> { + self.value.try_write() } - pub(crate) fn write(&self, id: usize) -> std::cell::RefMut { - let signals = self.signals.borrow_mut(); - std::cell::RefMut::map(signals, |signals| { - signals[id].value.downcast_mut::().unwrap() - }) - } - - pub(crate) fn getter(&self, id: usize) -> &dyn Fn() -> T { - let mut signals = self.signals.borrow_mut(); - let inner = &mut signals[id]; - let r = inner.getter.as_mut(); - - if r.is_none() { - let rt = self; - let r = move || rt.get::(id); - let getter: Box T> = Box::new(r); - let getter: Box = unsafe { std::mem::transmute(getter) }; - - inner.getter = Some(getter); - } - - let r = inner.getter.as_ref().unwrap(); - - unsafe { std::mem::transmute::<&dyn Fn(), &dyn Fn() -> T>(r) } + pub fn write(&self) -> RefMut<'_, T> { + self.value.write() } } - -pub(crate) struct Inner { - pub value: Box, - pub subscribers: Vec, - - // todo: this has a soundness hole in it that you might not run into - pub getter: Option>, -} From cb4c46154d6b145c9fdb98e34d1e43bd2c211437 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 14:12:59 -0700 Subject: [PATCH 02/39] fix scope context --- examples/clock.rs | 4 +- packages/core/src/arena.rs | 10 +++-- packages/core/src/diff.rs | 2 +- packages/core/src/runtime.rs | 64 ++++++++++++++++++------------ packages/core/src/scope_arena.rs | 11 ++++- packages/core/src/scope_context.rs | 23 ++++++++--- packages/core/src/scopes.rs | 14 +++++-- 7 files changed, 83 insertions(+), 45 deletions(-) diff --git a/examples/clock.rs b/examples/clock.rs index 505a5e87c..e59538edc 100644 --- a/examples/clock.rs +++ b/examples/clock.rs @@ -3,15 +3,13 @@ //! The example from the README.md. use dioxus::prelude::*; -use dioxus_signals::{use_init_signal_rt, use_signal}; +use dioxus_signals::use_signal; fn main() { dioxus_desktop::launch(app); } fn app(cx: Scope) -> Element { - use_init_signal_rt(cx); - let mut count = use_signal(cx, || 0); use_future!(cx, || async move { diff --git a/packages/core/src/arena.rs b/packages/core/src/arena.rs index 25b040643..30a9cba8f 100644 --- a/packages/core/src/arena.rs +++ b/packages/core/src/arena.rs @@ -110,11 +110,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(); + { + let context = scope.context(); - // Drop all the futures once the hooks are dropped - for task_id in context.spawned_tasks.borrow_mut().drain() { - context.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); diff --git a/packages/core/src/diff.rs b/packages/core/src/diff.rs index da1716e70..e3ca19c3a 100644 --- a/packages/core/src/diff.rs +++ b/packages/core/src/diff.rs @@ -209,7 +209,7 @@ impl<'b> VirtualDom { self.diff_scope(scope_id); self.dirty_scopes.remove(&DirtyScope { - height: self.runtime.scope_contexts[scope_id.0].height, + height: self.runtime.get_context(scope_id).unwrap().height, id: scope_id, }); } diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs index 7a9921e99..7b9c7c05c 100644 --- a/packages/core/src/runtime.rs +++ b/packages/core/src/runtime.rs @@ -1,20 +1,14 @@ -use std::cell::RefCell; +use std::cell::{Ref, RefCell}; -use crate::{ - innerlude::{DirtyScope, Scheduler, SchedulerMsg}, - scope_context::ScopeContext, - scopes::{ScopeId, ScopeState}, -}; -use rustc_hash::FxHashSet; -use slab::Slab; -use std::{collections::BTreeSet, rc::Rc}; +use crate::{innerlude::Scheduler, scope_context::ScopeContext, scopes::ScopeId}; +use std::rc::Rc; thread_local! { - static RUNTIMES: RefCell> = RefCell::new(vec![]); + static RUNTIMES: RefCell>> = RefCell::new(vec![]); } /// Pushes a new scope onto the stack -pub(crate) fn push_runtime(runtime: Runtime) { +pub(crate) fn push_runtime(runtime: Rc) { RUNTIMES.with(|stack| stack.borrow_mut().push(runtime)); } @@ -30,7 +24,7 @@ where { RUNTIMES.with(|stack| { let stack = stack.borrow(); - stack.last().map(f) + stack.last().map(|r| f(&**r)) }) } @@ -42,28 +36,50 @@ where with_runtime(|runtime| { runtime .current_scope_id() - .and_then(|scope| runtime.get_context(scope).map(f)) + .and_then(|scope| runtime.get_context(scope).map(|sc| f(&*sc))) }) .flatten() } pub struct Runtime { - pub(crate) scope_contexts: Slab, + pub(crate) scope_contexts: RefCell>>, pub(crate) scheduler: Rc, // While diffing we need some sort of way of breaking off a stream of suspended mutations. pub(crate) scope_stack: RefCell>, } +impl Drop for Runtime { + fn drop(&mut self) { + // todo: do this better + pop_runtime(); + } +} + impl Runtime { pub(crate) fn new(scheduler: Rc) -> Rc { - Rc::new(Self { + let runtime = Rc::new(Self { scheduler, scope_contexts: Default::default(), scope_stack: Default::default(), - }) + }); + push_runtime(runtime.clone()); + runtime + } + + /// 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 @@ -71,17 +87,13 @@ impl Runtime { self.scope_stack.borrow().last().copied() } - /// Get the state for any scope given its ID + /// 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 fn get_context(&self, id: ScopeId) -> Option<&ScopeContext> { - self.scope_contexts.get(id.0).map(|f| &*f) - } - - /// Get the single scope at the top of the Runtime tree that will always be around - /// - /// This scope has a ScopeId of 0 and is the root of the tree - pub fn base_context(&self) -> &ScopeContext { - self.get_context(ScopeId(0)).unwrap() + pub fn get_context(&self, id: ScopeId) -> Option> { + Ref::filter_map(self.scope_contexts.borrow(), |contexts| { + contexts.get(id.0).and_then(|f| f.as_ref()) + }) + .ok() } } diff --git a/packages/core/src/scope_arena.rs b/packages/core/src/scope_arena.rs index 1a64612bf..2d5e09b0b 100644 --- a/packages/core/src/scope_arena.rs +++ b/packages/core/src/scope_arena.rs @@ -3,6 +3,7 @@ use crate::{ bump_frame::BumpFrame, innerlude::DirtyScope, nodes::RenderReturn, + scope_context::ScopeContext, scopes::{ScopeId, ScopeState}, virtual_dom::VirtualDom, }; @@ -20,7 +21,7 @@ impl VirtualDom { let entry = self.scopes.vacant_entry(); let id = ScopeId(entry.key()); - entry.insert(ScopeState { + let scope = entry.insert(ScopeState { runtime: self.runtime.clone(), context_id: id, @@ -35,7 +36,13 @@ impl VirtualDom { borrowed_props: Default::default(), attributes_to_drop: Default::default(), - }) + }); + + 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 { diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index e1a64bc2b..340845afc 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -32,12 +32,23 @@ pub struct ScopeContext { } impl ScopeContext { - pub fn name(&self) -> &str { - self.name - } - - pub fn height(&self) -> u32 { - self.height + pub(crate) fn new( + name: &'static str, + id: ScopeId, + parent_id: Option, + height: u32, + tasks: Rc, + ) -> 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 { diff --git a/packages/core/src/scopes.rs b/packages/core/src/scopes.rs index d1897331a..e17e08aa9 100644 --- a/packages/core/src/scopes.rs +++ b/packages/core/src/scopes.rs @@ -13,7 +13,7 @@ use crate::{ use bumpalo::{boxed::Box as BumpBox, Bump}; use std::{ any::Any, - cell::{Cell, RefCell, UnsafeCell}, + cell::{Cell, Ref, RefCell, UnsafeCell}, fmt::{Arguments, Debug}, future::Future, rc::Rc, @@ -84,8 +84,14 @@ pub struct ScopeState { pub(crate) props: Option>>, } +impl Drop for ScopeState { + fn drop(&mut self) { + self.runtime.remove_context(self.context_id); + } +} + impl<'src> ScopeState { - pub(crate) fn context(&self) -> &ScopeContext { + pub(crate) fn context(&self) -> Ref<'_, ScopeContext> { self.runtime.get_context(self.context_id).unwrap() } @@ -494,7 +500,9 @@ impl<'src> ScopeState { /// Mark this component as suspended and then return None pub fn suspend(&self) -> Option { - self.context().suspend() + let cx = self.context(); + cx.suspend(); + None } /// Store a value between renders. The foundational hook for all other hooks. From b09e528aaab2f18274d66d6bc158009c68253fee Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 14:14:56 -0700 Subject: [PATCH 03/39] fix recursive runtime drop impl --- packages/core/src/runtime.rs | 8 -------- packages/core/src/virtual_dom.rs | 7 ++++++- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs index 7b9c7c05c..839a055df 100644 --- a/packages/core/src/runtime.rs +++ b/packages/core/src/runtime.rs @@ -49,13 +49,6 @@ pub struct Runtime { pub(crate) scope_stack: RefCell>, } -impl Drop for Runtime { - fn drop(&mut self) { - // todo: do this better - pop_runtime(); - } -} - impl Runtime { pub(crate) fn new(scheduler: Rc) -> Rc { let runtime = Rc::new(Self { @@ -65,7 +58,6 @@ impl Runtime { scope_stack: Default::default(), }); - push_runtime(runtime.clone()); runtime } diff --git a/packages/core/src/virtual_dom.rs b/packages/core/src/virtual_dom.rs index 0d22cbeea..1a2cf5c5d 100644 --- a/packages/core/src/virtual_dom.rs +++ b/packages/core/src/virtual_dom.rs @@ -9,7 +9,7 @@ use crate::{ mutations::Mutation, nodes::RenderReturn, nodes::{Template, TemplateId}, - runtime::Runtime, + runtime::{pop_runtime, push_runtime, Runtime}, scopes::{ScopeId, ScopeState}, AttributeValue, Element, Event, Scope, }; @@ -275,6 +275,9 @@ impl VirtualDom { // the root element is always given element ID 0 since it's the container for the entire tree dom.elements.insert(ElementRef::none()); + // Set this as the current runtime + push_runtime(dom.runtime.clone()); + dom } @@ -648,5 +651,7 @@ impl Drop for VirtualDom { fn drop(&mut self) { // Simply drop this scope which drops all of its children self.drop_scope(ScopeId(0), true); + // remove the current runtime + pop_runtime(); } } From a2c7b69a1dc617b5e9f064761d1fe41ad535c621 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 14:19:59 -0700 Subject: [PATCH 04/39] set the scope stack correctly --- packages/core/src/create.rs | 7 ++----- packages/core/src/diff.rs | 2 -- packages/core/src/runtime.rs | 2 +- packages/core/src/scope_arena.rs | 7 ++++++- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/core/src/create.rs b/packages/core/src/create.rs index f332760a5..17f3229d6 100644 --- a/packages/core/src/create.rs +++ b/packages/core/src/create.rs @@ -65,11 +65,8 @@ impl<'b> VirtualDom { /// Create a new template [`VNode`] and write it to the [`Mutations`] buffer. /// /// 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.runtime.scope_stack.borrow_mut().push(scope); - let out = self.create(template); - self.runtime.scope_stack.borrow_mut().pop(); - out + pub(crate) fn create_scope(&mut self, _scope: ScopeId, template: &'b VNode<'b>) -> usize { + self.create(template) } /// Create this template and write its mutations diff --git a/packages/core/src/diff.rs b/packages/core/src/diff.rs index e3ca19c3a..270c81730 100644 --- a/packages/core/src/diff.rs +++ b/packages/core/src/diff.rs @@ -15,7 +15,6 @@ use DynamicNode::*; impl<'b> VirtualDom { pub(super) fn diff_scope(&mut self, scope: ScopeId) { - 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 @@ -46,7 +45,6 @@ impl<'b> VirtualDom { (Aborted(l), Ready(r)) => self.replace_placeholder(l, [r]), }; } - self.runtime.scope_stack.borrow_mut().pop(); } fn diff_ok_to_err(&mut self, l: &'b VNode<'b>, p: &'b VPlaceholder) { diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs index 839a055df..1ca778edd 100644 --- a/packages/core/src/runtime.rs +++ b/packages/core/src/runtime.rs @@ -45,7 +45,7 @@ pub struct Runtime { pub(crate) scope_contexts: RefCell>>, pub(crate) scheduler: Rc, - // While diffing we need some sort of way of breaking off a stream of suspended mutations. + // We use this to track the current scope pub(crate) scope_stack: RefCell>, } diff --git a/packages/core/src/scope_arena.rs b/packages/core/src/scope_arena.rs index 2d5e09b0b..58fe97a90 100644 --- a/packages/core/src/scope_arena.rs +++ b/packages/core/src/scope_arena.rs @@ -46,6 +46,7 @@ impl VirtualDom { } 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 @@ -94,6 +95,10 @@ impl VirtualDom { } // 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 } } From 998f9e0d005cf9db6e6a14bfd56d3f5627956b00 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 14:24:49 -0700 Subject: [PATCH 05/39] remove static bound from props --- packages/core/src/scopes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/scopes.rs b/packages/core/src/scopes.rs index e17e08aa9..246d2801c 100644 --- a/packages/core/src/scopes.rs +++ b/packages/core/src/scopes.rs @@ -417,7 +417,7 @@ impl<'src> ScopeState { /// fn(Scope) -> Element; /// async fn(Scope>) -> Element; /// ``` - pub fn component( + pub fn component

( &'src self, component: fn(Scope<'src, P>) -> Element<'src>, props: P, From 2b6b3b67b1f8d9c8a0bcba333e9bc62b0578a001 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 14:28:55 -0700 Subject: [PATCH 06/39] move dioxus copy into a separate package --- Cargo.toml | 2 ++ packages/copy/Cargo.toml | 10 ++++++++++ packages/{signals/src/copy.rs => copy/src/lib.rs} | 0 packages/signals/Cargo.toml | 3 +-- packages/signals/src/lib.rs | 1 - packages/signals/src/rt.rs | 2 +- 6 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 packages/copy/Cargo.toml rename packages/{signals/src/copy.rs => copy/src/lib.rs} (100%) diff --git a/Cargo.toml b/Cargo.toml index e6ce4459b..a544335f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,7 @@ members = [ "packages/native-core", "packages/native-core-macro", "packages/rsx-rosetta", + "packages/copy", "packages/signals", "packages/hot-reload", "packages/fullstack", @@ -76,6 +77,7 @@ dioxus-native-core = { path = "packages/native-core", version = "0.4.0" } dioxus-native-core-macro = { path = "packages/native-core-macro", version = "0.4.0" } rsx-rosetta = { path = "packages/rsx-rosetta", version = "0.4.0" } dioxus-signals = { path = "packages/signals" } +dioxus-copy = { path = "packages/copy" } dioxus-hot-reload = { path = "packages/hot-reload", version = "0.4.0" } dioxus-fullstack = { path = "packages/fullstack", version = "0.4.1" } dioxus_server_macro = { path = "packages/server-macro", version = "0.4.1" } diff --git a/packages/copy/Cargo.toml b/packages/copy/Cargo.toml new file mode 100644 index 000000000..acb36426e --- /dev/null +++ b/packages/copy/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "dioxus-copy" +authors = ["Evan Almloff"] +version = "0.0.0" +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +bumpalo = { version = "3.6" } diff --git a/packages/signals/src/copy.rs b/packages/copy/src/lib.rs similarity index 100% rename from packages/signals/src/copy.rs rename to packages/copy/src/lib.rs diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index bfa16363b..1210442aa 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -8,5 +8,4 @@ edition = "2018" [dependencies] dioxus-core = { workspace = true } -slab = { workspace = true } -bumpalo = { version = "3.6" } +dioxus-copy = { workspace = true } \ No newline at end of file diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index 803d07a61..2a30d0798 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -5,7 +5,6 @@ use std::{ sync::Arc, }; -mod copy; mod rt; pub use rt::*; diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index def6666b1..a47b5764b 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -4,7 +4,7 @@ use std::rc::Rc; use dioxus_core::prelude::{consume_context, provide_root_context}; -use crate::copy::{CopyHandle, Owner, Store}; +use dioxus_copy::{CopyHandle, Owner, Store}; fn current_store() -> Store { match consume_context() { From 0be5dbe71508bf33903ddf10258f933db6f7183b Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 14:42:19 -0700 Subject: [PATCH 07/39] fix the context API --- packages/core/src/create.rs | 7 +++++-- packages/core/src/scope_context.rs | 8 +++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/core/src/create.rs b/packages/core/src/create.rs index 17f3229d6..7fbc8a9c8 100644 --- a/packages/core/src/create.rs +++ b/packages/core/src/create.rs @@ -65,8 +65,11 @@ impl<'b> VirtualDom { /// Create a new template [`VNode`] and write it to the [`Mutations`] buffer. /// /// 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.create(template) + pub(crate) fn create_scope(&mut self, scope: ScopeId, template: &'b VNode<'b>) -> usize { + 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 diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index 340845afc..13263f529 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -115,21 +115,19 @@ impl ScopeContext { let mut search_parent = self.parent_id; with_runtime(|runtime| { - let mut result = None; while let Some(parent_id) = search_parent { let parent = runtime.get_context(parent_id).unwrap(); if let Some(shared) = parent .shared_contexts .borrow() .iter() - .find(|(k, _)| *k == TypeId::of::()) + .find_map(|(_, any)| any.downcast_ref::()) { - result = shared.1.downcast_ref::().cloned(); - break; + return Some(shared.clone()); } search_parent = parent.parent_id; } - result + None }) .flatten() } From 3242fc9e88c741e33a440d326d03cf59fa6b5d29 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 14:49:52 -0700 Subject: [PATCH 08/39] add debug impl --- packages/signals/src/lib.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index 2a30d0798..cfb25c96a 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -1,6 +1,6 @@ use std::{ cell::{Ref, RefMut}, - fmt::Display, + fmt::{Debug, Display}, ops::{Add, Div, Mul, Sub}, sync::Arc, }; @@ -92,6 +92,12 @@ impl Display for Signal { } } +impl Debug for Signal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.with(|v| Debug::fmt(v, f)) + } +} + impl + Copy + 'static> std::ops::AddAssign for Signal { fn add_assign(&mut self, rhs: T) { self.set(self.get() + rhs); From 48b1e9e54cae4a09c2f069cba4e4946c8d9d624f Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 14:53:34 -0700 Subject: [PATCH 09/39] fix copy dependencies --- packages/copy/Cargo.toml | 3 +++ packages/signals/Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/copy/Cargo.toml b/packages/copy/Cargo.toml index acb36426e..6e623f67f 100644 --- a/packages/copy/Cargo.toml +++ b/packages/copy/Cargo.toml @@ -8,3 +8,6 @@ edition = "2018" [dependencies] bumpalo = { version = "3.6" } + +[dev-dependencies] +rand = "0.8.5" diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index 1210442aa..11d5542d7 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -8,4 +8,4 @@ edition = "2018" [dependencies] dioxus-core = { workspace = true } -dioxus-copy = { workspace = true } \ No newline at end of file +dioxus-copy = { workspace = true } From 0032f7e2af4b7335f25ad71c09142363188e0dd1 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 15:23:09 -0700 Subject: [PATCH 10/39] fix miri --- packages/core/src/scope_arena.rs | 4 ++-- packages/core/src/virtual_dom.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/core/src/scope_arena.rs b/packages/core/src/scope_arena.rs index 58fe97a90..138431740 100644 --- a/packages/core/src/scope_arena.rs +++ b/packages/core/src/scope_arena.rs @@ -21,7 +21,7 @@ impl VirtualDom { let entry = self.scopes.vacant_entry(); let id = ScopeId(entry.key()); - let scope = entry.insert(ScopeState { + let scope = entry.insert(Box::new(ScopeState { runtime: self.runtime.clone(), context_id: id, @@ -36,7 +36,7 @@ impl VirtualDom { borrowed_props: Default::default(), attributes_to_drop: Default::default(), - }); + })); let context = ScopeContext::new(name, id, parent_id, height, self.runtime.scheduler.clone()); diff --git a/packages/core/src/virtual_dom.rs b/packages/core/src/virtual_dom.rs index 1a2cf5c5d..86094da9d 100644 --- a/packages/core/src/virtual_dom.rs +++ b/packages/core/src/virtual_dom.rs @@ -175,7 +175,7 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc}; /// } /// ``` pub struct VirtualDom { - pub(crate) scopes: Slab, + pub(crate) scopes: Slab>, pub(crate) dirty_scopes: BTreeSet, @@ -285,7 +285,7 @@ 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) + self.scopes.get(id.0).map(|s| &**s) } /// Get the single scope at the top of the VirtualDom tree that will always be around From 07ed3e67dd89cb1e7fb99f985e56197db843b4db Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 15:46:04 -0700 Subject: [PATCH 11/39] add check_generation feature flag --- packages/copy/Cargo.toml | 4 ++++ packages/copy/src/lib.rs | 16 ++++++++-------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/packages/copy/Cargo.toml b/packages/copy/Cargo.toml index 6e623f67f..9c5e84065 100644 --- a/packages/copy/Cargo.toml +++ b/packages/copy/Cargo.toml @@ -11,3 +11,7 @@ bumpalo = { version = "3.6" } [dev-dependencies] rand = "0.8.5" + +[features] +default = ["check_generation"] +check_generation = [] \ No newline at end of file diff --git a/packages/copy/src/lib.rs b/packages/copy/src/lib.rs index a10540429..8e8b8053f 100644 --- a/packages/copy/src/lib.rs +++ b/packages/copy/src/lib.rs @@ -128,7 +128,7 @@ fn fuzz() { println!("{:?}", value); assert!(value.starts_with("hello world")); } - #[cfg(debug_assertions)] + #[cfg(any(debug_assertions, feature = "check_generation"))] for key in invalid_keys.iter() { assert!(!key.validate()); } @@ -146,7 +146,7 @@ fn fuzz() { pub struct CopyHandle { raw: MemoryLocation, - #[cfg(debug_assertions)] + #[cfg(any(debug_assertions, feature = "check_generation"))] generation: u32, _marker: PhantomData, } @@ -154,11 +154,11 @@ pub struct CopyHandle { impl CopyHandle { #[inline(always)] fn validate(&self) -> bool { - #[cfg(debug_assertions)] + #[cfg(any(debug_assertions, feature = "check_generation"))] { self.raw.generation.get() == self.generation } - #[cfg(not(debug_assertions))] + #[cfg(not(any(debug_assertions, feature = "check_generation")))] { true } @@ -206,7 +206,7 @@ impl Clone for CopyHandle { #[derive(Clone, Copy)] struct MemoryLocation { data: &'static RefCell>>, - #[cfg(debug_assertions)] + #[cfg(any(debug_assertions, feature = "check_generation"))] generation: &'static Cell, } @@ -214,7 +214,7 @@ impl MemoryLocation { #[allow(unused)] fn drop(&self) { let old = self.data.borrow_mut().take(); - #[cfg(debug_assertions)] + #[cfg(any(debug_assertions, feature = "check_generation"))] if old.is_some() { let new_generation = self.generation.get() + 1; self.generation.set(new_generation); @@ -229,7 +229,7 @@ impl MemoryLocation { assert!(old.is_none()); CopyHandle { raw: *self, - #[cfg(debug_assertions)] + #[cfg(any(debug_assertions, feature = "check_generation"))] generation: self.generation.get(), _marker: PhantomData, } @@ -264,7 +264,7 @@ impl Store { let data: &'static RefCell<_> = self.bump.alloc(RefCell::new(None)); MemoryLocation { data, - #[cfg(debug_assertions)] + #[cfg(any(debug_assertions, feature = "check_generation"))] generation: self.bump.alloc(Cell::new(0)), } } From a6f611eccf2332c40be22ba052a8d30bab6b13c8 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 17:23:57 -0700 Subject: [PATCH 12/39] fix subscriptions in events --- examples/clock.rs | 62 +++++++-- packages/copy/Cargo.toml | 2 +- packages/copy/src/lib.rs | 11 ++ packages/core/src/arena.rs | 2 +- packages/core/src/events.rs | 6 +- packages/core/src/nodes.rs | 6 +- packages/core/src/scopes.rs | 26 ++-- packages/core/src/virtual_dom.rs | 10 +- packages/signals/src/effect.rs | 52 ++++++++ packages/signals/src/impls.rs | 212 +++++++++++++++++++++++++++++++ packages/signals/src/lib.rs | 125 ++++++++++-------- packages/signals/src/rt.rs | 34 +++-- 12 files changed, 445 insertions(+), 103 deletions(-) create mode 100644 packages/signals/src/effect.rs create mode 100644 packages/signals/src/impls.rs diff --git a/examples/clock.rs b/examples/clock.rs index e59538edc..b0ea29b40 100644 --- a/examples/clock.rs +++ b/examples/clock.rs @@ -1,26 +1,60 @@ -//! Example: README.md showcase -//! -//! The example from the README.md. +#![allow(non_snake_case)] use dioxus::prelude::*; -use dioxus_signals::use_signal; +use dioxus_signals::{use_signal, Effect, Signal}; fn main() { dioxus_desktop::launch(app); } fn app(cx: Scope) -> Element { - let mut count = use_signal(cx, || 0); + let counts = use_signal(cx, || (0..100).map(Signal::new).collect::>()); - use_future!(cx, || async move { - loop { - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - count += 1; - println!("current: {count}"); - } + cx.use_hook(|| { + Effect::new(move || { + println!("Counts: {:?}", counts); + }) }); - cx.render(rsx! { - div { "High-Five counter: {count}" } - }) + render! { + for count in counts { + Child { + count: count, + } + } + } +} + +#[derive(Props, PartialEq)] +struct ChildProps { + count: Signal, +} + +fn Child(cx: Scope) -> Element { + let count = cx.props.count; + + // use_future!(cx, || async move { + // loop { + // tokio::time::sleep(std::time::Duration::from_secs(count.value())).await; + // *count.write() += 1; + // } + // }); + + render! { + div { + "Child: {count}" + button { + onclick: move |_| { + *count.write() += 1; + }, + "Increase" + } + button { + onclick: move |_| { + *count.write() -= 1; + }, + "Decrease" + } + } + } } diff --git a/packages/copy/Cargo.toml b/packages/copy/Cargo.toml index 9c5e84065..56964badd 100644 --- a/packages/copy/Cargo.toml +++ b/packages/copy/Cargo.toml @@ -14,4 +14,4 @@ rand = "0.8.5" [features] default = ["check_generation"] -check_generation = [] \ No newline at end of file +check_generation = [] diff --git a/packages/copy/src/lib.rs b/packages/copy/src/lib.rs index 8e8b8053f..3b091d30a 100644 --- a/packages/copy/src/lib.rs +++ b/packages/copy/src/lib.rs @@ -193,6 +193,17 @@ impl CopyHandle { pub fn write(&self) -> RefMut<'_, T> { self.try_write().unwrap() } + + pub fn ptr_eq(&self, other: &Self) -> bool { + #[cfg(any(debug_assertions, feature = "check_generation"))] + { + self.raw.data.as_ptr() == other.raw.data.as_ptr() && self.generation == other.generation + } + #[cfg(not(any(debug_assertions, feature = "check_generation")))] + { + self.raw.data.as_ptr() == other.raw.data.as_ptr() + } + } } impl Copy for CopyHandle {} diff --git a/packages/core/src/arena.rs b/packages/core/src/arena.rs index 30a9cba8f..b7ec46623 100644 --- a/packages/core/src/arena.rs +++ b/packages/core/src/arena.rs @@ -163,7 +163,7 @@ impl VirtualDom { let listener = unsafe { &*listener }; match &listener.value { AttributeValue::Listener(l) => { - _ = l.take(); + _ = l.callback.take(); } AttributeValue::Any(a) => { _ = a.take(); diff --git a/packages/core/src/events.rs b/packages/core/src/events.rs index ce958db40..c734ebd4a 100644 --- a/packages/core/src/events.rs +++ b/packages/core/src/events.rs @@ -1,7 +1,9 @@ use std::{ cell::{Cell, RefCell}, rc::Rc, + }; +use crate::ScopeId; /// A wrapper around some generic data that handles the event's state /// @@ -134,13 +136,15 @@ impl std::fmt::Debug for Event { /// } /// /// ``` -pub struct EventHandler<'bump, T = ()> { +pub struct EventHandler<'bump, T:?Sized = ()> { + pub(crate) origin: ScopeId, pub(super) callback: RefCell>>, } impl Default for EventHandler<'_, T> { fn default() -> Self { Self { + origin: ScopeId(0), callback: Default::default(), } } diff --git a/packages/core/src/nodes.rs b/packages/core/src/nodes.rs index a108f3577..5406e8f07 100644 --- a/packages/core/src/nodes.rs +++ b/packages/core/src/nodes.rs @@ -1,4 +1,4 @@ -use crate::{ +use crate::prelude::EventHandler;use crate::{ any_props::AnyProps, arena::ElementId, Element, Event, LazyNodes, ScopeId, ScopeState, }; use bumpalo::boxed::Box as BumpBox; @@ -476,7 +476,7 @@ pub enum AttributeValue<'a> { Bool(bool), /// A listener, like "onclick" - Listener(RefCell>>), + Listener(EventHandler<'a, Event>), /// An arbitrary value that implements PartialEq and is static Any(RefCell>>), @@ -485,8 +485,6 @@ pub enum AttributeValue<'a> { None, } -pub type ListenerCb<'a> = BumpBox<'a, dyn FnMut(Event) + 'a>; - /// Any of the built-in values that the Dioxus VirtualDom supports as dynamic attributes on elements that are borrowed /// /// These varients are used to communicate what the value of an attribute is that needs to be updated diff --git a/packages/core/src/scopes.rs b/packages/core/src/scopes.rs index 246d2801c..b43b2143a 100644 --- a/packages/core/src/scopes.rs +++ b/packages/core/src/scopes.rs @@ -446,7 +446,7 @@ 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 @@ -456,22 +456,16 @@ impl<'src> ScopeState { &'src self, mut callback: impl FnMut(Event) + 'src, ) -> AttributeValue<'src> { - // safety: there's no other way to create a dynamicly-dispatched bump box other than alloc + from-raw - // This is the suggested way to build a bumpbox - // - // In theory, we could just use regular boxes - let boxed: BumpBox<'src, dyn FnMut(_) + 'src> = unsafe { - BumpBox::from_raw(self.bump().alloc(move |event: Event| { - if let Ok(data) = event.data.downcast::() { - callback(Event { - propagates: event.propagates, - data, - }); - } - })) - }; + - AttributeValue::Listener(RefCell::new(Some(boxed))) + AttributeValue::Listener(self.event_handler(move |event: Event| { + if let Ok(data) = event.data.downcast::() { + callback(Event { + propagates: event.propagates, + data, + }); + } + })) } /// Create a new [`AttributeValue`] with a value that implements [`AnyValue`] diff --git a/packages/core/src/virtual_dom.rs b/packages/core/src/virtual_dom.rs index 86094da9d..c43af2254 100644 --- a/packages/core/src/virtual_dom.rs +++ b/packages/core/src/virtual_dom.rs @@ -391,9 +391,12 @@ 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 { - if let Some(cb) = listener.borrow_mut().as_deref_mut() { + let origin = listener.origin; + self.runtime.scope_stack.borrow_mut().push(origin); + if let Some(cb) = listener.callback.borrow_mut().as_deref_mut() { cb(uievent.clone()); } + self.runtime.scope_stack.borrow_mut().pop(); if !uievent.propagates.get() { return; @@ -422,9 +425,12 @@ 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 { - if let Some(cb) = listener.borrow_mut().as_deref_mut() { + let origin = listener.origin; + self.runtime.scope_stack.borrow_mut().push(origin); + if let Some(cb) = listener.callback.borrow_mut().as_deref_mut() { cb(uievent.clone()); } + self.runtime.scope_stack.borrow_mut().pop(); break; } diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs new file mode 100644 index 000000000..9bc9b33f2 --- /dev/null +++ b/packages/signals/src/effect.rs @@ -0,0 +1,52 @@ +use dioxus_core::prelude::*; + +use crate::CopyValue; + +#[derive(Default, Clone, Copy)] +pub(crate) struct EffectStack { + pub(crate) effects: CopyValue>, +} + +pub(crate) fn get_effect_stack() -> EffectStack { + match consume_context() { + Some(rt) => rt, + None => { + let store = EffectStack::default(); + provide_root_context(store).expect("in a virtual dom") + } + } +} + +#[derive(Copy, Clone, PartialEq)] +pub struct Effect { + callback: CopyValue>, +} + +impl Effect { + pub(crate) fn current() -> Option { + get_effect_stack().effects.read().last().copied() + } + + pub fn new(callback: impl FnMut() + 'static) -> Self { + let myself = Self { + callback: CopyValue::new(Box::new(callback)), + }; + + myself.try_run(); + + myself + } + + /// Run the effect callback immediately. Returns `true` if the effect was run. Returns `false` is the effect is dead. + pub fn try_run(&self) { + if let Some(mut callback) = self.callback.try_write() { + { + get_effect_stack().effects.write().push(*self); + } + callback(); + { + get_effect_stack().effects.write().pop(); + } + } + } +} diff --git a/packages/signals/src/impls.rs b/packages/signals/src/impls.rs new file mode 100644 index 000000000..d54e5251f --- /dev/null +++ b/packages/signals/src/impls.rs @@ -0,0 +1,212 @@ +use crate::rt::CopyValue; +use crate::Signal; + +use std::cell::{Ref, RefMut}; + +use std::{ + fmt::{Debug, Display}, + ops::{Add, Div, Mul, Sub}, +}; + +macro_rules! impls { + ($ty:ident) => { + impl Default for $ty { + fn default() -> Self { + Self::new(T::default()) + } + } + + impl std::clone::Clone for $ty { + fn clone(&self) -> Self { + *self + } + } + + impl Copy for $ty {} + + impl Display for $ty { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.with(|v| Display::fmt(v, f)) + } + } + + impl Debug for $ty { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.with(|v| Debug::fmt(v, f)) + } + } + + impl + Copy + 'static> std::ops::AddAssign for $ty { + fn add_assign(&mut self, rhs: T) { + self.set(self.value() + rhs); + } + } + + impl + Copy + 'static> std::ops::SubAssign for $ty { + fn sub_assign(&mut self, rhs: T) { + self.set(self.value() - rhs); + } + } + + impl + Copy + 'static> std::ops::MulAssign for $ty { + fn mul_assign(&mut self, rhs: T) { + self.set(self.value() * rhs); + } + } + + impl + Copy + 'static> std::ops::DivAssign for $ty { + fn div_assign(&mut self, rhs: T) { + self.set(self.value() / rhs); + } + } + + impl $ty> { + pub fn push(&self, value: T) { + self.with_mut(|v| v.push(value)) + } + + pub fn pop(&self) -> Option { + self.with_mut(|v| v.pop()) + } + + pub fn insert(&self, index: usize, value: T) { + self.with_mut(|v| v.insert(index, value)) + } + + pub fn remove(&self, index: usize) -> T { + self.with_mut(|v| v.remove(index)) + } + + pub fn clear(&self) { + self.with_mut(|v| v.clear()) + } + + pub fn extend(&self, iter: impl IntoIterator) { + self.with_mut(|v| v.extend(iter)) + } + + pub fn truncate(&self, len: usize) { + self.with_mut(|v| v.truncate(len)) + } + + pub fn swap_remove(&self, index: usize) -> T { + self.with_mut(|v| v.swap_remove(index)) + } + + pub fn retain(&self, f: impl FnMut(&T) -> bool) { + self.with_mut(|v| v.retain(f)) + } + + pub fn split_off(&self, at: usize) -> Vec { + self.with_mut(|v| v.split_off(at)) + } + + pub fn get(&self, index: usize) -> Option> { + Ref::filter_map(self.read(), |v| v.get(index)).ok() + } + + pub fn get_mut(&self, index: usize) -> Option> { + RefMut::filter_map(self.write(), |v| v.get_mut(index)).ok() + } + } + + impl $ty> { + pub fn take(&self) -> Option { + self.with_mut(|v| v.take()) + } + + pub fn replace(&self, value: T) -> Option { + self.with_mut(|v| v.replace(value)) + } + + pub fn unwrap(&self) -> T + where + T: Clone, + { + self.with(|v| v.clone()).unwrap() + } + + pub fn as_ref(&self) -> Option> { + Ref::filter_map(self.read(), |v| v.as_ref()).ok() + } + + pub fn as_mut(&self) -> Option> { + RefMut::filter_map(self.write(), |v| v.as_mut()).ok() + } + + pub fn get_or_insert(&self, default: T) -> Ref<'_, T> { + self.get_or_insert_with(|| default) + } + + pub fn get_or_insert_with(&self, default: impl FnOnce() -> T) -> Ref<'_, T> { + let borrow = self.read(); + if borrow.is_none() { + drop(borrow); + self.with_mut(|v| *v = Some(default())); + Ref::map(self.read(), |v| v.as_ref().unwrap()) + } else { + Ref::map(borrow, |v| v.as_ref().unwrap()) + } + } + } + }; +} + +impls!(CopyValue); +impls!(Signal); + +pub struct CopyValueIterator { + index: usize, + value: CopyValue>, +} + +impl Iterator for CopyValueIterator { + type Item = T; + + fn next(&mut self) -> Option { + let index = self.index; + self.index += 1; + self.value.get(index).map(|v| v.clone()) + } +} + +impl IntoIterator for CopyValue> { + type IntoIter = CopyValueIterator; + + type Item = T; + + fn into_iter(self) -> Self::IntoIter { + CopyValueIterator { + index: 0, + value: self, + } + } +} + +pub struct CopySignalIterator { + index: usize, + value: Signal>, +} + +impl Iterator for CopySignalIterator { + type Item = T; + + fn next(&mut self) -> Option { + let index = self.index; + self.index += 1; + self.value.get(index).map(|v| v.clone()) + } +} + +impl IntoIterator for Signal> { + type IntoIter = CopySignalIterator; + + type Item = T; + + fn into_iter(self) -> Self::IntoIter { + CopySignalIterator { + index: 0, + value: self, + } + } +} diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index cfb25c96a..4340b6484 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -1,15 +1,18 @@ use std::{ - cell::{Ref, RefMut}, - fmt::{Debug, Display}, - ops::{Add, Div, Mul, Sub}, + cell::{Ref, RefCell, RefMut}, + rc::Rc, sync::Arc, }; mod rt; pub use rt::*; +mod effect; +pub use effect::*; +#[macro_use] +mod impls; use dioxus_core::{ - prelude::{current_scope_id, schedule_update_any}, + prelude::{current_scope_id, has_context, provide_context, schedule_update_any}, ScopeId, ScopeState, }; @@ -17,8 +20,36 @@ pub fn use_signal(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal< *cx.use_hook(|| Signal::new(f())) } +#[derive(Clone)] +struct Unsubscriber { + scope: ScopeId, + subscribers: Rc>>>>>, +} + +impl Drop for Unsubscriber { + fn drop(&mut self) { + for subscribers in self.subscribers.borrow().iter() { + subscribers.borrow_mut().retain(|s| *s != self.scope); + } + } +} + +fn current_unsubscriber() -> Unsubscriber { + match has_context() { + Some(rt) => rt, + None => { + let owner = Unsubscriber { + scope: current_scope_id().expect("in a virtual dom"), + subscribers: Default::default(), + }; + provide_context(owner).expect("in a virtual dom") + } + } +} + struct SignalData { - subscribers: Vec, + subscribers: Rc>>, + effect_subscribers: Rc>>, update_any: Arc, value: T, } @@ -31,7 +62,8 @@ impl Signal { pub fn new(value: T) -> Self { Self { inner: CopyValue::new(SignalData { - subscribers: Vec::new(), + subscribers: Default::default(), + effect_subscribers: Default::default(), update_any: schedule_update_any().expect("in a virtual dom"), value, }), @@ -39,21 +71,40 @@ impl Signal { } pub fn read(&self) -> Ref { + let inner = self.inner.read(); if let Some(current_scope_id) = current_scope_id() { - let mut inner = self.inner.write(); - if !inner.subscribers.contains(¤t_scope_id) { - inner.subscribers.push(current_scope_id); + let mut subscribers = inner.subscribers.borrow_mut(); + if !subscribers.contains(¤t_scope_id) { + subscribers.push(current_scope_id); + drop(subscribers); + let unsubscriber = current_unsubscriber(); + inner.subscribers.borrow_mut().push(unsubscriber.scope); } } - Ref::map(self.inner.read(), |v| &v.value) + if let Some(effect) = Effect::current() { + let mut effect_subscribers = inner.effect_subscribers.borrow_mut(); + if !effect_subscribers.contains(&effect) { + effect_subscribers.push(effect); + } + } + Ref::map(inner, |v| &v.value) } pub fn write(&self) -> RefMut { - let inner = self.inner.write(); - for &scope_id in &inner.subscribers { - (inner.update_any)(scope_id); + { + let inner = self.inner.read(); + for &scope_id in &*inner.subscribers.borrow() { + (inner.update_any)(scope_id); + } } + let subscribers = + { std::mem::take(&mut *self.inner.read().effect_subscribers.borrow_mut()) }; + for effect in subscribers { + effect.try_run(); + } + + let inner = self.inner.write(); RefMut::map(inner, |v| &mut v.value) } @@ -66,58 +117,20 @@ impl Signal { f(&*write) } - pub fn update(&self, f: impl FnOnce(&mut T) -> O) -> O { + pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { let mut write = self.write(); f(&mut *write) } } impl Signal { - pub fn get(&self) -> T { + pub fn value(&self) -> T { self.read().clone() } } -impl std::clone::Clone for Signal { - fn clone(&self) -> Self { - *self - } -} - -impl Copy for Signal {} - -impl Display for Signal { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.with(|v| Display::fmt(v, f)) - } -} - -impl Debug for Signal { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.with(|v| Debug::fmt(v, f)) - } -} - -impl + Copy + 'static> std::ops::AddAssign for Signal { - fn add_assign(&mut self, rhs: T) { - self.set(self.get() + rhs); - } -} - -impl + Copy + 'static> std::ops::SubAssign for Signal { - fn sub_assign(&mut self, rhs: T) { - self.set(self.get() - rhs); - } -} - -impl + Copy + 'static> std::ops::MulAssign for Signal { - fn mul_assign(&mut self, rhs: T) { - self.set(self.get() * rhs); - } -} - -impl + Copy + 'static> std::ops::DivAssign for Signal { - fn div_assign(&mut self, rhs: T) { - self.set(self.get() / rhs); +impl PartialEq for Signal { + fn eq(&self, other: &Self) -> bool { + self.inner == other.inner } } diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index a47b5764b..0605fb951 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -26,14 +26,6 @@ fn current_owner() -> Rc { } } -impl Copy for CopyValue {} - -impl Clone for CopyValue { - fn clone(&self) -> Self { - *self - } -} - pub struct CopyValue { pub value: CopyHandle, } @@ -62,4 +54,30 @@ impl CopyValue { pub fn write(&self) -> RefMut<'_, T> { self.value.write() } + + pub fn set(&mut self, value: T) { + *self.write() = value; + } + + pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { + let write = self.read(); + f(&*write) + } + + pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { + let mut write = self.write(); + f(&mut *write) + } +} + +impl CopyValue { + pub fn value(&self) -> T { + self.read().clone() + } +} + +impl PartialEq for CopyValue { + fn eq(&self, other: &Self) -> bool { + self.value.ptr_eq(&other.value) + } } From b3fbbba7113a3e53d49a171cca6a5f6ed72243b8 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 17:25:40 -0700 Subject: [PATCH 13/39] fix signals in futures --- examples/clock.rs | 12 ++++++------ packages/core/src/scheduler/wait.rs | 6 ++++++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/examples/clock.rs b/examples/clock.rs index b0ea29b40..5c4bc4f25 100644 --- a/examples/clock.rs +++ b/examples/clock.rs @@ -33,12 +33,12 @@ struct ChildProps { fn Child(cx: Scope) -> Element { let count = cx.props.count; - // use_future!(cx, || async move { - // loop { - // tokio::time::sleep(std::time::Duration::from_secs(count.value())).await; - // *count.write() += 1; - // } - // }); + use_future!(cx, || async move { + loop { + tokio::time::sleep(std::time::Duration::from_secs(count.value())).await; + *count.write() += 1; + } + }); render! { div { diff --git a/packages/core/src/scheduler/wait.rs b/packages/core/src/scheduler/wait.rs index a04bf2730..47180c240 100644 --- a/packages/core/src/scheduler/wait.rs +++ b/packages/core/src/scheduler/wait.rs @@ -17,6 +17,9 @@ impl VirtualDom { let mut cx = Context::from_waker(&task.waker); + // update the scope stack + self.runtime.scope_stack.borrow_mut().push(task.scope); + // 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 @@ -26,5 +29,8 @@ impl VirtualDom { // Remove it from the scheduler tasks.try_remove(id.0); } + + // Remove the scope from the stack + self.runtime.scope_stack.borrow_mut().pop(); } } From 49001c59d39dd53170837020782221ddd406b5f4 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 17:29:44 -0700 Subject: [PATCH 14/39] add logging to clock example --- examples/clock.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/examples/clock.rs b/examples/clock.rs index 5c4bc4f25..2ed4812cf 100644 --- a/examples/clock.rs +++ b/examples/clock.rs @@ -8,6 +8,8 @@ fn main() { } fn app(cx: Scope) -> Element { + println!("running app"); + let counts = use_signal(cx, || (0..100).map(Signal::new).collect::>()); cx.use_hook(|| { @@ -17,8 +19,9 @@ fn app(cx: Scope) -> Element { }); render! { - for count in counts { + for (i, count) in counts.into_iter().enumerate() { Child { + id: i, count: count, } } @@ -27,10 +30,12 @@ fn app(cx: Scope) -> Element { #[derive(Props, PartialEq)] struct ChildProps { + id: usize, count: Signal, } fn Child(cx: Scope) -> Element { + println!("running child {}", cx.props.id); let count = cx.props.count; use_future!(cx, || async move { From dce418140a934bd68a1041b94752c96d4c256002 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 4 Aug 2023 17:50:05 -0700 Subject: [PATCH 15/39] create a way to hoist ownership to a different scope --- packages/core/src/lib.rs | 10 +++++----- packages/core/src/scope_context.rs | 14 ++++++++++++++ packages/signals/src/lib.rs | 4 ++++ packages/signals/src/rt.rs | 31 +++++++++++++++++++++++++++++- 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/packages/core/src/lib.rs b/packages/core/src/lib.rs index b65eaa86a..d500ca6b5 100644 --- a/packages/core/src/lib.rs +++ b/packages/core/src/lib.rs @@ -84,11 +84,11 @@ pub use crate::innerlude::{ /// This includes types like [`Scope`], [`Element`], and [`Component`]. pub mod prelude { pub use crate::innerlude::{ - consume_context, current_scope_id, fc_to_builder, has_context, provide_context, - provide_root_context, schedule_update_any, suspend, throw, 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, + provide_context, provide_context_to_scope, provide_root_context, schedule_update_any, + suspend, throw, AnyValue, Component, Element, Event, EventHandler, Fragment, + IntoAttributeValue, LazyNodes, Properties, Scope, ScopeId, ScopeState, Scoped, TaskId, + Template, TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom, }; } diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index 13263f529..a724bb27a 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -268,6 +268,15 @@ pub fn consume_context() -> Option { with_current_scope(|cx| cx.consume_context::()).flatten() } +/// Consume context from the current scope +pub fn consume_context_from_scope(scope_id: ScopeId) -> Option { + with_runtime(|rt| { + rt.get_context(scope_id) + .and_then(|cx| cx.consume_context::()) + }) + .flatten() +} + /// Check if the current scope has a context pub fn has_context() -> Option { with_current_scope(|cx| cx.has_context::()).flatten() @@ -278,6 +287,11 @@ pub fn provide_context(value: T) -> Option { with_current_scope(|cx| cx.provide_context(value)) } +/// Provide context to the the given scope +pub fn provide_context_to_scope(scope_id: ScopeId, value: T) -> Option { + 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(value: T) -> Option { with_current_scope(|cx| cx.provide_root_context(value)) diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index 4340b6484..a49a38a18 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -70,6 +70,10 @@ impl Signal { } } + pub fn origin_scope(&self) -> ScopeId { + self.inner.origin_scope() + } + pub fn read(&self) -> Ref { let inner = self.inner.read(); if let Some(current_scope_id) = current_scope_id() { diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index 0605fb951..ca5d5ec9f 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -2,7 +2,11 @@ use std::cell::{Ref, RefMut}; use std::rc::Rc; -use dioxus_core::prelude::{consume_context, provide_root_context}; +use dioxus_core::prelude::{ + consume_context, consume_context_from_scope, current_scope_id, provide_context_to_scope, + provide_root_context, +}; +use dioxus_core::ScopeId; use dioxus_copy::{CopyHandle, Owner, Store}; @@ -26,8 +30,19 @@ fn current_owner() -> Rc { } } +fn owner_in_scope(scope: ScopeId) -> Rc { + match consume_context_from_scope(scope) { + Some(rt) => rt, + None => { + let owner = Rc::new(current_store().owner()); + provide_context_to_scope(scope, owner).expect("in a virtual dom") + } + } +} + pub struct CopyValue { pub value: CopyHandle, + origin_scope: ScopeId, } impl CopyValue { @@ -36,9 +51,23 @@ impl CopyValue { Self { value: owner.insert(value), + origin_scope: current_scope_id().expect("in a virtual dom"), } } + pub fn new_in_scope(value: T, scope: ScopeId) -> Self { + let owner = owner_in_scope(scope); + + Self { + value: owner.insert(value), + origin_scope: scope, + } + } + + pub fn origin_scope(&self) -> ScopeId { + self.origin_scope + } + pub fn try_read(&self) -> Option> { self.value.try_read() } From b0d499036a4d6fe21661d2906eba5c849bc29dd5 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 11:16:22 -0700 Subject: [PATCH 16/39] make future handling functions global --- packages/core/src/lib.rs | 9 +++++---- packages/core/src/scope_context.rs | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/packages/core/src/lib.rs b/packages/core/src/lib.rs index d500ca6b5..363be390d 100644 --- a/packages/core/src/lib.rs +++ b/packages/core/src/lib.rs @@ -85,10 +85,11 @@ pub use crate::innerlude::{ pub mod prelude { pub use crate::innerlude::{ consume_context, consume_context_from_scope, current_scope_id, fc_to_builder, has_context, - provide_context, provide_context_to_scope, provide_root_context, schedule_update_any, - suspend, throw, AnyValue, Component, Element, Event, EventHandler, Fragment, - IntoAttributeValue, LazyNodes, Properties, Scope, ScopeId, ScopeState, Scoped, TaskId, - Template, TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom, + 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, Scope, ScopeId, ScopeState, Scoped, TaskId, Template, TemplateAttribute, + TemplateNode, Throw, VNode, VirtualDom, }; } diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index a724bb27a..36c864117 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -309,3 +309,27 @@ pub fn suspend() -> Option> { 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 + 'static) -> Option { + with_current_scope(|cx| cx.push_future(fut)) +} + +/// Spawns the future but does not return the [`TaskId`] +pub fn spawn(fut: impl Future + '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 + 'static) -> Option { + 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)); +} From 717c09c4a33b774f9b6899eecd50f070391a1d39 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 11:52:54 -0700 Subject: [PATCH 17/39] create tests for signals --- packages/copy/src/lib.rs | 15 +++++ packages/signals/Cargo.toml | 5 ++ packages/signals/src/impls.rs | 8 +-- packages/signals/src/lib.rs | 10 ++++ packages/signals/src/rt.rs | 2 +- packages/signals/tests/create.rs | 60 +++++++++++++++++++ packages/signals/tests/effect.rs | 47 +++++++++++++++ packages/signals/tests/subscribe.rs | 92 +++++++++++++++++++++++++++++ 8 files changed, 234 insertions(+), 5 deletions(-) create mode 100644 packages/signals/tests/create.rs create mode 100644 packages/signals/tests/effect.rs create mode 100644 packages/signals/tests/subscribe.rs diff --git a/packages/copy/src/lib.rs b/packages/copy/src/lib.rs index 3b091d30a..149c14434 100644 --- a/packages/copy/src/lib.rs +++ b/packages/copy/src/lib.rs @@ -1,5 +1,6 @@ use std::{ cell::{Cell, Ref, RefCell, RefMut}, + fmt::Debug, marker::PhantomData, rc::Rc, }; @@ -151,6 +152,20 @@ pub struct CopyHandle { _marker: PhantomData, } +impl Debug for CopyHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + #[cfg(any(debug_assertions, feature = "check_generation"))] + f.write_fmt(format_args!( + "{:?}@{:?}", + self.raw.data.as_ptr(), + self.generation + ))?; + #[cfg(not(any(debug_assertions, feature = "check_generation")))] + f.write_fmt(format_args!("{:?}", self.raw.data.as_ptr()))?; + Ok(()) + } +} + impl CopyHandle { #[inline(always)] fn validate(&self) -> bool { diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index 11d5542d7..19f2039cc 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -9,3 +9,8 @@ edition = "2018" [dependencies] dioxus-core = { workspace = true } dioxus-copy = { workspace = true } +log.workspace = true +simple_logger = "4.2.0" + +[dev-dependencies] +dioxus = { workspace = true } diff --git a/packages/signals/src/impls.rs b/packages/signals/src/impls.rs index d54e5251f..8a3c9db8c 100644 --- a/packages/signals/src/impls.rs +++ b/packages/signals/src/impls.rs @@ -38,25 +38,25 @@ macro_rules! impls { impl + Copy + 'static> std::ops::AddAssign for $ty { fn add_assign(&mut self, rhs: T) { - self.set(self.value() + rhs); + self.with_mut(|v| *v = *v + rhs) } } impl + Copy + 'static> std::ops::SubAssign for $ty { fn sub_assign(&mut self, rhs: T) { - self.set(self.value() - rhs); + self.with_mut(|v| *v = *v - rhs) } } impl + Copy + 'static> std::ops::MulAssign for $ty { fn mul_assign(&mut self, rhs: T) { - self.set(self.value() * rhs); + self.with_mut(|v| *v = *v * rhs) } } impl + Copy + 'static> std::ops::DivAssign for $ty { fn div_assign(&mut self, rhs: T) { - self.set(self.value() / rhs); + self.with_mut(|v| *v = *v / rhs) } } diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index a49a38a18..c0d081f7d 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -77,6 +77,11 @@ impl Signal { pub fn read(&self) -> Ref { let inner = self.inner.read(); if let Some(current_scope_id) = current_scope_id() { + log::trace!( + "{:?} subscribed to {:?}", + self.inner.value, + current_scope_id + ); let mut subscribers = inner.subscribers.borrow_mut(); if !subscribers.contains(¤t_scope_id) { subscribers.push(current_scope_id); @@ -98,6 +103,11 @@ impl Signal { { let inner = self.inner.read(); for &scope_id in &*inner.subscribers.borrow() { + log::trace!( + "Write on {:?} triggered update on {:?}", + self.inner.value, + scope_id + ); (inner.update_any)(scope_id); } } diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index ca5d5ec9f..b37a46a53 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -41,7 +41,7 @@ fn owner_in_scope(scope: ScopeId) -> Rc { } pub struct CopyValue { - pub value: CopyHandle, + pub(crate) value: CopyHandle, origin_scope: ScopeId, } diff --git a/packages/signals/tests/create.rs b/packages/signals/tests/create.rs new file mode 100644 index 000000000..0681263ea --- /dev/null +++ b/packages/signals/tests/create.rs @@ -0,0 +1,60 @@ +#![allow(unused, non_upper_case_globals, non_snake_case)] + +use dioxus::prelude::*; +use dioxus_core::ElementId; +use dioxus_signals::*; + +#[test] +fn create_signals_global() { + let mut dom = VirtualDom::new(|cx| { + render! { + for _ in 0..10 { + Child {} + } + } + }); + + fn Child(cx: Scope) -> Element { + let signal = create_without_cx(); + + render! { + "{signal}" + } + } + + let _edits = dom.rebuild().santize(); + + fn create_without_cx() -> Signal { + Signal::new("hello world".to_string()) + } +} + +#[test] +fn drop_signals() { + let mut dom = VirtualDom::new(|cx| { + let generation = cx.generation(); + + let count = if generation % 2 == 0 { 10 } else { 0 }; + render! { + for _ in 0..count { + Child {} + } + } + }); + + fn Child(cx: Scope) -> Element { + let signal = create_without_cx(); + + render! { + "{signal}" + } + } + + let _ = dom.rebuild().santize(); + dom.mark_dirty(ScopeId(0)); + dom.render_immediate(); + + fn create_without_cx() -> Signal { + Signal::new("hello world".to_string()) + } +} diff --git a/packages/signals/tests/effect.rs b/packages/signals/tests/effect.rs new file mode 100644 index 000000000..513b7e929 --- /dev/null +++ b/packages/signals/tests/effect.rs @@ -0,0 +1,47 @@ +#![allow(unused, non_upper_case_globals, non_snake_case)] +use std::collections::HashMap; +use std::rc::Rc; + +use dioxus::prelude::*; +use dioxus_core::ElementId; +use dioxus_signals::*; + +#[test] +fn effects_rerun() { + simple_logger::SimpleLogger::new().init().unwrap(); + + #[derive(Default)] + struct RunCounter { + component: usize, + effect: usize, + } + + let counter = Rc::new(RefCell::new(RunCounter::default())); + let mut dom = VirtualDom::new_with_props( + |cx| { + let counter = cx.props; + counter.borrow_mut().component += 1; + + let mut signal = use_signal(cx, || 0); + cx.use_hook(move || { + to_owned![counter]; + Effect::new(move || { + counter.borrow_mut().effect += 1; + println!("Signal: {:?}", signal); + }) + }); + signal += 1; + + render! { + div {} + } + }, + counter.clone(), + ); + + let _ = dom.rebuild().santize(); + + let current_counter = counter.borrow(); + assert_eq!(current_counter.component, 1); + assert_eq!(current_counter.effect, 2); +} diff --git a/packages/signals/tests/subscribe.rs b/packages/signals/tests/subscribe.rs new file mode 100644 index 000000000..5c1a99347 --- /dev/null +++ b/packages/signals/tests/subscribe.rs @@ -0,0 +1,92 @@ +#![allow(unused, non_upper_case_globals, non_snake_case)] +use std::collections::HashMap; +use std::rc::Rc; + +use dioxus::prelude::*; +use dioxus_core::ElementId; +use dioxus_signals::*; + +#[test] +fn reading_subscribes() { + simple_logger::SimpleLogger::new().init().unwrap(); + + #[derive(Default)] + struct RunCounter { + parent: usize, + children: HashMap, + } + + let counter = Rc::new(RefCell::new(RunCounter::default())); + let mut dom = VirtualDom::new_with_props( + |cx| { + let mut signal = use_signal(cx, || 0); + + println!("Parent: {:?}", cx.scope_id()); + if cx.generation() == 1 { + signal += 1; + } + + cx.props.borrow_mut().parent += 1; + + render! { + for id in 0..10 { + Child { + signal: signal, + counter: cx.props.clone() + } + } + } + }, + counter.clone(), + ); + + #[derive(Props, Clone)] + struct ChildProps { + signal: Signal, + counter: Rc>, + } + + impl PartialEq for ChildProps { + fn eq(&self, other: &Self) -> bool { + self.signal == other.signal + } + } + + fn Child(cx: Scope) -> Element { + println!("Child: {:?}", cx.scope_id()); + *cx.props + .counter + .borrow_mut() + .children + .entry(cx.scope_id()) + .or_default() += 1; + + render! { + "{cx.props.signal}" + } + } + + let _ = dom.rebuild().santize(); + + { + let current_counter = counter.borrow(); + assert_eq!(current_counter.parent, 1); + + for (scope_id, rerun_count) in current_counter.children.iter() { + assert_eq!(rerun_count, &1); + } + } + + dom.mark_dirty(ScopeId(0)); + dom.render_immediate(); + dom.render_immediate(); + + { + let current_counter = counter.borrow(); + assert_eq!(current_counter.parent, 2); + + for (scope_id, rerun_count) in current_counter.children.iter() { + assert_eq!(rerun_count, &2); + } + } +} From 7f2049b6479835cb9354d7d455426a63f6fbbd80 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 12:32:46 -0700 Subject: [PATCH 18/39] add memo --- packages/copy/src/lib.rs | 17 ++++++++++++ packages/signals/src/effect.rs | 11 +++++++- packages/signals/src/lib.rs | 12 ++++++-- packages/signals/src/memo.rs | 42 ++++++++++++++++++++++++++++ packages/signals/src/rt.rs | 9 ++++++ packages/signals/tests/memo.rs | 50 ++++++++++++++++++++++++++++++++++ 6 files changed, 137 insertions(+), 4 deletions(-) create mode 100644 packages/signals/src/memo.rs create mode 100644 packages/signals/tests/memo.rs diff --git a/packages/copy/src/lib.rs b/packages/copy/src/lib.rs index 149c14434..b9b8aec06 100644 --- a/packages/copy/src/lib.rs +++ b/packages/copy/src/lib.rs @@ -209,6 +209,12 @@ impl CopyHandle { self.try_write().unwrap() } + pub fn set(&self, value: T) { + self.validate().then(|| { + *self.raw.data.borrow_mut() = Some(Box::new(value)); + }); + } + pub fn ptr_eq(&self, other: &Self) -> bool { #[cfg(any(debug_assertions, feature = "check_generation"))] { @@ -316,6 +322,17 @@ impl Owner { self.owned.borrow_mut().push(location); key } + + /// Creates an invalid handle. This is useful for creating a handle that will be filled in later. If you use this before the value is filled in, you will get may get a panic or an out of date value. + pub fn invalid(&self) -> CopyHandle { + let location = self.store.claim(); + CopyHandle { + raw: location, + #[cfg(any(debug_assertions, feature = "check_generation"))] + generation: location.generation.get(), + _marker: PhantomData, + } + } } impl Drop for Owner { diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs index 9bc9b33f2..06b02ffd4 100644 --- a/packages/signals/src/effect.rs +++ b/packages/signals/src/effect.rs @@ -1,3 +1,6 @@ +use core::{self, fmt::Debug}; +use std::fmt::{self, Formatter}; + use dioxus_core::prelude::*; use crate::CopyValue; @@ -19,7 +22,13 @@ pub(crate) fn get_effect_stack() -> EffectStack { #[derive(Copy, Clone, PartialEq)] pub struct Effect { - callback: CopyValue>, + pub(crate) callback: CopyValue>, +} + +impl Debug for Effect { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_fmt(format_args!("{:?}", self.callback.value)) + } } impl Effect { diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index c0d081f7d..8319b4b8e 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -8,8 +8,9 @@ mod rt; pub use rt::*; mod effect; pub use effect::*; -#[macro_use] mod impls; +mod memo; +pub use memo::*; use dioxus_core::{ prelude::{current_scope_id, has_context, provide_context, schedule_update_any}, @@ -55,7 +56,7 @@ struct SignalData { } pub struct Signal { - inner: CopyValue>, + pub(crate) inner: CopyValue>, } impl Signal { @@ -115,6 +116,11 @@ impl Signal { let subscribers = { std::mem::take(&mut *self.inner.read().effect_subscribers.borrow_mut()) }; for effect in subscribers { + log::trace!( + "Write on {:?} triggered effect {:?}", + self.inner.value, + effect + ); effect.try_run(); } @@ -122,7 +128,7 @@ impl Signal { RefMut::map(inner, |v| &mut v.value) } - pub fn set(&mut self, value: T) { + pub fn set(&self, value: T) { *self.write() = value; } diff --git a/packages/signals/src/memo.rs b/packages/signals/src/memo.rs new file mode 100644 index 000000000..362f9cbd3 --- /dev/null +++ b/packages/signals/src/memo.rs @@ -0,0 +1,42 @@ +use dioxus_core::prelude::*; + +use crate::{get_effect_stack, CopyValue, Effect, Signal, SignalData}; + +pub fn use_memo(cx: &ScopeState, f: impl FnMut() -> R + 'static) -> Signal { + *cx.use_hook(|| memo(f)) +} + +pub fn memo(mut f: impl FnMut() -> R + 'static) -> Signal { + let state = Signal:: { + inner: CopyValue::invalid(), + }; + let effect = Effect { + callback: CopyValue::invalid(), + }; + + { + get_effect_stack().effects.write().push(effect); + } + state.inner.value.set(SignalData { + subscribers: Default::default(), + effect_subscribers: Default::default(), + update_any: schedule_update_any().expect("in a virtual dom"), + value: f(), + }); + { + get_effect_stack().effects.write().pop(); + } + + effect.callback.value.set(Box::new(move || { + let value = f(); + let changed = { + let state = state.read(); + value != *state + }; + if changed { + state.set(value) + } + })); + + state +} diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index b37a46a53..db394af5e 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -64,6 +64,15 @@ impl CopyValue { } } + pub(crate) fn invalid() -> Self { + let owner = current_owner(); + + Self { + value: owner.invalid(), + origin_scope: current_scope_id().expect("in a virtual dom"), + } + } + pub fn origin_scope(&self) -> ScopeId { self.origin_scope } diff --git a/packages/signals/tests/memo.rs b/packages/signals/tests/memo.rs new file mode 100644 index 000000000..b0f91ee73 --- /dev/null +++ b/packages/signals/tests/memo.rs @@ -0,0 +1,50 @@ +#![allow(unused, non_upper_case_globals, non_snake_case)] +use std::collections::HashMap; +use std::rc::Rc; + +use dioxus::prelude::*; +use dioxus_core::ElementId; +use dioxus_signals::*; + +#[test] +fn memos_rerun() { + simple_logger::SimpleLogger::new().init().unwrap(); + + #[derive(Default)] + struct RunCounter { + component: usize, + effect: usize, + } + + let counter = Rc::new(RefCell::new(RunCounter::default())); + let mut dom = VirtualDom::new_with_props( + |cx| { + let counter = cx.props; + counter.borrow_mut().component += 1; + + let mut signal = use_signal(cx, || 0); + let memo = cx.use_hook(move || { + to_owned![counter]; + memo(move || { + counter.borrow_mut().effect += 1; + println!("Signal: {:?}", signal); + signal.value() + }) + }); + assert_eq!(memo.value(), 0); + signal += 1; + assert_eq!(memo.value(), 1); + + render! { + div {} + } + }, + counter.clone(), + ); + + let _ = dom.rebuild().santize(); + + let current_counter = counter.borrow(); + assert_eq!(current_counter.component, 1); + assert_eq!(current_counter.effect, 2); +} From 190c65b15d0604d25cffef93e56812ed5f742ac1 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 14:31:03 -0700 Subject: [PATCH 19/39] fix memo and add tests --- examples/signals.rs | 2 +- packages/signals/src/impls.rs | 34 ++++++++---- packages/signals/src/lib.rs | 88 +++++++++++++++++++++++++----- packages/signals/src/memo.rs | 4 +- packages/signals/tests/memo.rs | 97 +++++++++++++++++++++++++++++++++- 5 files changed, 198 insertions(+), 27 deletions(-) diff --git a/examples/signals.rs b/examples/signals.rs index 725577206..bc627fa8f 100644 --- a/examples/signals.rs +++ b/examples/signals.rs @@ -20,7 +20,7 @@ fn app(cx: Scope) -> Element { button { onclick: move |_| count += 1, "Up high!" } button { onclick: move |_| count -= 1, "Down low!" } - if count() > 5 { + if count.value() > 5 { rsx!{ h2 { "High five!" } } } }) diff --git a/packages/signals/src/impls.rs b/packages/signals/src/impls.rs index 8a3c9db8c..0ce739640 100644 --- a/packages/signals/src/impls.rs +++ b/packages/signals/src/impls.rs @@ -1,5 +1,5 @@ use crate::rt::CopyValue; -use crate::Signal; +use crate::{Signal, Write}; use std::cell::{Ref, RefMut}; @@ -104,10 +104,6 @@ macro_rules! impls { pub fn get(&self, index: usize) -> Option> { Ref::filter_map(self.read(), |v| v.get(index)).ok() } - - pub fn get_mut(&self, index: usize) -> Option> { - RefMut::filter_map(self.write(), |v| v.get_mut(index)).ok() - } } impl $ty> { @@ -130,10 +126,6 @@ macro_rules! impls { Ref::filter_map(self.read(), |v| v.as_ref()).ok() } - pub fn as_mut(&self) -> Option> { - RefMut::filter_map(self.write(), |v| v.as_mut()).ok() - } - pub fn get_or_insert(&self, default: T) -> Ref<'_, T> { self.get_or_insert_with(|| default) } @@ -183,6 +175,18 @@ impl IntoIterator for CopyValue> { } } +impl CopyValue> { + pub fn get_mut(&self, index: usize) -> Option> { + RefMut::filter_map(self.write(), |v| v.get_mut(index)).ok() + } +} + +impl CopyValue> { + pub fn as_mut(&self) -> Option> { + RefMut::filter_map(self.write(), |v| v.as_mut()).ok() + } +} + pub struct CopySignalIterator { index: usize, value: Signal>, @@ -210,3 +214,15 @@ impl IntoIterator for Signal> { } } } + +impl Signal> { + pub fn get_mut(&self, index: usize) -> Option>> { + Write::filter_map(self.write(), |v| v.get_mut(index)) + } +} + +impl Signal> { + pub fn as_mut(&self) -> Option>> { + Write::filter_map(self.write(), |v| v.as_mut()) + } +} diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index 8319b4b8e..179e0bef8 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -1,5 +1,6 @@ use std::{ cell::{Ref, RefCell, RefMut}, + ops::{Deref, DerefMut}, rc::Rc, sync::Arc, }; @@ -52,7 +53,7 @@ struct SignalData { subscribers: Rc>>, effect_subscribers: Rc>>, update_any: Arc, - value: T, + pub(crate) value: T, } pub struct Signal { @@ -77,7 +78,12 @@ impl Signal { pub fn read(&self) -> Ref { let inner = self.inner.read(); - if let Some(current_scope_id) = current_scope_id() { + if let Some(effect) = Effect::current() { + let mut effect_subscribers = inner.effect_subscribers.borrow_mut(); + if !effect_subscribers.contains(&effect) { + effect_subscribers.push(effect); + } + } else if let Some(current_scope_id) = current_scope_id() { log::trace!( "{:?} subscribed to {:?}", self.inner.value, @@ -91,16 +97,19 @@ impl Signal { inner.subscribers.borrow_mut().push(unsubscriber.scope); } } - if let Some(effect) = Effect::current() { - let mut effect_subscribers = inner.effect_subscribers.borrow_mut(); - if !effect_subscribers.contains(&effect) { - effect_subscribers.push(effect); - } - } Ref::map(inner, |v| &v.value) } - pub fn write(&self) -> RefMut { + pub fn write(&self) -> Write<'_, T> { + let inner = self.inner.write(); + let borrow = RefMut::map(inner, |v| &mut v.value); + Write { + write: borrow, + signal: SignalSubscriberDrop { signal: *self }, + } + } + + fn update_subscribers(&self) { { let inner = self.inner.read(); for &scope_id in &*inner.subscribers.borrow() { @@ -113,8 +122,11 @@ impl Signal { } } - let subscribers = - { std::mem::take(&mut *self.inner.read().effect_subscribers.borrow_mut()) }; + let subscribers = { + let self_read = self.inner.read(); + let mut effects = self_read.effect_subscribers.borrow_mut(); + std::mem::take(&mut *effects) + }; for effect in subscribers { log::trace!( "Write on {:?} triggered effect {:?}", @@ -123,9 +135,6 @@ impl Signal { ); effect.try_run(); } - - let inner = self.inner.write(); - RefMut::map(inner, |v| &mut v.value) } pub fn set(&self, value: T) { @@ -154,3 +163,54 @@ impl PartialEq for Signal { self.inner == other.inner } } + +struct SignalSubscriberDrop { + signal: Signal, +} + +impl Drop for SignalSubscriberDrop { + fn drop(&mut self) { + self.signal.update_subscribers(); + } +} + +pub struct Write<'a, T: 'static, I: 'static = T> { + write: RefMut<'a, T>, + signal: SignalSubscriberDrop, +} + +impl<'a, T: 'static, I: 'static> Write<'a, T, I> { + pub fn map(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<'a, O, I> { + let Self { write, signal } = myself; + Write { + write: RefMut::map(write, f), + signal, + } + } + + pub fn filter_map( + myself: Self, + f: impl FnOnce(&mut T) -> Option<&mut O>, + ) -> Option> { + let Self { write, signal } = myself; + let write = RefMut::filter_map(write, f).ok(); + write.map(|write| Write { + write, + signal: signal, + }) + } +} + +impl<'a, T: 'static> Deref for Write<'a, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + &*self.write + } +} + +impl DerefMut for Write<'_, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut *self.write + } +} diff --git a/packages/signals/src/memo.rs b/packages/signals/src/memo.rs index 362f9cbd3..07d18f5a6 100644 --- a/packages/signals/src/memo.rs +++ b/packages/signals/src/memo.rs @@ -30,8 +30,8 @@ pub fn memo(mut f: impl FnMut() -> R + 'static) -> Signal { effect.callback.value.set(Box::new(move || { let value = f(); let changed = { - let state = state.read(); - value != *state + let old = state.inner.read(); + value != old.value }; if changed { state.set(value) diff --git a/packages/signals/tests/memo.rs b/packages/signals/tests/memo.rs index b0f91ee73..b27d7d546 100644 --- a/packages/signals/tests/memo.rs +++ b/packages/signals/tests/memo.rs @@ -2,13 +2,14 @@ use std::collections::HashMap; use std::rc::Rc; +use dioxus::html::p; use dioxus::prelude::*; use dioxus_core::ElementId; use dioxus_signals::*; #[test] fn memos_rerun() { - simple_logger::SimpleLogger::new().init().unwrap(); + let _ = simple_logger::SimpleLogger::new().init(); #[derive(Default)] struct RunCounter { @@ -48,3 +49,97 @@ fn memos_rerun() { assert_eq!(current_counter.component, 1); assert_eq!(current_counter.effect, 2); } + +#[test] +fn memos_prevents_component_rerun() { + let _ = simple_logger::SimpleLogger::new().init(); + + #[derive(Default)] + struct RunCounter { + component: usize, + effect: usize, + } + + let counter = Rc::new(RefCell::new(RunCounter::default())); + let mut dom = VirtualDom::new_with_props( + |cx| { + let mut signal = use_signal(cx, || 0); + + if cx.generation() == 1 { + *signal.write() = 0; + } + if cx.generation() == 2 { + println!("Writing to signal"); + *signal.write() = 1; + } + + render! { + Child { + signal: signal, + counter: cx.props.clone(), + } + } + }, + counter.clone(), + ); + + #[derive(Default, Props)] + struct ChildProps { + signal: Signal, + counter: Rc>, + } + + impl PartialEq for ChildProps { + fn eq(&self, other: &Self) -> bool { + self.signal == other.signal + } + } + + fn Child(cx: Scope) -> Element { + let counter = &cx.props.counter; + let signal = cx.props.signal; + counter.borrow_mut().component += 1; + + let memo = cx.use_hook(move || { + to_owned![counter]; + memo(move || { + counter.borrow_mut().effect += 1; + println!("Signal: {:?}", signal); + signal.value() + }) + }); + match cx.generation() { + 0 => { + assert_eq!(memo.value(), 0); + } + 1 => { + assert_eq!(memo.value(), 1); + } + _ => panic!("Unexpected generation"), + } + + render! { + div {} + } + } + + let _ = dom.rebuild().santize(); + dom.mark_dirty(ScopeId(0)); + dom.render_immediate(); + + { + let current_counter = counter.borrow(); + assert_eq!(current_counter.component, 1); + assert_eq!(current_counter.effect, 2); + } + + dom.mark_dirty(ScopeId(0)); + dom.render_immediate(); + dom.render_immediate(); + + { + let current_counter = counter.borrow(); + assert_eq!(current_counter.component, 2); + assert_eq!(current_counter.effect, 3); + } +} From 84734c4146fa71003e1949c22bd15cdce61337b1 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 14:34:16 -0700 Subject: [PATCH 20/39] change dioxus signal to generational box --- Cargo.toml | 4 ++-- .../{copy => generational_box}/Cargo.toml | 2 +- .../{copy => generational_box}/src/lib.rs | 24 +++++++++---------- packages/signals/Cargo.toml | 2 +- packages/signals/src/rt.rs | 4 ++-- 5 files changed, 18 insertions(+), 18 deletions(-) rename packages/{copy => generational_box}/Cargo.toml (92%) rename packages/{copy => generational_box}/src/lib.rs (93%) diff --git a/Cargo.toml b/Cargo.toml index a544335f8..b01396a26 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,7 @@ members = [ "packages/native-core", "packages/native-core-macro", "packages/rsx-rosetta", - "packages/copy", + "packages/generational_box", "packages/signals", "packages/hot-reload", "packages/fullstack", @@ -77,7 +77,7 @@ dioxus-native-core = { path = "packages/native-core", version = "0.4.0" } dioxus-native-core-macro = { path = "packages/native-core-macro", version = "0.4.0" } rsx-rosetta = { path = "packages/rsx-rosetta", version = "0.4.0" } dioxus-signals = { path = "packages/signals" } -dioxus-copy = { path = "packages/copy" } +generational-box = { path = "packages/generational_box" } dioxus-hot-reload = { path = "packages/hot-reload", version = "0.4.0" } dioxus-fullstack = { path = "packages/fullstack", version = "0.4.1" } dioxus_server_macro = { path = "packages/server-macro", version = "0.4.1" } diff --git a/packages/copy/Cargo.toml b/packages/generational_box/Cargo.toml similarity index 92% rename from packages/copy/Cargo.toml rename to packages/generational_box/Cargo.toml index 56964badd..6c5a5a841 100644 --- a/packages/copy/Cargo.toml +++ b/packages/generational_box/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "dioxus-copy" +name = "generational-box" authors = ["Evan Almloff"] version = "0.0.0" edition = "2018" diff --git a/packages/copy/src/lib.rs b/packages/generational_box/src/lib.rs similarity index 93% rename from packages/copy/src/lib.rs rename to packages/generational_box/src/lib.rs index b9b8aec06..d45701e6c 100644 --- a/packages/copy/src/lib.rs +++ b/packages/generational_box/src/lib.rs @@ -106,8 +106,8 @@ fn panics() { fn fuzz() { fn maybe_owner_scope( store: &Store, - valid_keys: &mut Vec>, - invalid_keys: &mut Vec>, + valid_keys: &mut Vec>, + invalid_keys: &mut Vec>, path: &mut Vec, ) { let branch_cutoff = 5; @@ -145,14 +145,14 @@ fn fuzz() { } } -pub struct CopyHandle { +pub struct GenerationalBox { raw: MemoryLocation, #[cfg(any(debug_assertions, feature = "check_generation"))] generation: u32, _marker: PhantomData, } -impl Debug for CopyHandle { +impl Debug for GenerationalBox { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { #[cfg(any(debug_assertions, feature = "check_generation"))] f.write_fmt(format_args!( @@ -166,7 +166,7 @@ impl Debug for CopyHandle { } } -impl CopyHandle { +impl GenerationalBox { #[inline(always)] fn validate(&self) -> bool { #[cfg(any(debug_assertions, feature = "check_generation"))] @@ -227,9 +227,9 @@ impl CopyHandle { } } -impl Copy for CopyHandle {} +impl Copy for GenerationalBox {} -impl Clone for CopyHandle { +impl Clone for GenerationalBox { fn clone(&self) -> Self { *self } @@ -253,13 +253,13 @@ impl MemoryLocation { } } - fn replace(&mut self, value: T) -> CopyHandle { + fn replace(&mut self, value: T) -> GenerationalBox { let mut inner_mut = self.data.borrow_mut(); let raw = Box::new(value); let old = inner_mut.replace(raw); assert!(old.is_none()); - CopyHandle { + GenerationalBox { raw: *self, #[cfg(any(debug_assertions, feature = "check_generation"))] generation: self.generation.get(), @@ -316,7 +316,7 @@ pub struct Owner { } impl Owner { - pub fn insert(&self, value: T) -> CopyHandle { + pub fn insert(&self, value: T) -> GenerationalBox { let mut location = self.store.claim(); let key = location.replace(value); self.owned.borrow_mut().push(location); @@ -324,9 +324,9 @@ impl Owner { } /// Creates an invalid handle. This is useful for creating a handle that will be filled in later. If you use this before the value is filled in, you will get may get a panic or an out of date value. - pub fn invalid(&self) -> CopyHandle { + pub fn invalid(&self) -> GenerationalBox { let location = self.store.claim(); - CopyHandle { + GenerationalBox { raw: location, #[cfg(any(debug_assertions, feature = "check_generation"))] generation: location.generation.get(), diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index 19f2039cc..c145b850a 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -8,7 +8,7 @@ edition = "2018" [dependencies] dioxus-core = { workspace = true } -dioxus-copy = { workspace = true } +generational-box = { workspace = true } log.workspace = true simple_logger = "4.2.0" diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index db394af5e..f96ff6ab3 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -8,7 +8,7 @@ use dioxus_core::prelude::{ }; use dioxus_core::ScopeId; -use dioxus_copy::{CopyHandle, Owner, Store}; +use generational_box::{GenerationalBox, Owner, Store}; fn current_store() -> Store { match consume_context() { @@ -41,7 +41,7 @@ fn owner_in_scope(scope: ScopeId) -> Rc { } pub struct CopyValue { - pub(crate) value: CopyHandle, + pub(crate) value: GenerationalBox, origin_scope: ScopeId, } From ddbe913e799ff80ef6be0444c408ee6a1af6682f Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 14:50:36 -0700 Subject: [PATCH 21/39] make signals non-breaking --- packages/core/src/arena.rs | 8 +++++++- packages/core/src/events.rs | 11 ++++++++--- packages/core/src/nodes.rs | 6 ++++-- packages/core/src/scopes.rs | 29 +++++++++++++++++++---------- packages/core/src/virtual_dom.rs | 12 ++++++------ 5 files changed, 44 insertions(+), 22 deletions(-) diff --git a/packages/core/src/arena.rs b/packages/core/src/arena.rs index b7ec46623..c8f7ce3c9 100644 --- a/packages/core/src/arena.rs +++ b/packages/core/src/arena.rs @@ -19,6 +19,9 @@ pub(crate) struct ElementRef { // The actual template pub template: Option>>, + + // 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(0), } } } @@ -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(0)); 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) } @@ -163,7 +169,7 @@ impl VirtualDom { let listener = unsafe { &*listener }; match &listener.value { AttributeValue::Listener(l) => { - _ = l.callback.take(); + _ = l.take(); } AttributeValue::Any(a) => { _ = a.take(); diff --git a/packages/core/src/events.rs b/packages/core/src/events.rs index c734ebd4a..90511a8e6 100644 --- a/packages/core/src/events.rs +++ b/packages/core/src/events.rs @@ -1,9 +1,8 @@ +use crate::{runtime::with_runtime, ScopeId}; use std::{ cell::{Cell, RefCell}, rc::Rc, - }; -use crate::ScopeId; /// A wrapper around some generic data that handles the event's state /// @@ -136,7 +135,7 @@ impl std::fmt::Debug for Event { /// } /// /// ``` -pub struct EventHandler<'bump, T:?Sized = ()> { +pub struct EventHandler<'bump, T: ?Sized = ()> { pub(crate) origin: ScopeId, pub(super) callback: RefCell>>, } @@ -158,7 +157,13 @@ impl 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(); + }); } } diff --git a/packages/core/src/nodes.rs b/packages/core/src/nodes.rs index 5406e8f07..a108f3577 100644 --- a/packages/core/src/nodes.rs +++ b/packages/core/src/nodes.rs @@ -1,4 +1,4 @@ -use crate::prelude::EventHandler;use crate::{ +use crate::{ any_props::AnyProps, arena::ElementId, Element, Event, LazyNodes, ScopeId, ScopeState, }; use bumpalo::boxed::Box as BumpBox; @@ -476,7 +476,7 @@ pub enum AttributeValue<'a> { Bool(bool), /// A listener, like "onclick" - Listener(EventHandler<'a, Event>), + Listener(RefCell>>), /// An arbitrary value that implements PartialEq and is static Any(RefCell>>), @@ -485,6 +485,8 @@ pub enum AttributeValue<'a> { None, } +pub type ListenerCb<'a> = BumpBox<'a, dyn FnMut(Event) + 'a>; + /// Any of the built-in values that the Dioxus VirtualDom supports as dynamic attributes on elements that are borrowed /// /// These varients are used to communicate what the value of an attribute is that needs to be updated diff --git a/packages/core/src/scopes.rs b/packages/core/src/scopes.rs index b43b2143a..f255c4175 100644 --- a/packages/core/src/scopes.rs +++ b/packages/core/src/scopes.rs @@ -446,7 +446,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, origin: self.context().id } + EventHandler { + callback, + origin: self.context().id, + } } /// Create a new [`AttributeValue`] with the listener variant from a callback @@ -456,16 +459,22 @@ impl<'src> ScopeState { &'src self, mut callback: impl FnMut(Event) + 'src, ) -> AttributeValue<'src> { - + // safety: there's no other way to create a dynamicly-dispatched bump box other than alloc + from-raw + // This is the suggested way to build a bumpbox + // + // In theory, we could just use regular boxes + let boxed: BumpBox<'src, dyn FnMut(_) + 'src> = unsafe { + BumpBox::from_raw(self.bump().alloc(move |event: Event| { + if let Ok(data) = event.data.downcast::() { + callback(Event { + propagates: event.propagates, + data, + }); + } + })) + }; - AttributeValue::Listener(self.event_handler(move |event: Event| { - if let Ok(data) = event.data.downcast::() { - callback(Event { - propagates: event.propagates, - data, - }); - } - })) + AttributeValue::Listener(RefCell::new(Some(boxed))) } /// Create a new [`AttributeValue`] with a value that implements [`AnyValue`] diff --git a/packages/core/src/virtual_dom.rs b/packages/core/src/virtual_dom.rs index c43af2254..f20b80412 100644 --- a/packages/core/src/virtual_dom.rs +++ b/packages/core/src/virtual_dom.rs @@ -391,12 +391,12 @@ 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 = listener.origin; - self.runtime.scope_stack.borrow_mut().push(origin); - if let Some(cb) = listener.callback.borrow_mut().as_deref_mut() { + let origin = el_ref.scope; + self.runtime.scope_stack.borrow_mut().push(origin); + if let Some(cb) = listener.borrow_mut().as_deref_mut() { cb(uievent.clone()); } - self.runtime.scope_stack.borrow_mut().pop(); + self.runtime.scope_stack.borrow_mut().pop(); if !uievent.propagates.get() { return; @@ -425,9 +425,9 @@ 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 = listener.origin; + let origin = el_ref.scope; self.runtime.scope_stack.borrow_mut().push(origin); - if let Some(cb) = listener.callback.borrow_mut().as_deref_mut() { + if let Some(cb) = listener.borrow_mut().as_deref_mut() { cb(uievent.clone()); } self.runtime.scope_stack.borrow_mut().pop(); From 6ca170453b6e20350787ffd6e2d4fbdea14b0433 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 14:59:58 -0700 Subject: [PATCH 22/39] handle virtual dom switching --- packages/core/src/runtime.rs | 15 +++++++++++++++ packages/core/src/scheduler/wait.rs | 3 ++- packages/core/src/virtual_dom.rs | 19 ++++++++++--------- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs index 1ca778edd..89de770c5 100644 --- a/packages/core/src/runtime.rs +++ b/packages/core/src/runtime.rs @@ -89,3 +89,18 @@ impl Runtime { .ok() } } + +pub struct RuntimeGuard(Rc); + +impl RuntimeGuard { + pub fn new(runtime: Rc) -> Self { + push_runtime(runtime.clone()); + Self(runtime) + } +} + +impl Drop for RuntimeGuard { + fn drop(&mut self) { + pop_runtime(); + } +} diff --git a/packages/core/src/scheduler/wait.rs b/packages/core/src/scheduler/wait.rs index 47180c240..62fa10180 100644 --- a/packages/core/src/scheduler/wait.rs +++ b/packages/core/src/scheduler/wait.rs @@ -1,4 +1,4 @@ -use crate::{TaskId, VirtualDom}; +use crate::{runtime::RuntimeGuard, TaskId, VirtualDom}; use std::task::Context; impl VirtualDom { @@ -7,6 +7,7 @@ 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 _runtime = RuntimeGuard::new(self.runtime.clone()); let mut tasks = self.runtime.scheduler.tasks.borrow_mut(); let task = match tasks.get(id.0) { diff --git a/packages/core/src/virtual_dom.rs b/packages/core/src/virtual_dom.rs index f20b80412..0a4577f4c 100644 --- a/packages/core/src/virtual_dom.rs +++ b/packages/core/src/virtual_dom.rs @@ -9,7 +9,7 @@ use crate::{ mutations::Mutation, nodes::RenderReturn, nodes::{Template, TemplateId}, - runtime::{pop_runtime, push_runtime, Runtime}, + runtime::{Runtime, RuntimeGuard}, scopes::{ScopeId, ScopeState}, AttributeValue, Element, Event, Scope, }; @@ -275,9 +275,6 @@ impl VirtualDom { // the root element is always given element ID 0 since it's the container for the entire tree dom.elements.insert(ElementRef::none()); - // Set this as the current runtime - push_runtime(dom.runtime.clone()); - dom } @@ -329,6 +326,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 @@ -543,6 +542,7 @@ impl VirtualDom { /// apply_edits(edits); /// ``` pub fn rebuild(&mut self) -> Mutations { + let _runtime = RuntimeGuard::new(self.runtime.clone()); match unsafe { self.run_scope(ScopeId(0)).extend_lifetime_ref() } { // Rebuilding implies we append the created elements to the root RenderReturn::Ready(node) => { @@ -621,9 +621,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 @@ -657,7 +660,5 @@ impl Drop for VirtualDom { fn drop(&mut self) { // Simply drop this scope which drops all of its children self.drop_scope(ScopeId(0), true); - // remove the current runtime - pop_runtime(); } } From 646c161c7d98ea62f46da5135fa838734d0646bf Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 16:04:49 -0700 Subject: [PATCH 23/39] create read only signal --- Cargo.toml | 4 +- .../Cargo.toml | 0 .../src/lib.rs | 0 packages/signals/src/impls.rs | 51 ++-- packages/signals/src/lib.rs | 211 +-------------- packages/signals/src/memo.rs | 13 +- packages/signals/src/signal.rs | 244 ++++++++++++++++++ 7 files changed, 287 insertions(+), 236 deletions(-) rename packages/{generational_box => generational-box}/Cargo.toml (100%) rename packages/{generational_box => generational-box}/src/lib.rs (100%) create mode 100644 packages/signals/src/signal.rs diff --git a/Cargo.toml b/Cargo.toml index b01396a26..7bb7d1570 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,7 @@ members = [ "packages/native-core", "packages/native-core-macro", "packages/rsx-rosetta", - "packages/generational_box", + "packages/generational-box", "packages/signals", "packages/hot-reload", "packages/fullstack", @@ -77,7 +77,7 @@ dioxus-native-core = { path = "packages/native-core", version = "0.4.0" } dioxus-native-core-macro = { path = "packages/native-core-macro", version = "0.4.0" } rsx-rosetta = { path = "packages/rsx-rosetta", version = "0.4.0" } dioxus-signals = { path = "packages/signals" } -generational-box = { path = "packages/generational_box" } +generational-box = { path = "packages/generational-box" } dioxus-hot-reload = { path = "packages/hot-reload", version = "0.4.0" } dioxus-fullstack = { path = "packages/fullstack", version = "0.4.1" } dioxus_server_macro = { path = "packages/server-macro", version = "0.4.1" } diff --git a/packages/generational_box/Cargo.toml b/packages/generational-box/Cargo.toml similarity index 100% rename from packages/generational_box/Cargo.toml rename to packages/generational-box/Cargo.toml diff --git a/packages/generational_box/src/lib.rs b/packages/generational-box/src/lib.rs similarity index 100% rename from packages/generational_box/src/lib.rs rename to packages/generational-box/src/lib.rs diff --git a/packages/signals/src/impls.rs b/packages/signals/src/impls.rs index 0ce739640..0328d4063 100644 --- a/packages/signals/src/impls.rs +++ b/packages/signals/src/impls.rs @@ -1,5 +1,5 @@ use crate::rt::CopyValue; -use crate::{Signal, Write}; +use crate::signal::{ReadOnlySignal, Signal, Write}; use std::cell::{Ref, RefMut}; @@ -8,11 +8,11 @@ use std::{ ops::{Add, Div, Mul, Sub}, }; -macro_rules! impls { +macro_rules! read_impls { ($ty:ident) => { impl Default for $ty { fn default() -> Self { - Self::new(T::default()) + Self::new(Default::default()) } } @@ -36,6 +36,29 @@ macro_rules! impls { } } + impl $ty> { + pub fn get(&self, index: usize) -> Option> { + Ref::filter_map(self.read(), |v| v.get(index)).ok() + } + } + + impl $ty> { + pub fn unwrap(&self) -> T + where + T: Clone, + { + self.with(|v| v.clone()).unwrap() + } + + pub fn as_ref(&self) -> Option> { + Ref::filter_map(self.read(), |v| v.as_ref()).ok() + } + } + }; +} + +macro_rules! write_impls { + ($ty:ident) => { impl + Copy + 'static> std::ops::AddAssign for $ty { fn add_assign(&mut self, rhs: T) { self.with_mut(|v| *v = *v + rhs) @@ -100,10 +123,6 @@ macro_rules! impls { pub fn split_off(&self, at: usize) -> Vec { self.with_mut(|v| v.split_off(at)) } - - pub fn get(&self, index: usize) -> Option> { - Ref::filter_map(self.read(), |v| v.get(index)).ok() - } } impl $ty> { @@ -115,17 +134,6 @@ macro_rules! impls { self.with_mut(|v| v.replace(value)) } - pub fn unwrap(&self) -> T - where - T: Clone, - { - self.with(|v| v.clone()).unwrap() - } - - pub fn as_ref(&self) -> Option> { - Ref::filter_map(self.read(), |v| v.as_ref()).ok() - } - pub fn get_or_insert(&self, default: T) -> Ref<'_, T> { self.get_or_insert_with(|| default) } @@ -144,8 +152,11 @@ macro_rules! impls { }; } -impls!(CopyValue); -impls!(Signal); +read_impls!(CopyValue); +write_impls!(CopyValue); +read_impls!(Signal); +write_impls!(Signal); +read_impls!(ReadOnlySignal); pub struct CopyValueIterator { index: usize, diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index 179e0bef8..66b7801f0 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -1,10 +1,3 @@ -use std::{ - cell::{Ref, RefCell, RefMut}, - ops::{Deref, DerefMut}, - rc::Rc, - sync::Arc, -}; - mod rt; pub use rt::*; mod effect; @@ -12,205 +5,5 @@ pub use effect::*; mod impls; mod memo; pub use memo::*; - -use dioxus_core::{ - prelude::{current_scope_id, has_context, provide_context, schedule_update_any}, - ScopeId, ScopeState, -}; - -pub fn use_signal(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal { - *cx.use_hook(|| Signal::new(f())) -} - -#[derive(Clone)] -struct Unsubscriber { - scope: ScopeId, - subscribers: Rc>>>>>, -} - -impl Drop for Unsubscriber { - fn drop(&mut self) { - for subscribers in self.subscribers.borrow().iter() { - subscribers.borrow_mut().retain(|s| *s != self.scope); - } - } -} - -fn current_unsubscriber() -> Unsubscriber { - match has_context() { - Some(rt) => rt, - None => { - let owner = Unsubscriber { - scope: current_scope_id().expect("in a virtual dom"), - subscribers: Default::default(), - }; - provide_context(owner).expect("in a virtual dom") - } - } -} - -struct SignalData { - subscribers: Rc>>, - effect_subscribers: Rc>>, - update_any: Arc, - pub(crate) value: T, -} - -pub struct Signal { - pub(crate) inner: CopyValue>, -} - -impl Signal { - pub fn new(value: T) -> Self { - Self { - inner: CopyValue::new(SignalData { - subscribers: Default::default(), - effect_subscribers: Default::default(), - update_any: schedule_update_any().expect("in a virtual dom"), - value, - }), - } - } - - pub fn origin_scope(&self) -> ScopeId { - self.inner.origin_scope() - } - - pub fn read(&self) -> Ref { - let inner = self.inner.read(); - if let Some(effect) = Effect::current() { - let mut effect_subscribers = inner.effect_subscribers.borrow_mut(); - if !effect_subscribers.contains(&effect) { - effect_subscribers.push(effect); - } - } else if let Some(current_scope_id) = current_scope_id() { - log::trace!( - "{:?} subscribed to {:?}", - self.inner.value, - current_scope_id - ); - let mut subscribers = inner.subscribers.borrow_mut(); - if !subscribers.contains(¤t_scope_id) { - subscribers.push(current_scope_id); - drop(subscribers); - let unsubscriber = current_unsubscriber(); - inner.subscribers.borrow_mut().push(unsubscriber.scope); - } - } - Ref::map(inner, |v| &v.value) - } - - pub fn write(&self) -> Write<'_, T> { - let inner = self.inner.write(); - let borrow = RefMut::map(inner, |v| &mut v.value); - Write { - write: borrow, - signal: SignalSubscriberDrop { signal: *self }, - } - } - - fn update_subscribers(&self) { - { - let inner = self.inner.read(); - for &scope_id in &*inner.subscribers.borrow() { - log::trace!( - "Write on {:?} triggered update on {:?}", - self.inner.value, - scope_id - ); - (inner.update_any)(scope_id); - } - } - - let subscribers = { - let self_read = self.inner.read(); - let mut effects = self_read.effect_subscribers.borrow_mut(); - std::mem::take(&mut *effects) - }; - for effect in subscribers { - log::trace!( - "Write on {:?} triggered effect {:?}", - self.inner.value, - effect - ); - effect.try_run(); - } - } - - pub fn set(&self, value: T) { - *self.write() = value; - } - - pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { - let write = self.read(); - f(&*write) - } - - pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { - let mut write = self.write(); - f(&mut *write) - } -} - -impl Signal { - pub fn value(&self) -> T { - self.read().clone() - } -} - -impl PartialEq for Signal { - fn eq(&self, other: &Self) -> bool { - self.inner == other.inner - } -} - -struct SignalSubscriberDrop { - signal: Signal, -} - -impl Drop for SignalSubscriberDrop { - fn drop(&mut self) { - self.signal.update_subscribers(); - } -} - -pub struct Write<'a, T: 'static, I: 'static = T> { - write: RefMut<'a, T>, - signal: SignalSubscriberDrop, -} - -impl<'a, T: 'static, I: 'static> Write<'a, T, I> { - pub fn map(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<'a, O, I> { - let Self { write, signal } = myself; - Write { - write: RefMut::map(write, f), - signal, - } - } - - pub fn filter_map( - myself: Self, - f: impl FnOnce(&mut T) -> Option<&mut O>, - ) -> Option> { - let Self { write, signal } = myself; - let write = RefMut::filter_map(write, f).ok(); - write.map(|write| Write { - write, - signal: signal, - }) - } -} - -impl<'a, T: 'static> Deref for Write<'a, T> { - type Target = T; - - fn deref(&self) -> &Self::Target { - &*self.write - } -} - -impl DerefMut for Write<'_, T> { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut *self.write - } -} +pub(crate) mod signal; +pub use signal::*; diff --git a/packages/signals/src/memo.rs b/packages/signals/src/memo.rs index 07d18f5a6..62292731a 100644 --- a/packages/signals/src/memo.rs +++ b/packages/signals/src/memo.rs @@ -1,12 +1,15 @@ use dioxus_core::prelude::*; -use crate::{get_effect_stack, CopyValue, Effect, Signal, SignalData}; +use crate::{get_effect_stack, signal::SignalData, CopyValue, Effect, ReadOnlySignal, Signal}; -pub fn use_memo(cx: &ScopeState, f: impl FnMut() -> R + 'static) -> Signal { - *cx.use_hook(|| memo(f)) +pub fn use_selector( + cx: &ScopeState, + f: impl FnMut() -> R + 'static, +) -> ReadOnlySignal { + *cx.use_hook(|| selector(f)) } -pub fn memo(mut f: impl FnMut() -> R + 'static) -> Signal { +fn selector(mut f: impl FnMut() -> R + 'static) -> ReadOnlySignal { let state = Signal:: { inner: CopyValue::invalid(), }; @@ -38,5 +41,5 @@ pub fn memo(mut f: impl FnMut() -> R + 'static) -> Signal { } })); - state + ReadOnlySignal::new(state) } diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs new file mode 100644 index 000000000..0c45da75a --- /dev/null +++ b/packages/signals/src/signal.rs @@ -0,0 +1,244 @@ +use std::{ + cell::{Ref, RefCell, RefMut}, + ops::{Deref, DerefMut}, + rc::Rc, + sync::Arc, +}; + +use dioxus_core::{ + prelude::{current_scope_id, has_context, provide_context, schedule_update_any}, + ScopeId, ScopeState, +}; + +use crate::{CopyValue, Effect}; + +pub fn use_signal(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal { + *cx.use_hook(|| Signal::new(f())) +} + +#[derive(Clone)] +struct Unsubscriber { + scope: ScopeId, + subscribers: Rc>>>>>, +} + +impl Drop for Unsubscriber { + fn drop(&mut self) { + for subscribers in self.subscribers.borrow().iter() { + subscribers.borrow_mut().retain(|s| *s != self.scope); + } + } +} + +fn current_unsubscriber() -> Unsubscriber { + match has_context() { + Some(rt) => rt, + None => { + let owner = Unsubscriber { + scope: current_scope_id().expect("in a virtual dom"), + subscribers: Default::default(), + }; + provide_context(owner).expect("in a virtual dom") + } + } +} + +pub(crate) struct SignalData { + pub(crate) subscribers: Rc>>, + pub(crate) effect_subscribers: Rc>>, + pub(crate) update_any: Arc, + pub(crate) value: T, +} + +pub struct Signal { + pub(crate) inner: CopyValue>, +} + +impl Signal { + pub fn new(value: T) -> Self { + Self { + inner: CopyValue::new(SignalData { + subscribers: Default::default(), + effect_subscribers: Default::default(), + update_any: schedule_update_any().expect("in a virtual dom"), + value, + }), + } + } + + pub fn origin_scope(&self) -> ScopeId { + self.inner.origin_scope() + } + + pub fn read(&self) -> Ref { + let inner = self.inner.read(); + if let Some(effect) = Effect::current() { + let mut effect_subscribers = inner.effect_subscribers.borrow_mut(); + if !effect_subscribers.contains(&effect) { + effect_subscribers.push(effect); + } + } else if let Some(current_scope_id) = current_scope_id() { + log::trace!( + "{:?} subscribed to {:?}", + self.inner.value, + current_scope_id + ); + let mut subscribers = inner.subscribers.borrow_mut(); + if !subscribers.contains(¤t_scope_id) { + subscribers.push(current_scope_id); + drop(subscribers); + let unsubscriber = current_unsubscriber(); + inner.subscribers.borrow_mut().push(unsubscriber.scope); + } + } + Ref::map(inner, |v| &v.value) + } + + pub fn write(&self) -> Write<'_, T> { + let inner = self.inner.write(); + let borrow = RefMut::map(inner, |v| &mut v.value); + Write { + write: borrow, + signal: SignalSubscriberDrop { signal: *self }, + } + } + + fn update_subscribers(&self) { + { + let inner = self.inner.read(); + for &scope_id in &*inner.subscribers.borrow() { + log::trace!( + "Write on {:?} triggered update on {:?}", + self.inner.value, + scope_id + ); + (inner.update_any)(scope_id); + } + } + + let subscribers = { + let self_read = self.inner.read(); + let mut effects = self_read.effect_subscribers.borrow_mut(); + std::mem::take(&mut *effects) + }; + for effect in subscribers { + log::trace!( + "Write on {:?} triggered effect {:?}", + self.inner.value, + effect + ); + effect.try_run(); + } + } + + pub fn set(&self, value: T) { + *self.write() = value; + } + + pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { + let write = self.read(); + f(&*write) + } + + pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { + let mut write = self.write(); + f(&mut *write) + } +} + +impl Signal { + pub fn value(&self) -> T { + self.read().clone() + } +} + +impl PartialEq for Signal { + fn eq(&self, other: &Self) -> bool { + self.inner == other.inner + } +} + +struct SignalSubscriberDrop { + signal: Signal, +} + +impl Drop for SignalSubscriberDrop { + fn drop(&mut self) { + self.signal.update_subscribers(); + } +} + +pub struct Write<'a, T: 'static, I: 'static = T> { + write: RefMut<'a, T>, + signal: SignalSubscriberDrop, +} + +impl<'a, T: 'static, I: 'static> Write<'a, T, I> { + pub fn map(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<'a, O, I> { + let Self { write, signal } = myself; + Write { + write: RefMut::map(write, f), + signal, + } + } + + pub fn filter_map( + myself: Self, + f: impl FnOnce(&mut T) -> Option<&mut O>, + ) -> Option> { + let Self { write, signal } = myself; + let write = RefMut::filter_map(write, f).ok(); + write.map(|write| Write { + write, + signal: signal, + }) + } +} + +impl<'a, T: 'static> Deref for Write<'a, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + &*self.write + } +} + +impl DerefMut for Write<'_, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut *self.write + } +} + +pub struct ReadOnlySignal { + inner: Signal, +} + +impl ReadOnlySignal { + pub fn new(signal: Signal) -> Self { + Self { inner: signal } + } + + pub fn origin_scope(&self) -> ScopeId { + self.inner.origin_scope() + } + + pub fn read(&self) -> Ref { + self.inner.read() + } + + pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { + self.inner.with(f) + } +} + +impl ReadOnlySignal { + pub fn value(&self) -> T { + self.read().clone() + } +} + +impl PartialEq for ReadOnlySignal { + fn eq(&self, other: &Self) -> bool { + self.inner == other.inner + } +} From 2c7d0700d4dc2b3d926b98a94d6599a8a6f6c8d3 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 16:17:47 -0700 Subject: [PATCH 24/39] rename memo to selector --- packages/signals/src/lib.rs | 4 ++-- packages/signals/src/{memo.rs => selector.rs} | 2 +- packages/signals/tests/{memo.rs => selector.rs} | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) rename packages/signals/src/{memo.rs => selector.rs} (92%) rename packages/signals/tests/{memo.rs => selector.rs} (98%) diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index 66b7801f0..b667fe074 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -3,7 +3,7 @@ pub use rt::*; mod effect; pub use effect::*; mod impls; -mod memo; -pub use memo::*; +mod selector; +pub use selector::*; pub(crate) mod signal; pub use signal::*; diff --git a/packages/signals/src/memo.rs b/packages/signals/src/selector.rs similarity index 92% rename from packages/signals/src/memo.rs rename to packages/signals/src/selector.rs index 62292731a..dd02031ad 100644 --- a/packages/signals/src/memo.rs +++ b/packages/signals/src/selector.rs @@ -9,7 +9,7 @@ pub fn use_selector( *cx.use_hook(|| selector(f)) } -fn selector(mut f: impl FnMut() -> R + 'static) -> ReadOnlySignal { +pub fn selector(mut f: impl FnMut() -> R + 'static) -> ReadOnlySignal { let state = Signal:: { inner: CopyValue::invalid(), }; diff --git a/packages/signals/tests/memo.rs b/packages/signals/tests/selector.rs similarity index 98% rename from packages/signals/tests/memo.rs rename to packages/signals/tests/selector.rs index b27d7d546..17eb1c38a 100644 --- a/packages/signals/tests/memo.rs +++ b/packages/signals/tests/selector.rs @@ -26,7 +26,7 @@ fn memos_rerun() { let mut signal = use_signal(cx, || 0); let memo = cx.use_hook(move || { to_owned![counter]; - memo(move || { + selector(move || { counter.borrow_mut().effect += 1; println!("Signal: {:?}", signal); signal.value() @@ -102,7 +102,7 @@ fn memos_prevents_component_rerun() { let memo = cx.use_hook(move || { to_owned![counter]; - memo(move || { + selector(move || { counter.borrow_mut().effect += 1; println!("Signal: {:?}", signal); signal.value() From cfd68bf7d9ac94851928f9772536a8897c6e90d0 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 16:56:49 -0700 Subject: [PATCH 25/39] document signals crate --- packages/hooks/src/computed.rs | 210 ------------------------------- packages/hooks/src/lib.rs | 3 - packages/signals/src/effect.rs | 10 ++ packages/signals/src/impls.rs | 60 ++++++++- packages/signals/src/rt.rs | 6 + packages/signals/src/selector.rs | 20 +++ packages/signals/src/signal.rs | 31 +++++ 7 files changed, 123 insertions(+), 217 deletions(-) delete mode 100644 packages/hooks/src/computed.rs diff --git a/packages/hooks/src/computed.rs b/packages/hooks/src/computed.rs deleted file mode 100644 index 248eb4f83..000000000 --- a/packages/hooks/src/computed.rs +++ /dev/null @@ -1,210 +0,0 @@ -use dioxus_core::{ScopeId, ScopeState}; -use slab::Slab; -use std::{ - cell::{RefCell, RefMut}, - collections::HashSet, - ops::{Deref, DerefMut}, - rc::Rc, -}; - -/// Create a new tracked state. -/// Tracked state is state that can drive Selector state -/// -/// It state will efficiently update any Selector state that is reading from it, but it is not readable on it's own. -/// -/// ```rust -/// use dioxus::prelude::*; -/// -/// fn Parent(cx: Scope) -> Element { -/// let count = use_tracked_state(cx, || 0); -/// -/// render! { -/// Child { -/// count: count.clone(), -/// } -/// } -/// } -/// -/// #[inline_props] -/// fn Child(cx: Scope, count: Tracked) -> Element { -/// let less_than_five = use_selector(cx, count, |count| *count < 5); -/// -/// render! { -/// "{less_than_five}" -/// } -/// } -/// ``` -pub fn use_tracked_state(cx: &ScopeState, init: impl FnOnce() -> T) -> &Tracked { - cx.use_hook(|| { - let init = init(); - Tracked::new(cx, init) - }) -} - -/// Tracked state is state that can drive Selector state -/// -/// Tracked state will efficiently update any Selector state that is reading from it, but it is not readable on it's own. -#[derive(Clone)] -pub struct Tracked { - state: Rc>, - update_any: std::sync::Arc, - subscribers: SubscribedCallbacks, -} - -impl PartialEq for Tracked { - fn eq(&self, other: &Self) -> bool { - self.state == other.state - } -} - -impl Tracked { - /// Create a new tracked state - pub fn new(cx: &ScopeState, state: I) -> Self { - let subscribers = std::rc::Rc::new(std::cell::RefCell::new(Slab::new())); - Self { - state: Rc::new(RefCell::new(state)), - subscribers, - update_any: cx.schedule_update_any(), - } - } - - /// Create a new Selector state from this tracked state - pub fn compute( - &self, - mut compute: impl FnMut(&I) -> O + 'static, - ) -> Selector { - let subscribers = Rc::new(RefCell::new(HashSet::new())); - let state = Rc::new(RefCell::new(compute(&self.state.borrow()))); - let update_any = self.update_any.clone(); - - Selector { - value: state.clone(), - subscribers: subscribers.clone(), - _tracker: Rc::new(self.track(move |input_state| { - let new = compute(input_state); - let different = { - let state = state.borrow(); - *state != new - }; - if different { - let mut state = state.borrow_mut(); - *state = new; - for id in subscribers.borrow().iter().copied() { - (update_any)(id); - } - } - })), - } - } - - pub(crate) fn track(&self, update: impl FnMut(&I) + 'static) -> Tracker { - let mut subscribers = self.subscribers.borrow_mut(); - let id = subscribers.insert(Box::new(update)); - Tracker { - subscribers: self.subscribers.clone(), - id, - } - } - - /// Write to the tracked state - pub fn write(&self) -> TrackedMut<'_, I> { - TrackedMut { - state: self.state.borrow_mut(), - subscribers: self.subscribers.clone(), - } - } -} - -/// A mutable reference to tracked state -pub struct TrackedMut<'a, I> { - state: RefMut<'a, I>, - subscribers: SubscribedCallbacks, -} - -impl<'a, I> Deref for TrackedMut<'a, I> { - type Target = I; - - fn deref(&self) -> &Self::Target { - &self.state - } -} - -impl<'a, I> DerefMut for TrackedMut<'a, I> { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.state - } -} - -impl<'a, I> Drop for TrackedMut<'a, I> { - fn drop(&mut self) { - let state = self.state.deref(); - for (_, sub) in &mut *self.subscribers.borrow_mut() { - sub(state); - } - } -} - -type SubscribedCallbacks = std::rc::Rc>>>; - -pub(crate) struct Tracker { - subscribers: SubscribedCallbacks, - id: usize, -} - -impl Drop for Tracker { - fn drop(&mut self) { - let _ = self.subscribers.borrow_mut().remove(self.id); - } -} - -pub fn use_selector( - cx: &ScopeState, - tracked: &Tracked, - init: impl FnMut(&I) -> O + 'static, -) -> O { - let selector = cx.use_hook(|| tracked.compute(init)); - selector.use_state(cx) -} - -/// Selector state is state that is derived from tracked state -/// -/// Whenever the tracked state changes, the Selector state will be updated and any components reading from it will be rerun -#[derive(Clone)] -pub struct Selector { - _tracker: Rc>, - value: Rc>, - subscribers: Rc>>, -} - -impl PartialEq for Selector { - fn eq(&self, other: &Self) -> bool { - std::rc::Rc::ptr_eq(&self.value, &other.value) - } -} - -impl Selector { - /// Read the Selector state and subscribe to updates - pub fn use_state(&self, cx: &ScopeState) -> T { - cx.use_hook(|| { - let id = cx.scope_id(); - self.subscribers.borrow_mut().insert(id); - - ComputedRead { - scope: cx.scope_id(), - subscribers: self.subscribers.clone(), - } - }); - self.value.borrow().clone() - } -} - -struct ComputedRead { - scope: ScopeId, - subscribers: std::rc::Rc>>, -} - -impl Drop for ComputedRead { - fn drop(&mut self) { - self.subscribers.borrow_mut().remove(&self.scope); - } -} diff --git a/packages/hooks/src/lib.rs b/packages/hooks/src/lib.rs index 7e5798167..65f390eda 100644 --- a/packages/hooks/src/lib.rs +++ b/packages/hooks/src/lib.rs @@ -52,9 +52,6 @@ macro_rules! to_owned { }; } -mod computed; -pub use computed::*; - mod use_on_unmount; pub use use_on_unmount::*; diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs index 06b02ffd4..be57f5cfd 100644 --- a/packages/signals/src/effect.rs +++ b/packages/signals/src/effect.rs @@ -20,6 +20,13 @@ pub(crate) fn get_effect_stack() -> EffectStack { } } +/// Create a new effect. The effect will be run immediately and whenever any signal it reads changes. +/// The signal will be owned by the current component and will be dropped when the component is dropped. +pub fn use_effect(cx: &ScopeState, callback: impl FnMut() + 'static) { + cx.use_hook(|| Effect::new(callback)); +} + +/// Effects allow you to run code when a signal changes. Effects are run immediately and whenever any signal it reads changes. #[derive(Copy, Clone, PartialEq)] pub struct Effect { pub(crate) callback: CopyValue>, @@ -36,6 +43,9 @@ impl Effect { get_effect_stack().effects.read().last().copied() } + /// Create a new effect. The effect will be run immediately and whenever any signal it reads changes. + /// + /// The signal will be owned by the current component and will be dropped when the component is dropped. pub fn new(callback: impl FnMut() + 'static) -> Self { let myself = Self { callback: CopyValue::new(Box::new(callback)), diff --git a/packages/signals/src/impls.rs b/packages/signals/src/impls.rs index 0328d4063..4e81a5a27 100644 --- a/packages/signals/src/impls.rs +++ b/packages/signals/src/impls.rs @@ -43,6 +43,7 @@ macro_rules! read_impls { } impl $ty> { + /// Unwraps the inner value and clones it. pub fn unwrap(&self) -> T where T: Clone, @@ -50,6 +51,7 @@ macro_rules! read_impls { self.with(|v| v.clone()).unwrap() } + /// Attemps to read the inner value of the Option. pub fn as_ref(&self) -> Option> { Ref::filter_map(self.read(), |v| v.as_ref()).ok() } @@ -59,6 +61,14 @@ macro_rules! read_impls { macro_rules! write_impls { ($ty:ident) => { + impl + Copy + 'static> std::ops::Add for $ty { + type Output = T; + + fn add(self, rhs: T) -> Self::Output { + self.with(|v| *v + rhs) + } + } + impl + Copy + 'static> std::ops::AddAssign for $ty { fn add_assign(&mut self, rhs: T) { self.with_mut(|v| *v = *v + rhs) @@ -71,73 +81,111 @@ macro_rules! write_impls { } } + impl + Copy + 'static> std::ops::Sub for $ty { + type Output = T; + + fn sub(self, rhs: T) -> Self::Output { + self.with(|v| *v - rhs) + } + } + impl + Copy + 'static> std::ops::MulAssign for $ty { fn mul_assign(&mut self, rhs: T) { self.with_mut(|v| *v = *v * rhs) } } + impl + Copy + 'static> std::ops::Mul for $ty { + type Output = T; + + fn mul(self, rhs: T) -> Self::Output { + self.with(|v| *v * rhs) + } + } + impl + Copy + 'static> std::ops::DivAssign for $ty { fn div_assign(&mut self, rhs: T) { self.with_mut(|v| *v = *v / rhs) } } + impl + Copy + 'static> std::ops::Div for $ty { + type Output = T; + + fn div(self, rhs: T) -> Self::Output { + self.with(|v| *v / rhs) + } + } + impl $ty> { + /// Pushes a new value to the end of the vector. pub fn push(&self, value: T) { self.with_mut(|v| v.push(value)) } + /// Pops the last value from the vector. pub fn pop(&self) -> Option { self.with_mut(|v| v.pop()) } + /// Inserts a new value at the given index. pub fn insert(&self, index: usize, value: T) { self.with_mut(|v| v.insert(index, value)) } + /// Removes the value at the given index. pub fn remove(&self, index: usize) -> T { self.with_mut(|v| v.remove(index)) } + /// Clears the vector, removing all values. pub fn clear(&self) { self.with_mut(|v| v.clear()) } + /// Extends the vector with the given iterator. pub fn extend(&self, iter: impl IntoIterator) { self.with_mut(|v| v.extend(iter)) } + /// Truncates the vector to the given length. pub fn truncate(&self, len: usize) { self.with_mut(|v| v.truncate(len)) } + /// Swaps two values in the vector. pub fn swap_remove(&self, index: usize) -> T { self.with_mut(|v| v.swap_remove(index)) } + /// Retains only the values that match the given predicate. pub fn retain(&self, f: impl FnMut(&T) -> bool) { self.with_mut(|v| v.retain(f)) } + /// Splits the vector into two at the given index. pub fn split_off(&self, at: usize) -> Vec { self.with_mut(|v| v.split_off(at)) } } impl $ty> { + /// Takes the value out of the Option. pub fn take(&self) -> Option { self.with_mut(|v| v.take()) } + /// Replace the value in the Option. pub fn replace(&self, value: T) -> Option { self.with_mut(|v| v.replace(value)) } + /// Gets the value out of the Option, or inserts the given value if the Option is empty. pub fn get_or_insert(&self, default: T) -> Ref<'_, T> { self.get_or_insert_with(|| default) } + /// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty. pub fn get_or_insert_with(&self, default: impl FnOnce() -> T) -> Ref<'_, T> { let borrow = self.read(); if borrow.is_none() { @@ -158,6 +206,7 @@ read_impls!(Signal); write_impls!(Signal); read_impls!(ReadOnlySignal); +/// An iterator over the values of a `CopyValue>`. pub struct CopyValueIterator { index: usize, value: CopyValue>, @@ -198,12 +247,13 @@ impl CopyValue> { } } -pub struct CopySignalIterator { +/// An iterator over items in a `Signal>`. +pub struct SignalIterator { index: usize, value: Signal>, } -impl Iterator for CopySignalIterator { +impl Iterator for SignalIterator { type Item = T; fn next(&mut self) -> Option { @@ -214,12 +264,12 @@ impl Iterator for CopySignalIterator { } impl IntoIterator for Signal> { - type IntoIter = CopySignalIterator; + type IntoIter = SignalIterator; type Item = T; fn into_iter(self) -> Self::IntoIter { - CopySignalIterator { + SignalIterator { index: 0, value: self, } @@ -227,12 +277,14 @@ impl IntoIterator for Signal> { } impl Signal> { + /// Returns a reference to an element or `None` if out of bounds. pub fn get_mut(&self, index: usize) -> Option>> { Write::filter_map(self.write(), |v| v.get_mut(index)) } } impl Signal> { + /// Returns a reference to an element or `None` if out of bounds. pub fn as_mut(&self) -> Option>> { Write::filter_map(self.write(), |v| v.as_mut()) } diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index f96ff6ab3..dc1c4a66f 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -40,12 +40,18 @@ fn owner_in_scope(scope: ScopeId) -> Rc { } } +/// CopyValue is a wrapper around a value to make the value mutable and Copy. +/// +/// It is internally backed by [`generational_box::GenerationalBox`]. pub struct CopyValue { pub(crate) value: GenerationalBox, origin_scope: ScopeId, } impl CopyValue { + /// Create a new CopyValue. The value will be stored in the current component. + /// + /// Once the component this value is created in is dropped, the value will be dropped. pub fn new(value: T) -> Self { let owner = current_owner(); diff --git a/packages/signals/src/selector.rs b/packages/signals/src/selector.rs index dd02031ad..79a8f679b 100644 --- a/packages/signals/src/selector.rs +++ b/packages/signals/src/selector.rs @@ -2,6 +2,23 @@ use dioxus_core::prelude::*; use crate::{get_effect_stack, signal::SignalData, CopyValue, Effect, ReadOnlySignal, Signal}; +/// Creates a new Selector. The selector will be run immediately and whenever any signal it reads changes. +/// +/// Selectors can be used to efficiently compute derived data from signals. +/// +/// ```rust +/// use dioxus::prelude::*; +/// use dioxus_signals::*; +/// +/// fn App(cx: Scope) -> Element { +/// let mut count = use_signal(cx, || 0); +/// let double = use_selector(cx, move || count * 2); +/// count += 1; +/// assert_eq!(double.value(), count * 2); +/// +/// render! { "{double}" } +/// } +/// ``` pub fn use_selector( cx: &ScopeState, f: impl FnMut() -> R + 'static, @@ -9,6 +26,9 @@ pub fn use_selector( *cx.use_hook(|| selector(f)) } +/// Creates a new Selector. The selector will be run immediately and whenever any signal it reads changes. +/// +/// Selectors can be used to efficiently compute derived data from signals. pub fn selector(mut f: impl FnMut() -> R + 'static) -> ReadOnlySignal { let state = Signal:: { inner: CopyValue::invalid(), diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 0c45da75a..698ac8e12 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -12,6 +12,37 @@ use dioxus_core::{ use crate::{CopyValue, Effect}; +/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking. +/// +/// ```rust +/// use dioxus::prelude::*; +/// use dioxus_signals::*; +/// +/// fn App(cx: Scope) -> Element { +/// let mut count = use_signal(cx, || 0); +/// +/// // Because signals have automatic dependency tracking, if you never read them in a component, that component will not be re-rended when the signal is updated. +/// // The app component will never be rerendered in this example. +/// render! { Child { state: count } } +/// } +/// +/// #[inline_props] +/// fn Child(cx: Scope, state: Signal) -> Element { +/// let state = *state; +/// +/// use_future!(cx, |()| async move { +/// // Because the signal is a Copy type, we can use it in an async block without cloning it. +/// *state.write() += 1; +/// }); +/// +/// render! { +/// button { +/// onclick: move |_| *state.write() += 1, +/// "{state}" +/// } +/// } +/// } +/// ``` pub fn use_signal(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal { *cx.use_hook(|| Signal::new(f())) } From 280d094f67f0de7856d81cd836f744147fde0c66 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 17:32:25 -0700 Subject: [PATCH 26/39] document generational box --- packages/generational-box/README.md | 34 ++++++++++++++++++++++++++++ packages/generational-box/src/lib.rs | 3 +++ 2 files changed, 37 insertions(+) create mode 100644 packages/generational-box/README.md diff --git a/packages/generational-box/README.md b/packages/generational-box/README.md new file mode 100644 index 000000000..d4600dd53 --- /dev/null +++ b/packages/generational-box/README.md @@ -0,0 +1,34 @@ +# Generational Box + +Generational Box is a runtime for Rust that allows any static type to implement `Copy`. It can be combined with a global runtime to create an ergonomic state solution like `dioxus-signals`. This crate contains no `unsafe` code. + +There are three main types that manage state in Generational Box: + +- Store: Handles recycling generational boxes that have been dropped. Your application should have one store or one store per thread. +- Owner: Handles dropping generational boxes. The owner acts like a runtime lifetime guard. Any states that you create with an owner will be dropped when that owner is dropped. +- GenerationalBox: The core Copy state type. The generational box will be dropped when the owner is dropped. + +Example: + +```rust +// Create a store for this thread +let store = Store::default(); + +{ + // Create an owner for some state for a scope + let owner = store.owner(); + + // Create some non-copy data, move it into a owner, and work with copy data + let data: String = "hello world".to_string(); + let key = owner.insert(data); + + // The generational box can be read from and written to like a RefCell + let value = key.read(); + assert_eq!(*value, "hello world"); +} +// Reading value at this point will cause a panic +``` + +## How it works + +Internally \ No newline at end of file diff --git a/packages/generational-box/src/lib.rs b/packages/generational-box/src/lib.rs index d45701e6c..dedd62d75 100644 --- a/packages/generational-box/src/lib.rs +++ b/packages/generational-box/src/lib.rs @@ -145,6 +145,7 @@ fn fuzz() { } } +/// The core Copy state type. The generational box will be dropped when the [Owner] is dropped. pub struct GenerationalBox { raw: MemoryLocation, #[cfg(any(debug_assertions, feature = "check_generation"))] @@ -268,6 +269,7 @@ impl MemoryLocation { } } +/// Handles recycling generational boxes that have been dropped. Your application should have one store or one store per thread. #[derive(Clone)] pub struct Store { bump: &'static Bump, @@ -310,6 +312,7 @@ impl Store { } } +/// Owner: Handles dropping generational boxes. The owner acts like a runtime lifetime guard. Any states that you create with an owner will be dropped when that owner is dropped. pub struct Owner { store: Store, owned: Rc>>, From 4447709ac85fba020fb1f49738a6b7d89189efb4 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 17:49:14 -0700 Subject: [PATCH 27/39] add readmes --- packages/generational-box/README.md | 2 +- packages/generational-box/src/lib.rs | 11 ++++++ packages/signals/README.md | 56 ++++++++++++++++++++++++++++ packages/signals/src/lib.rs | 3 ++ 4 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 packages/signals/README.md diff --git a/packages/generational-box/README.md b/packages/generational-box/README.md index d4600dd53..5ab7926ba 100644 --- a/packages/generational-box/README.md +++ b/packages/generational-box/README.md @@ -2,7 +2,7 @@ Generational Box is a runtime for Rust that allows any static type to implement `Copy`. It can be combined with a global runtime to create an ergonomic state solution like `dioxus-signals`. This crate contains no `unsafe` code. -There are three main types that manage state in Generational Box: +Three main types manage state in Generational Box: - Store: Handles recycling generational boxes that have been dropped. Your application should have one store or one store per thread. - Owner: Handles dropping generational boxes. The owner acts like a runtime lifetime guard. Any states that you create with an owner will be dropped when that owner is dropped. diff --git a/packages/generational-box/src/lib.rs b/packages/generational-box/src/lib.rs index dedd62d75..29c7ebdb2 100644 --- a/packages/generational-box/src/lib.rs +++ b/packages/generational-box/src/lib.rs @@ -1,3 +1,6 @@ +#![doc = include_str!("../README.md")] +#![warn(missing_docs)] + use std::{ cell::{Cell, Ref, RefCell, RefMut}, fmt::Debug, @@ -180,6 +183,7 @@ impl GenerationalBox { } } + /// Try to read the value. Returns None if the value is no longer valid. pub fn try_read(&self) -> Option> { self.validate() .then(|| { @@ -191,10 +195,12 @@ impl GenerationalBox { .flatten() } + /// Read the value. Panics if the value is no longer valid. pub fn read(&self) -> Ref<'_, T> { self.try_read().unwrap() } + /// Try to write the value. Returns None if the value is no longer valid. pub fn try_write(&self) -> Option> { self.validate() .then(|| { @@ -206,16 +212,19 @@ impl GenerationalBox { .flatten() } + /// Write the value. Panics if the value is no longer valid. pub fn write(&self) -> RefMut<'_, T> { self.try_write().unwrap() } + /// Set the value. Panics if the value is no longer valid. pub fn set(&self, value: T) { self.validate().then(|| { *self.raw.data.borrow_mut() = Some(Box::new(value)); }); } + /// Returns true if the pointer is equal to the other pointer. pub fn ptr_eq(&self, other: &Self) -> bool { #[cfg(any(debug_assertions, feature = "check_generation"))] { @@ -304,6 +313,7 @@ impl Store { } } + /// Create a new owner. The owner will be responsible for dropping all of the generational boxes that it creates. pub fn owner(&self) -> Owner { Owner { store: self.clone(), @@ -319,6 +329,7 @@ pub struct Owner { } impl Owner { + /// Insert a value into the store. The value will be dropped when the owner is dropped. pub fn insert(&self, value: T) -> GenerationalBox { let mut location = self.store.claim(); let key = location.replace(value); diff --git a/packages/signals/README.md b/packages/signals/README.md new file mode 100644 index 000000000..e65c613fe --- /dev/null +++ b/packages/signals/README.md @@ -0,0 +1,56 @@ +# Dioxus Signals + +Dioxus Signals is an ergonomic Copy runtime for data with local subscriptions in Dioxus. + +## Copy Data + +All signals implement Copy, even if the inner value does not implement copy. This makes it easy to move any data into futures or children. + +```rust +fn App(cx: Scope) -> Element { + let signal = use_signal(cx, || "hello world".to_string()); + + spawn(async move { + // signal is Copy even though String is not copy + signal + }); + + render! { + "{signal}" + } +} +``` + +## Local Subscriptions + +Signals will only subscribe to components when you read from the signal in that component. It will never subscribe to a component when reading data in a future or event handler. + +```rust +fn app(cx: Scope) -> Element { + // Because signal is never read in this component, this component will not rerun when the signal changes + let signal = use_signal(cx, || 0); + + render! { + onclick: move |_| { + *signal.write() += 1; + } + for id in 0..10 { + Child { + signal: signal, + } + } + } +} + +#[derive(Props, Clone, PartialEq)] +struct ChildProps { + signal: Signal, +} + +fn Child(cx: Scope) -> Element { + // This component does read from the signal, so when the signal changes it will rerun + render! { + "{cx.props.signal}" + } +} +``` diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index b667fe074..1c67ab462 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -1,3 +1,6 @@ +#![doc = include_str!("../README.md")] +#![warn(missing_docs)] + mod rt; pub use rt::*; mod effect; From 0c17bdb73753443c0c4f57e8b2eb3f6c750d386f Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 17:55:29 -0700 Subject: [PATCH 28/39] don't subscribe in tasks or event handlers --- packages/core/src/lib.rs | 9 +++++---- packages/core/src/runtime.rs | 5 ++++- packages/core/src/scheduler/wait.rs | 2 ++ packages/core/src/scope_context.rs | 6 ++++++ packages/core/src/virtual_dom.rs | 4 ++++ packages/signals/src/signal.rs | 25 ++++++++++++++----------- 6 files changed, 35 insertions(+), 16 deletions(-) diff --git a/packages/core/src/lib.rs b/packages/core/src/lib.rs index 363be390d..62e142f60 100644 --- a/packages/core/src/lib.rs +++ b/packages/core/src/lib.rs @@ -73,10 +73,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 diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs index 89de770c5..9f031f287 100644 --- a/packages/core/src/runtime.rs +++ b/packages/core/src/runtime.rs @@ -1,4 +1,4 @@ -use std::cell::{Ref, RefCell}; +use std::cell::{Cell, Ref, RefCell}; use crate::{innerlude::Scheduler, scope_context::ScopeContext, scopes::ScopeId}; use std::rc::Rc; @@ -47,6 +47,7 @@ pub struct Runtime { // We use this to track the current scope pub(crate) scope_stack: RefCell>, + pub(crate) rendering: Cell, } impl Runtime { @@ -57,6 +58,8 @@ impl Runtime { scope_contexts: Default::default(), scope_stack: Default::default(), + + rendering: Cell::new(true), }); runtime } diff --git a/packages/core/src/scheduler/wait.rs b/packages/core/src/scheduler/wait.rs index 62fa10180..625873293 100644 --- a/packages/core/src/scheduler/wait.rs +++ b/packages/core/src/scheduler/wait.rs @@ -20,6 +20,7 @@ impl VirtualDom { // 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() { @@ -33,5 +34,6 @@ impl VirtualDom { // Remove the scope from the stack self.runtime.scope_stack.borrow_mut().pop(); + self.runtime.rendering.set(true); } } diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index 36c864117..82b3fd4e2 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -263,6 +263,12 @@ pub fn current_scope_id() -> Option { 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() -> Option { with_current_scope(|cx| cx.consume_context::()).flatten() diff --git a/packages/core/src/virtual_dom.rs b/packages/core/src/virtual_dom.rs index 0a4577f4c..a1def71d2 100644 --- a/packages/core/src/virtual_dom.rs +++ b/packages/core/src/virtual_dom.rs @@ -392,10 +392,12 @@ impl VirtualDom { 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; @@ -426,10 +428,12 @@ impl VirtualDom { 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; } diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 698ac8e12..8d2275b41 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -109,17 +109,20 @@ impl Signal { effect_subscribers.push(effect); } } else if let Some(current_scope_id) = current_scope_id() { - log::trace!( - "{:?} subscribed to {:?}", - self.inner.value, - current_scope_id - ); - let mut subscribers = inner.subscribers.borrow_mut(); - if !subscribers.contains(¤t_scope_id) { - subscribers.push(current_scope_id); - drop(subscribers); - let unsubscriber = current_unsubscriber(); - inner.subscribers.borrow_mut().push(unsubscriber.scope); + // only subscribe if the vdom is rendering + if dioxus_core::vdom_is_rendering() { + log::trace!( + "{:?} subscribed to {:?}", + self.inner.value, + current_scope_id + ); + let mut subscribers = inner.subscribers.borrow_mut(); + if !subscribers.contains(¤t_scope_id) { + subscribers.push(current_scope_id); + drop(subscribers); + let unsubscriber = current_unsubscriber(); + inner.subscribers.borrow_mut().push(unsubscriber.scope); + } } } Ref::map(inner, |v| &v.value) From ed05abc19652bccec80ba144946b8712be01c949 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 18:00:17 -0700 Subject: [PATCH 29/39] document remaining methods in the signal crate --- packages/signals/src/impls.rs | 3 ++ packages/signals/src/rt.rs | 10 +++++++ packages/signals/src/signal.rs | 53 ++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) diff --git a/packages/signals/src/impls.rs b/packages/signals/src/impls.rs index 4e81a5a27..6427c2e2b 100644 --- a/packages/signals/src/impls.rs +++ b/packages/signals/src/impls.rs @@ -37,6 +37,7 @@ macro_rules! read_impls { } impl $ty> { + /// Read a value from the inner vector. pub fn get(&self, index: usize) -> Option> { Ref::filter_map(self.read(), |v| v.get(index)).ok() } @@ -236,12 +237,14 @@ impl IntoIterator for CopyValue> { } impl CopyValue> { + /// Write to an element in the inner vector. pub fn get_mut(&self, index: usize) -> Option> { RefMut::filter_map(self.write(), |v| v.get_mut(index)).ok() } } impl CopyValue> { + /// Deref the inner value mutably. pub fn as_mut(&self) -> Option> { RefMut::filter_map(self.write(), |v| v.as_mut()).ok() } diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index dc1c4a66f..685a77204 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -61,6 +61,7 @@ impl CopyValue { } } + /// Create a new CopyValue. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped. pub fn new_in_scope(value: T, scope: ScopeId) -> Self { let owner = owner_in_scope(scope); @@ -79,35 +80,43 @@ impl CopyValue { } } + /// Get the scope this value was created in. pub fn origin_scope(&self) -> ScopeId { self.origin_scope } + /// Try to read the value. If the value has been dropped, this will return None. pub fn try_read(&self) -> Option> { self.value.try_read() } + /// Read the value. If the value has been dropped, this will panic. pub fn read(&self) -> Ref<'_, T> { self.value.read() } + /// Try to write the value. If the value has been dropped, this will return None. pub fn try_write(&self) -> Option> { self.value.try_write() } + /// Write the value. If the value has been dropped, this will panic. pub fn write(&self) -> RefMut<'_, T> { self.value.write() } + /// Set the value. If the value has been dropped, this will panic. pub fn set(&mut self, value: T) { *self.write() = value; } + /// Run a function with a reference to the value. If the value has been dropped, this will panic. pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { let write = self.read(); f(&*write) } + /// Run a function with a mutable reference to the value. If the value has been dropped, this will panic. pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { let mut write = self.write(); f(&mut *write) @@ -115,6 +124,7 @@ impl CopyValue { } impl CopyValue { + /// Get the value. If the value has been dropped, this will panic. pub fn value(&self) -> T { self.read().clone() } diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 8d2275b41..2bac8e1ea 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -81,11 +81,43 @@ pub(crate) struct SignalData { pub(crate) value: T, } +/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking. +/// +/// ```rust +/// use dioxus::prelude::*; +/// use dioxus_signals::*; +/// +/// fn App(cx: Scope) -> Element { +/// let mut count = use_signal(cx, || 0); +/// +/// // Because signals have automatic dependency tracking, if you never read them in a component, that component will not be re-rended when the signal is updated. +/// // The app component will never be rerendered in this example. +/// render! { Child { state: count } } +/// } +/// +/// #[inline_props] +/// fn Child(cx: Scope, state: Signal) -> Element { +/// let state = *state; +/// +/// use_future!(cx, |()| async move { +/// // Because the signal is a Copy type, we can use it in an async block without cloning it. +/// *state.write() += 1; +/// }); +/// +/// render! { +/// button { +/// onclick: move |_| *state.write() += 1, +/// "{state}" +/// } +/// } +/// } +/// ``` pub struct Signal { pub(crate) inner: CopyValue>, } impl Signal { + /// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking. pub fn new(value: T) -> Self { Self { inner: CopyValue::new(SignalData { @@ -97,10 +129,13 @@ impl Signal { } } + /// Get the scope the signal was created in. pub fn origin_scope(&self) -> ScopeId { self.inner.origin_scope() } + /// Get the current value of the signal. This will subscribe the current scope to the signal. + /// If the signal has been dropped, this will panic. pub fn read(&self) -> Ref { let inner = self.inner.read(); if let Some(effect) = Effect::current() { @@ -128,6 +163,8 @@ impl Signal { Ref::map(inner, |v| &v.value) } + /// Get a mutable reference to the signal's value. + /// If the signal has been dropped, this will panic. pub fn write(&self) -> Write<'_, T> { let inner = self.inner.write(); let borrow = RefMut::map(inner, |v| &mut v.value); @@ -165,15 +202,20 @@ impl Signal { } } + /// Set the value of the signal. This will trigger an update on all subscribers. pub fn set(&self, value: T) { *self.write() = value; } + /// Run a closure with a reference to the signal's value. + /// If the signal has been dropped, this will panic. pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { let write = self.read(); f(&*write) } + /// Run a closure with a mutable reference to the signal's value. + /// If the signal has been dropped, this will panic. pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { let mut write = self.write(); f(&mut *write) @@ -181,6 +223,8 @@ impl Signal { } impl Signal { + /// Get the current value of the signal. This will subscribe the current scope to the signal. + /// If the signal has been dropped, this will panic. pub fn value(&self) -> T { self.read().clone() } @@ -202,12 +246,14 @@ impl Drop for SignalSubscriberDrop { } } +/// A mutable reference to a signal's value. pub struct Write<'a, T: 'static, I: 'static = T> { write: RefMut<'a, T>, signal: SignalSubscriberDrop, } impl<'a, T: 'static, I: 'static> Write<'a, T, I> { + /// Map the mutable reference to the signal's value to a new type. pub fn map(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<'a, O, I> { let Self { write, signal } = myself; Write { @@ -216,6 +262,7 @@ impl<'a, T: 'static, I: 'static> Write<'a, T, I> { } } + /// Try to map the mutable reference to the signal's value to a new type pub fn filter_map( myself: Self, f: impl FnOnce(&mut T) -> Option<&mut O>, @@ -243,29 +290,35 @@ impl DerefMut for Write<'_, T> { } } +/// A signal that can only be read from. pub struct ReadOnlySignal { inner: Signal, } impl ReadOnlySignal { + /// Create a new read-only signal. pub fn new(signal: Signal) -> Self { Self { inner: signal } } + /// Get the scope that the signal was created in. pub fn origin_scope(&self) -> ScopeId { self.inner.origin_scope() } + /// Get the current value of the signal. This will subscribe the current scope to the signal. pub fn read(&self) -> Ref { self.inner.read() } + /// Run a closure with a reference to the signal's value. pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { self.inner.with(f) } } impl ReadOnlySignal { + /// Get the current value of the signal. This will subscribe the current scope to the signal. pub fn value(&self) -> T { self.read().clone() } From 292b3367dd58c636bf02018f1f7c92202ecd9cb9 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 7 Aug 2023 18:20:03 -0700 Subject: [PATCH 30/39] create some more compelling examples --- packages/core/src/scope_context.rs | 12 +- packages/generational-box/src/lib.rs | 1 + packages/signals/Cargo.toml | 1 + packages/signals/README.md | 22 +++ packages/signals/examples/context.rs | 25 +++ .../signals/examples/split_subscriptions.rs | 150 ++++++++++++++++++ 6 files changed, 203 insertions(+), 8 deletions(-) create mode 100644 packages/signals/examples/context.rs create mode 100644 packages/signals/examples/split_subscriptions.rs diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index 82b3fd4e2..fec34f914 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -180,14 +180,10 @@ impl ScopeContext { /// 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(&self, context: T) -> T { with_runtime(|runtime| { - // Walk upwards until there is no more parent - and tada we have the root - let mut parent = runtime.get_context(self.scope_id()).unwrap(); - while let Some(next_parent) = parent.parent_id { - parent = runtime.get_context(next_parent).unwrap(); - } - debug_assert_eq!(parent.scope_id(), ScopeId(0)); - - parent.provide_context(context) + runtime + .get_context(ScopeId(0)) + .unwrap() + .provide_context(context) }) .expect("Runtime to exist") } diff --git a/packages/generational-box/src/lib.rs b/packages/generational-box/src/lib.rs index 29c7ebdb2..60bd41419 100644 --- a/packages/generational-box/src/lib.rs +++ b/packages/generational-box/src/lib.rs @@ -258,6 +258,7 @@ impl MemoryLocation { let old = self.data.borrow_mut().take(); #[cfg(any(debug_assertions, feature = "check_generation"))] if old.is_some() { + drop(old); let new_generation = self.generation.get() + 1; self.generation.set(new_generation); } diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index c145b850a..3df7d34ca 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -14,3 +14,4 @@ simple_logger = "4.2.0" [dev-dependencies] dioxus = { workspace = true } +dioxus-desktop = { workspace = true } diff --git a/packages/signals/README.md b/packages/signals/README.md index e65c613fe..68cb8d80a 100644 --- a/packages/signals/README.md +++ b/packages/signals/README.md @@ -54,3 +54,25 @@ fn Child(cx: Scope) -> Element { } } ``` + +Because subscriptions happen when you read from (not create) the data, you can provide signals through the normal context API: + +```rust +fn app(cx: Scope) -> Element { + // Because signal is never read in this component, this component will not rerun when the signal changes + use_context_provider(cx, || Signal::new(0)); + + render! { + Child {} + } +} + +fn Child(cx: Scope) -> Element { + let signal: Signal = *use_context(cx).unwrap(); + // This component does read from the signal, so when the signal changes it will rerun + render! { + "{signal}" + } +} + +``` diff --git a/packages/signals/examples/context.rs b/packages/signals/examples/context.rs new file mode 100644 index 000000000..ddd52e691 --- /dev/null +++ b/packages/signals/examples/context.rs @@ -0,0 +1,25 @@ +#![allow(non_snake_case)] + +use dioxus::prelude::*; +use dioxus_signals::{use_signal, Effect, Signal}; + +fn main() { + dioxus_desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + // Because signal is never read in this component, this component will not rerun when the signal changes + use_context_provider(cx, || Signal::new(0)); + + render! { + Child {} + } +} + +fn Child(cx: Scope) -> Element { + let signal: Signal = *use_context(cx).unwrap(); + // This component does read from the signal, so when the signal changes it will rerun + render! { + "{signal}" + } +} diff --git a/packages/signals/examples/split_subscriptions.rs b/packages/signals/examples/split_subscriptions.rs new file mode 100644 index 000000000..3eb60ed29 --- /dev/null +++ b/packages/signals/examples/split_subscriptions.rs @@ -0,0 +1,150 @@ +#![allow(non_snake_case)] + +use dioxus::prelude::*; +use dioxus_signals::Signal; + +fn main() { + dioxus_desktop::launch(app); +} + +#[derive(Clone, Copy, Default)] +struct ApplicationData { + first_data: Signal, + second_data: Signal, + many_signals: Signal>>, +} + +fn use_app_data(cx: Scope) -> ApplicationData { + *use_context(cx).unwrap() +} + +fn app(cx: Scope) -> Element { + use_context_provider(cx, ApplicationData::default); + + render! { + div { + ReadsFirst {} + } + div { + ReadsSecond {} + } + div { + ReadsManySignals {} + } + } +} + +fn ReadsFirst(cx: Scope) -> Element { + println!("running first"); + let data = use_app_data(cx); + + render! { + button { + onclick: move |_| { + *data.first_data.write() += 1; + }, + "Increase" + } + button { + onclick: move |_| { + *data.first_data.write() -= 1; + }, + "Decrease" + } + button { + onclick: move |_| { + *data.first_data.write() = 0; + }, + "Reset" + } + "{data.first_data}" + } +} + +fn ReadsSecond(cx: Scope) -> Element { + println!("running second"); + let data = use_app_data(cx); + + render! { + button { + onclick: move |_| { + *data.second_data.write() += 1; + }, + "Increase" + } + button { + onclick: move |_| { + *data.second_data.write() -= 1; + }, + "Decrease" + } + button { + onclick: move |_| { + *data.second_data.write() = 0; + }, + "Reset" + } + "{data.second_data}" + } +} + +fn ReadsManySignals(cx: Scope) -> Element { + println!("running many signals"); + let data = use_app_data(cx); + + render! { + button { + onclick: move |_| { + data.many_signals.write().push(Signal::new(0)); + }, + "Create" + } + button { + onclick: move |_| { + data.many_signals.write().pop(); + }, + "Destroy" + } + button { + onclick: move |_| { + if let Some(first) = data.many_signals.read().get(0) { + *first.write() += 1; + } + }, + "Increase First Item" + } + for signal in data.many_signals { + Child { + count: signal, + } + } + } +} + +#[derive(Props, PartialEq)] +struct ChildProps { + count: Signal, +} + +fn Child(cx: Scope) -> Element { + println!("running child"); + let count = cx.props.count; + + render! { + div { + "Child: {count}" + button { + onclick: move |_| { + *count.write() += 1; + }, + "Increase" + } + button { + onclick: move |_| { + *count.write() -= 1; + }, + "Decrease" + } + } + } +} From e2c08a79aeeb7819d2cbaa7cdaa2b4072b3d7880 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 8 Aug 2023 11:12:08 -0700 Subject: [PATCH 31/39] fix signal readme example --- packages/signals/README.md | 20 ++++++++++++++++---- packages/signals/examples/context.rs | 2 +- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/signals/README.md b/packages/signals/README.md index 68cb8d80a..baac37867 100644 --- a/packages/signals/README.md +++ b/packages/signals/README.md @@ -7,12 +7,15 @@ Dioxus Signals is an ergonomic Copy runtime for data with local subscriptions in All signals implement Copy, even if the inner value does not implement copy. This makes it easy to move any data into futures or children. ```rust -fn App(cx: Scope) -> Element { +use dioxus::prelude::*; +use dioxus_signals::*; + +fn app(cx: Scope) -> Element { let signal = use_signal(cx, || "hello world".to_string()); spawn(async move { // signal is Copy even though String is not copy - signal + print!("{signal}"); }); render! { @@ -26,13 +29,19 @@ fn App(cx: Scope) -> Element { Signals will only subscribe to components when you read from the signal in that component. It will never subscribe to a component when reading data in a future or event handler. ```rust +use dioxus::prelude::*; +use dioxus_signals::*; + fn app(cx: Scope) -> Element { // Because signal is never read in this component, this component will not rerun when the signal changes let signal = use_signal(cx, || 0); render! { - onclick: move |_| { - *signal.write() += 1; + button { + onclick: move |_| { + *signal.write() += 1; + }, + "Increase" } for id in 0..10 { Child { @@ -58,6 +67,9 @@ fn Child(cx: Scope) -> Element { Because subscriptions happen when you read from (not create) the data, you can provide signals through the normal context API: ```rust +use dioxus::prelude::*; +use dioxus_signals::*; + fn app(cx: Scope) -> Element { // Because signal is never read in this component, this component will not rerun when the signal changes use_context_provider(cx, || Signal::new(0)); diff --git a/packages/signals/examples/context.rs b/packages/signals/examples/context.rs index ddd52e691..5e7ea831f 100644 --- a/packages/signals/examples/context.rs +++ b/packages/signals/examples/context.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] use dioxus::prelude::*; -use dioxus_signals::{use_signal, Effect, Signal}; +use dioxus_signals::Signal; fn main() { dioxus_desktop::launch(app); From d6089bbd35cf99d92324c8777f8d43e212452607 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 8 Aug 2023 13:06:33 -0700 Subject: [PATCH 32/39] add optional dependency variants of selectors and effects --- packages/signals/Cargo.toml | 1 + packages/signals/examples/dependancies.rs | 38 +++++++++++++ packages/signals/src/dependency.rs | 67 +++++++++++++++++++++++ packages/signals/src/effect.rs | 27 ++++++++- packages/signals/src/lib.rs | 2 + packages/signals/src/selector.rs | 40 ++++++++++++++ 6 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 packages/signals/examples/dependancies.rs create mode 100644 packages/signals/src/dependency.rs diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index 3df7d34ca..2c24758b5 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -15,3 +15,4 @@ simple_logger = "4.2.0" [dev-dependencies] dioxus = { workspace = true } dioxus-desktop = { workspace = true } +tokio = { version = "1", features = ["full"] } diff --git a/packages/signals/examples/dependancies.rs b/packages/signals/examples/dependancies.rs new file mode 100644 index 000000000..7b744eb3c --- /dev/null +++ b/packages/signals/examples/dependancies.rs @@ -0,0 +1,38 @@ +#![allow(non_snake_case)] + +use dioxus::prelude::*; +use dioxus_signals::*; + +fn main() { + dioxus_desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + let signal = use_signal(cx, || 0); + + use_future!(cx, || async move { + loop { + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + *signal.write() += 1; + } + }); + + let local_state = use_state(cx, || 0); + let computed = + use_selector_with_dependencies(cx, (local_state.get(),), move |(local_state,)| { + local_state * 2 + signal.value() + }); + println!("Running app"); + + render! { + button { + onclick: move |_| { + local_state.set(local_state.get() + 1); + }, + "Add one" + } + div { + "{computed}" + } + } +} diff --git a/packages/signals/src/dependency.rs b/packages/signals/src/dependency.rs new file mode 100644 index 000000000..d6ab65a5f --- /dev/null +++ b/packages/signals/src/dependency.rs @@ -0,0 +1,67 @@ +/// A dependency is a trait that can be used to determine if a effect or selector should be re-run. +pub trait Dependency: Sized + Clone { + /// The output of the dependency + type Out: Clone + PartialEq; + /// Returns the output of the dependency. + fn out(&self) -> Self::Out; + /// Returns true if the dependency has changed. + fn changed(&self, other: &Self::Out) -> bool { + self.out() != *other + } +} + +impl Dependency for () { + type Out = (); + fn out(&self) -> Self::Out {} +} + +/// A dependency is a trait that can be used to determine if a effect or selector should be re-run. +pub trait Dep: 'static + PartialEq + Clone {} +impl Dep for T where T: 'static + PartialEq + Clone {} + +impl Dependency for &A { + type Out = A; + fn out(&self) -> Self::Out { + (*self).clone() + } +} + +macro_rules! impl_dep { + ( + $($el:ident=$name:ident $other:ident,)* + ) => { + impl< $($el),* > Dependency for ($(&$el,)*) + where + $( + $el: Dep + ),* + { + type Out = ($($el,)*); + + fn out(&self) -> Self::Out { + let ($($name,)*) = self; + ($((*$name).clone(),)*) + } + + fn changed(&self, other: &Self::Out) -> bool { + let ($($name,)*) = self; + let ($($other,)*) = other; + $( + if *$name != $other { + return true; + } + )* + false + } + } + }; +} + +impl_dep!(A = a1 a2,); +impl_dep!(A = a1 a2, B = b1 b2,); +impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2,); +impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2,); +impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2,); +impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2,); +impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2, G = g1 g2,); +impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2, G = g1 g2, H = h1 h2,); diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs index be57f5cfd..fdceb5211 100644 --- a/packages/signals/src/effect.rs +++ b/packages/signals/src/effect.rs @@ -1,9 +1,12 @@ use core::{self, fmt::Debug}; use std::fmt::{self, Formatter}; +use std::marker::PhantomData; use dioxus_core::prelude::*; -use crate::CopyValue; +use crate::dependency::Dep; +use crate::{dependency::Dependency, CopyValue}; +use crate::{use_signal, Signal}; #[derive(Default, Clone, Copy)] pub(crate) struct EffectStack { @@ -26,6 +29,28 @@ pub fn use_effect(cx: &ScopeState, callback: impl FnMut() + 'static) { cx.use_hook(|| Effect::new(callback)); } +/// Create a new effect. The effect will be run immediately and whenever any signal it reads changes. +/// The signal will be owned by the current component and will be dropped when the component is dropped. +pub fn use_effect_with_dependencies( + cx: &ScopeState, + dependencies: D, + mut callback: impl FnMut(D::Out) + 'static, +) where + D::Out: 'static, +{ + let dependencies_signal = use_signal(cx, || dependencies.out()); + cx.use_hook(|| { + Effect::new(move || { + let deref = &*dependencies_signal.read(); + callback(deref.clone()); + }); + }); + let changed = { dependencies.changed(&*dependencies_signal.read()) }; + if changed { + dependencies_signal.set(dependencies.out()); + } +} + /// Effects allow you to run code when a signal changes. Effects are run immediately and whenever any signal it reads changes. #[derive(Copy, Clone, PartialEq)] pub struct Effect { diff --git a/packages/signals/src/lib.rs b/packages/signals/src/lib.rs index 1c67ab462..1f8bc3297 100644 --- a/packages/signals/src/lib.rs +++ b/packages/signals/src/lib.rs @@ -10,3 +10,5 @@ mod selector; pub use selector::*; pub(crate) mod signal; pub use signal::*; +mod dependency; +pub use dependency::*; diff --git a/packages/signals/src/selector.rs b/packages/signals/src/selector.rs index 79a8f679b..81fb50398 100644 --- a/packages/signals/src/selector.rs +++ b/packages/signals/src/selector.rs @@ -1,5 +1,7 @@ use dioxus_core::prelude::*; +use crate::dependency::Dependency; +use crate::use_signal; use crate::{get_effect_stack, signal::SignalData, CopyValue, Effect, ReadOnlySignal, Signal}; /// Creates a new Selector. The selector will be run immediately and whenever any signal it reads changes. @@ -26,6 +28,44 @@ pub fn use_selector( *cx.use_hook(|| selector(f)) } +/// Creates a new Selector with some local dependencies. The selector will be run immediately and whenever any signal it reads or any dependencies it tracks changes +/// +/// Selectors can be used to efficiently compute derived data from signals. +/// +/// ```rust +/// use dioxus::prelude::*; +/// use dioxus_signals::*; +/// +/// fn App(cx: Scope) -> Element { +/// let mut local_state = use_state(cx, || 0); +/// let double = use_selector_with_dependencies(cx, (local_state.get(),), move |(local_state,)| local_state * 2); +/// local_state.set(1); +/// +/// render! { "{double}" } +/// } +/// ``` +pub fn use_selector_with_dependencies( + cx: &ScopeState, + dependencies: D, + mut f: impl FnMut(D::Out) -> R + 'static, +) -> ReadOnlySignal +where + D::Out: 'static, +{ + let dependencies_signal = use_signal(cx, || dependencies.out()); + let selector = *cx.use_hook(|| { + selector(move || { + let deref = &*dependencies_signal.read(); + f(deref.clone()) + }) + }); + let changed = { dependencies.changed(&*dependencies_signal.read()) }; + if changed { + dependencies_signal.set(dependencies.out()); + } + selector +} + /// Creates a new Selector. The selector will be run immediately and whenever any signal it reads changes. /// /// Selectors can be used to efficiently compute derived data from signals. From ba7a663eb65c0dcee8c04ddd44f8bdb7096535ca Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 8 Aug 2023 13:18:15 -0700 Subject: [PATCH 33/39] fix some ownership issues --- packages/core/src/scope_context.rs | 14 ++++++-------- packages/signals/src/effect.rs | 18 +++++++++--------- packages/signals/src/rt.rs | 6 +++--- packages/signals/src/selector.rs | 4 ++-- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index fec34f914..0861d063f 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -5,7 +5,7 @@ use crate::{ }; use rustc_hash::FxHashSet; use std::{ - any::{Any, TypeId}, + any::Any, cell::{Cell, RefCell}, fmt::Debug, future::Future, @@ -25,7 +25,7 @@ pub struct ScopeContext { pub(crate) height: u32, pub(crate) suspended: Cell, - pub(crate) shared_contexts: RefCell)>>, + pub(crate) shared_contexts: RefCell>>, pub(crate) tasks: Rc, pub(crate) spawned_tasks: RefCell>, @@ -99,9 +99,7 @@ impl ScopeContext { self.shared_contexts .borrow() .iter() - .find(|(k, _)| *k == TypeId::of::()) - .map(|(_, v)| v)? - .downcast_ref::() + .find_map(|any| any.downcast_ref::()) .cloned() } @@ -121,7 +119,7 @@ impl ScopeContext { .shared_contexts .borrow() .iter() - .find_map(|(_, any)| any.downcast_ref::()) + .find_map(|any| any.downcast_ref::()) { return Some(shared.clone()); } @@ -159,14 +157,14 @@ impl ScopeContext { // 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::() { + if let Some(ctx) = ctx.downcast_mut::() { std::mem::swap(ctx, &mut value.clone()); return value; } } // Else, just push it - contexts.push((TypeId::of::(), Box::new(value.clone()))); + contexts.push(Box::new(value.clone())); value } diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs index fdceb5211..0685938a0 100644 --- a/packages/signals/src/effect.rs +++ b/packages/signals/src/effect.rs @@ -1,16 +1,16 @@ use core::{self, fmt::Debug}; +use std::cell::RefCell; use std::fmt::{self, Formatter}; -use std::marker::PhantomData; - +use std::rc::Rc; +// use dioxus_core::prelude::*; -use crate::dependency::Dep; +use crate::use_signal; use crate::{dependency::Dependency, CopyValue}; -use crate::{use_signal, Signal}; -#[derive(Default, Clone, Copy)] +#[derive(Default, Clone)] pub(crate) struct EffectStack { - pub(crate) effects: CopyValue>, + pub(crate) effects: Rc>>, } pub(crate) fn get_effect_stack() -> EffectStack { @@ -65,7 +65,7 @@ impl Debug for Effect { impl Effect { pub(crate) fn current() -> Option { - get_effect_stack().effects.read().last().copied() + get_effect_stack().effects.borrow().last().copied() } /// Create a new effect. The effect will be run immediately and whenever any signal it reads changes. @@ -85,11 +85,11 @@ impl Effect { pub fn try_run(&self) { if let Some(mut callback) = self.callback.try_write() { { - get_effect_stack().effects.write().push(*self); + get_effect_stack().effects.borrow_mut().push(*self); } callback(); { - get_effect_stack().effects.write().pop(); + get_effect_stack().effects.borrow_mut().pop(); } } } diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index 685a77204..0f0b3a8c2 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -3,8 +3,8 @@ use std::cell::{Ref, RefMut}; use std::rc::Rc; use dioxus_core::prelude::{ - consume_context, consume_context_from_scope, current_scope_id, provide_context_to_scope, - provide_root_context, + consume_context, consume_context_from_scope, current_scope_id, provide_context, + provide_context_to_scope, provide_root_context, }; use dioxus_core::ScopeId; @@ -25,7 +25,7 @@ fn current_owner() -> Rc { Some(rt) => rt, None => { let owner = Rc::new(current_store().owner()); - provide_root_context(owner).expect("in a virtual dom") + provide_context(owner).expect("in a virtual dom") } } } diff --git a/packages/signals/src/selector.rs b/packages/signals/src/selector.rs index 81fb50398..301f4495e 100644 --- a/packages/signals/src/selector.rs +++ b/packages/signals/src/selector.rs @@ -78,7 +78,7 @@ pub fn selector(mut f: impl FnMut() -> R + 'static) -> ReadOnlySig }; { - get_effect_stack().effects.write().push(effect); + get_effect_stack().effects.borrow_mut().push(effect); } state.inner.value.set(SignalData { subscribers: Default::default(), @@ -87,7 +87,7 @@ pub fn selector(mut f: impl FnMut() -> R + 'static) -> ReadOnlySig value: f(), }); { - get_effect_stack().effects.write().pop(); + // get_effect_stack().effects.borrow_mut().pop(); } effect.callback.value.set(Box::new(move || { From 69dab86873a77caa8bddaecfae1e8bfafdc5e34b Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 8 Aug 2023 13:27:45 -0700 Subject: [PATCH 34/39] add selector example to readme --- packages/core/src/scope_context.rs | 2 +- packages/signals/README.md | 34 ++++++++++++++++++++++++++- packages/signals/examples/selector.rs | 30 +++++++++++++++++++++++ packages/signals/src/selector.rs | 2 +- 4 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 packages/signals/examples/selector.rs diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index 0861d063f..d627eea5f 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -245,7 +245,7 @@ impl ScopeContext { /// 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. +/// 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> { diff --git a/packages/signals/README.md b/packages/signals/README.md index baac37867..020edc18f 100644 --- a/packages/signals/README.md +++ b/packages/signals/README.md @@ -1,6 +1,6 @@ # Dioxus Signals -Dioxus Signals is an ergonomic Copy runtime for data with local subscriptions in Dioxus. +Dioxus Signals is an ergonomic Copy runtime for data with local subscriptions. ## Copy Data @@ -86,5 +86,37 @@ fn Child(cx: Scope) -> Element { "{signal}" } } +``` +## Computed Data + +In addition to local subscriptions in components, `dioxus-signals` provides a way to derive data with local subscriptions. + +The use_selector hook will only rerun when any signals inside of the hook change: + +```rust +use dioxus::prelude::*; +use dioxus_signals::*; + +fn app(cx: Scope) -> Element { + let signal = use_signal(cx, || 0); + let doubled = use_selector(cx, || signal * 2); + + render! { + button { + onclick: move |_| *signal.write() += 1, + "Increase" + } + Child { + signal: signal + } + } +} + +#[inline_props] +fn Child(cx: Scope, signal: ReadOnlySignal) -> Element { + render! { + "{signal}" + } +} ``` diff --git a/packages/signals/examples/selector.rs b/packages/signals/examples/selector.rs new file mode 100644 index 000000000..85d93ae7f --- /dev/null +++ b/packages/signals/examples/selector.rs @@ -0,0 +1,30 @@ +#![allow(non_snake_case)] + +use dioxus::prelude::*; +use dioxus_signals::*; + +fn main() { + dioxus_desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + let signal = use_signal(cx, || 0); + let doubled = use_selector(cx, move || signal * 2); + + render! { + button { + onclick: move |_| *signal.write() += 1, + "Increase" + } + Child { + signal: doubled + } + } +} + +#[inline_props] +fn Child(cx: Scope, signal: ReadOnlySignal) -> Element { + render! { + "{signal}" + } +} diff --git a/packages/signals/src/selector.rs b/packages/signals/src/selector.rs index 301f4495e..5eb3fa3c9 100644 --- a/packages/signals/src/selector.rs +++ b/packages/signals/src/selector.rs @@ -87,7 +87,7 @@ pub fn selector(mut f: impl FnMut() -> R + 'static) -> ReadOnlySig value: f(), }); { - // get_effect_stack().effects.borrow_mut().pop(); + get_effect_stack().effects.borrow_mut().pop(); } effect.callback.value.set(Box::new(move || { From 14c852010bc695c62884cffb0bc8ace70edf5fa2 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 8 Aug 2023 13:31:38 -0700 Subject: [PATCH 35/39] restore clock example --- examples/clock.rs | 59 +++++++---------------------------------------- 1 file changed, 8 insertions(+), 51 deletions(-) diff --git a/examples/clock.rs b/examples/clock.rs index 2ed4812cf..f9c1892d9 100644 --- a/examples/clock.rs +++ b/examples/clock.rs @@ -1,65 +1,22 @@ -#![allow(non_snake_case)] - use dioxus::prelude::*; -use dioxus_signals::{use_signal, Effect, Signal}; +use dioxus_signals::use_signal; fn main() { dioxus_desktop::launch(app); } fn app(cx: Scope) -> Element { - println!("running app"); - - let counts = use_signal(cx, || (0..100).map(Signal::new).collect::>()); - - cx.use_hook(|| { - Effect::new(move || { - println!("Counts: {:?}", counts); - }) - }); - - render! { - for (i, count) in counts.into_iter().enumerate() { - Child { - id: i, - count: count, - } - } - } -} - -#[derive(Props, PartialEq)] -struct ChildProps { - id: usize, - count: Signal, -} - -fn Child(cx: Scope) -> Element { - println!("running child {}", cx.props.id); - let count = cx.props.count; + let mut count = use_signal(cx, || 0); use_future!(cx, || async move { loop { - tokio::time::sleep(std::time::Duration::from_secs(count.value())).await; - *count.write() += 1; + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + count += 1; + println!("current: {count}"); } }); - render! { - div { - "Child: {count}" - button { - onclick: move |_| { - *count.write() += 1; - }, - "Increase" - } - button { - onclick: move |_| { - *count.write() -= 1; - }, - "Decrease" - } - } - } + cx.render(rsx! { + div { "High-Five counter: {count}" } + }) } From 4ee4cf23d3fd64839b9e0080eddf4d6fe6a43a79 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 8 Aug 2023 13:37:29 -0700 Subject: [PATCH 36/39] restore a few unneeded breaking changes --- packages/core/src/events.rs | 2 +- packages/core/src/runtime.rs | 6 +- packages/core/src/scope_context.rs | 2 +- packages/core/src/scopes.rs | 2 +- packages/hooks/src/computed.rs | 210 +++++++++++++++++++++++++++++ packages/hooks/src/lib.rs | 3 + 6 files changed, 219 insertions(+), 6 deletions(-) create mode 100644 packages/hooks/src/computed.rs diff --git a/packages/core/src/events.rs b/packages/core/src/events.rs index 90511a8e6..b85e0394d 100644 --- a/packages/core/src/events.rs +++ b/packages/core/src/events.rs @@ -135,7 +135,7 @@ impl std::fmt::Debug for Event { /// } /// /// ``` -pub struct EventHandler<'bump, T: ?Sized = ()> { +pub struct EventHandler<'bump, T = ()> { pub(crate) origin: ScopeId, pub(super) callback: RefCell>>, } diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs index 9f031f287..256b46909 100644 --- a/packages/core/src/runtime.rs +++ b/packages/core/src/runtime.rs @@ -41,7 +41,7 @@ where .flatten() } -pub struct Runtime { +pub(crate) struct Runtime { pub(crate) scope_contexts: RefCell>>, pub(crate) scheduler: Rc, @@ -93,10 +93,10 @@ impl Runtime { } } -pub struct RuntimeGuard(Rc); +pub(crate) struct RuntimeGuard(Rc); impl RuntimeGuard { - pub fn new(runtime: Rc) -> Self { + pub(crate) fn new(runtime: Rc) -> Self { push_runtime(runtime.clone()); Self(runtime) } diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index d627eea5f..14366eefb 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -16,7 +16,7 @@ use std::{ /// 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 ScopeContext { +pub(crate) struct ScopeContext { pub(crate) name: &'static str, pub(crate) id: ScopeId, diff --git a/packages/core/src/scopes.rs b/packages/core/src/scopes.rs index f255c4175..8469781c4 100644 --- a/packages/core/src/scopes.rs +++ b/packages/core/src/scopes.rs @@ -195,7 +195,7 @@ impl<'src> ScopeState { /// /// assert_eq!(base.parent(), None); /// ``` - pub fn parent_id(&self) -> Option { + pub fn parent(&self) -> Option { // safety: the pointer to our parent is *always* valid thanks to the bump arena self.context().parent_id() } diff --git a/packages/hooks/src/computed.rs b/packages/hooks/src/computed.rs new file mode 100644 index 000000000..94011d37d --- /dev/null +++ b/packages/hooks/src/computed.rs @@ -0,0 +1,210 @@ +use dioxus_core::{ScopeId, ScopeState}; +use slab::Slab; +use std::{ + cell::{RefCell, RefMut}, + collections::HashSet, + ops::{Deref, DerefMut}, + rc::Rc, +}; + +/// Create a new tracked state. +/// Tracked state is state that can drive Selector state +/// +/// It will efficiently update any Selector state that is reading from it, but it is not readable on its own. +/// +/// ```rust +/// use dioxus::prelude::*; +/// +/// fn Parent(cx: Scope) -> Element { +/// let count = use_tracked_state(cx, || 0); +/// +/// render! { +/// Child { +/// count: count.clone(), +/// } +/// } +/// } +/// +/// #[inline_props] +/// fn Child(cx: Scope, count: Tracked) -> Element { +/// let less_than_five = use_selector(cx, count, |count| *count < 5); +/// +/// render! { +/// "{less_than_five}" +/// } +/// } +/// ``` +pub fn use_tracked_state(cx: &ScopeState, init: impl FnOnce() -> T) -> &Tracked { + cx.use_hook(|| { + let init = init(); + Tracked::new(cx, init) + }) +} + +/// Tracked state is state that can drive Selector state +/// +/// Tracked state will efficiently update any Selector state that is reading from it, but it is not readable on it's own. +#[derive(Clone)] +pub struct Tracked { + state: Rc>, + update_any: std::sync::Arc, + subscribers: SubscribedCallbacks, +} + +impl PartialEq for Tracked { + fn eq(&self, other: &Self) -> bool { + self.state == other.state + } +} + +impl Tracked { + /// Create a new tracked state + pub fn new(cx: &ScopeState, state: I) -> Self { + let subscribers = std::rc::Rc::new(std::cell::RefCell::new(Slab::new())); + Self { + state: Rc::new(RefCell::new(state)), + subscribers, + update_any: cx.schedule_update_any(), + } + } + + /// Create a new Selector state from this tracked state + pub fn compute( + &self, + mut compute: impl FnMut(&I) -> O + 'static, + ) -> Selector { + let subscribers = Rc::new(RefCell::new(HashSet::new())); + let state = Rc::new(RefCell::new(compute(&self.state.borrow()))); + let update_any = self.update_any.clone(); + + Selector { + value: state.clone(), + subscribers: subscribers.clone(), + _tracker: Rc::new(self.track(move |input_state| { + let new = compute(input_state); + let different = { + let state = state.borrow(); + *state != new + }; + if different { + let mut state = state.borrow_mut(); + *state = new; + for id in subscribers.borrow().iter().copied() { + (update_any)(id); + } + } + })), + } + } + + pub(crate) fn track(&self, update: impl FnMut(&I) + 'static) -> Tracker { + let mut subscribers = self.subscribers.borrow_mut(); + let id = subscribers.insert(Box::new(update)); + Tracker { + subscribers: self.subscribers.clone(), + id, + } + } + + /// Write to the tracked state + pub fn write(&self) -> TrackedMut<'_, I> { + TrackedMut { + state: self.state.borrow_mut(), + subscribers: self.subscribers.clone(), + } + } +} + +/// A mutable reference to tracked state +pub struct TrackedMut<'a, I> { + state: RefMut<'a, I>, + subscribers: SubscribedCallbacks, +} + +impl<'a, I> Deref for TrackedMut<'a, I> { + type Target = I; + + fn deref(&self) -> &Self::Target { + &self.state + } +} + +impl<'a, I> DerefMut for TrackedMut<'a, I> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.state + } +} + +impl<'a, I> Drop for TrackedMut<'a, I> { + fn drop(&mut self) { + let state = self.state.deref(); + for (_, sub) in &mut *self.subscribers.borrow_mut() { + sub(state); + } + } +} + +type SubscribedCallbacks = std::rc::Rc>>>; + +pub(crate) struct Tracker { + subscribers: SubscribedCallbacks, + id: usize, +} + +impl Drop for Tracker { + fn drop(&mut self) { + let _ = self.subscribers.borrow_mut().remove(self.id); + } +} + +pub fn use_selector( + cx: &ScopeState, + tracked: &Tracked, + init: impl FnMut(&I) -> O + 'static, +) -> O { + let selector = cx.use_hook(|| tracked.compute(init)); + selector.use_state(cx) +} + +/// Selector state is state that is derived from tracked state +/// +/// Whenever the tracked state changes, the Selector state will be updated and any components reading from it will be rerun +#[derive(Clone)] +pub struct Selector { + _tracker: Rc>, + value: Rc>, + subscribers: Rc>>, +} + +impl PartialEq for Selector { + fn eq(&self, other: &Self) -> bool { + std::rc::Rc::ptr_eq(&self.value, &other.value) + } +} + +impl Selector { + /// Read the Selector state and subscribe to updates + pub fn use_state(&self, cx: &ScopeState) -> T { + cx.use_hook(|| { + let id = cx.scope_id(); + self.subscribers.borrow_mut().insert(id); + + ComputedRead { + scope: cx.scope_id(), + subscribers: self.subscribers.clone(), + } + }); + self.value.borrow().clone() + } +} + +struct ComputedRead { + scope: ScopeId, + subscribers: std::rc::Rc>>, +} + +impl Drop for ComputedRead { + fn drop(&mut self) { + self.subscribers.borrow_mut().remove(&self.scope); + } +} diff --git a/packages/hooks/src/lib.rs b/packages/hooks/src/lib.rs index 65f390eda..7e5798167 100644 --- a/packages/hooks/src/lib.rs +++ b/packages/hooks/src/lib.rs @@ -52,6 +52,9 @@ macro_rules! to_owned { }; } +mod computed; +pub use computed::*; + mod use_on_unmount; pub use use_on_unmount::*; From 24c626b30660c42c64b6ec4aa9e5f1c7faf0f6ab Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 8 Aug 2023 13:43:57 -0700 Subject: [PATCH 37/39] fix clippy --- packages/core/src/runtime.rs | 9 ++++----- packages/desktop/src/protocol.rs | 9 +++++++-- packages/dioxus-tui/examples/hover.rs | 8 +++++++- packages/hooks/src/computed.rs | 2 ++ packages/hooks/src/lib.rs | 3 +-- packages/html/src/eval.rs | 2 +- packages/native-core/src/real_dom.rs | 1 - packages/rsx/src/lib.rs | 10 ++-------- packages/signals/src/signal.rs | 13 ++++++------- 9 files changed, 30 insertions(+), 27 deletions(-) diff --git a/packages/core/src/runtime.rs b/packages/core/src/runtime.rs index 256b46909..b2b535830 100644 --- a/packages/core/src/runtime.rs +++ b/packages/core/src/runtime.rs @@ -24,7 +24,7 @@ where { RUNTIMES.with(|stack| { let stack = stack.borrow(); - stack.last().map(|r| f(&**r)) + stack.last().map(|r| f(r)) }) } @@ -36,7 +36,7 @@ where with_runtime(|runtime| { runtime .current_scope_id() - .and_then(|scope| runtime.get_context(scope).map(|sc| f(&*sc))) + .and_then(|scope| runtime.get_context(scope).map(|sc| f(&sc))) }) .flatten() } @@ -52,7 +52,7 @@ pub(crate) struct Runtime { impl Runtime { pub(crate) fn new(scheduler: Rc) -> Rc { - let runtime = Rc::new(Self { + Rc::new(Self { scheduler, scope_contexts: Default::default(), @@ -60,8 +60,7 @@ impl Runtime { scope_stack: Default::default(), rendering: Cell::new(true), - }); - runtime + }) } /// Create a scope context. This slab is synchronized with the scope slab. diff --git a/packages/desktop/src/protocol.rs b/packages/desktop/src/protocol.rs index 89ce50a48..53652f82f 100644 --- a/packages/desktop/src/protocol.rs +++ b/packages/desktop/src/protocol.rs @@ -158,8 +158,13 @@ fn get_mime_from_path(trimmed: &Path) -> Result<&'static str> { } let res = match infer::get_from_path(trimmed)?.map(|f| f.mime_type()) { - Some(t) if t == "text/plain" => get_mime_by_ext(trimmed), - Some(f) => f, + Some(f) => { + if f == "text/plain" { + get_mime_by_ext(trimmed) + } else { + f + } + } None => get_mime_by_ext(trimmed), }; diff --git a/packages/dioxus-tui/examples/hover.rs b/packages/dioxus-tui/examples/hover.rs index 77770b46d..c8784a8bc 100644 --- a/packages/dioxus-tui/examples/hover.rs +++ b/packages/dioxus-tui/examples/hover.rs @@ -1,6 +1,7 @@ use dioxus::{events::MouseData, prelude::*}; use dioxus_core::Event; use std::convert::TryInto; +use std::fmt::Write; use std::rc::Rc; fn main() { @@ -9,7 +10,12 @@ fn main() { fn app(cx: Scope) -> Element { fn to_str(c: &[i32; 3]) -> String { - "#".to_string() + &c.iter().map(|c| format!("{c:02X?}")).collect::() + let mut result = String::new(); + result += "#"; + for c in c.iter() { + write!(string, "{c:02X?}").unwrap(); + } + result } fn get_brightness(m: &Rc) -> i32 { diff --git a/packages/hooks/src/computed.rs b/packages/hooks/src/computed.rs index 94011d37d..1fcad8bb0 100644 --- a/packages/hooks/src/computed.rs +++ b/packages/hooks/src/computed.rs @@ -1,3 +1,5 @@ +//! Tracked and computed state in Dioxus + use dioxus_core::{ScopeId, ScopeState}; use slab::Slab; use std::{ diff --git a/packages/hooks/src/lib.rs b/packages/hooks/src/lib.rs index 7e5798167..6d7ab6f53 100644 --- a/packages/hooks/src/lib.rs +++ b/packages/hooks/src/lib.rs @@ -52,8 +52,7 @@ macro_rules! to_owned { }; } -mod computed; -pub use computed::*; +pub mod computed; mod use_on_unmount; pub use use_on_unmount::*; diff --git a/packages/html/src/eval.rs b/packages/html/src/eval.rs index b39eef805..c90f5125b 100644 --- a/packages/html/src/eval.rs +++ b/packages/html/src/eval.rs @@ -42,7 +42,7 @@ pub fn use_eval(cx: &ScopeState) -> &EvalCreator { Rc::new(move |script: &str| { eval_provider .new_evaluator(script.to_string()) - .map(|evaluator| UseEval::new(evaluator)) + .map(UseEval::new) }) as Rc Result> }) } diff --git a/packages/native-core/src/real_dom.rs b/packages/native-core/src/real_dom.rs index 44c378ddf..b520b2de1 100644 --- a/packages/native-core/src/real_dom.rs +++ b/packages/native-core/src/real_dom.rs @@ -446,7 +446,6 @@ impl RealDom { drop(tree); children.reverse(); if let Some(node) = self.get_mut(id) { - let node = node; f(node); stack.extend(children.iter()); } diff --git a/packages/rsx/src/lib.rs b/packages/rsx/src/lib.rs index 1f01fcd72..783dd3322 100644 --- a/packages/rsx/src/lib.rs +++ b/packages/rsx/src/lib.rs @@ -288,10 +288,7 @@ impl DynamicMapping { let idx = self.last_attribute_idx; self.last_attribute_idx += 1; - self.attribute_to_idx - .entry(attr) - .or_insert_with(Vec::new) - .push(idx); + self.attribute_to_idx.entry(attr).or_default().push(idx); idx } @@ -300,10 +297,7 @@ impl DynamicMapping { let idx = self.last_element_idx; self.last_element_idx += 1; - self.node_to_idx - .entry(node) - .or_insert_with(Vec::new) - .push(idx); + self.node_to_idx.entry(node).or_default().push(idx); idx } diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 2bac8e1ea..5d696ee17 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -50,9 +50,11 @@ pub fn use_signal(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal< #[derive(Clone)] struct Unsubscriber { scope: ScopeId, - subscribers: Rc>>>>>, + subscribers: UnsubscriberArray, } +type UnsubscriberArray = Rc>>>>>; + impl Drop for Unsubscriber { fn drop(&mut self) { for subscribers in self.subscribers.borrow().iter() { @@ -269,10 +271,7 @@ impl<'a, T: 'static, I: 'static> Write<'a, T, I> { ) -> Option> { let Self { write, signal } = myself; let write = RefMut::filter_map(write, f).ok(); - write.map(|write| Write { - write, - signal: signal, - }) + write.map(|write| Write { write, signal }) } } @@ -280,13 +279,13 @@ impl<'a, T: 'static> Deref for Write<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { - &*self.write + &self.write } } impl DerefMut for Write<'_, T> { fn deref_mut(&mut self) -> &mut Self::Target { - &mut *self.write + &mut self.write } } From 3f31b9de43ee33187f530e49c87fab97a80e9876 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 8 Aug 2023 15:13:02 -0700 Subject: [PATCH 38/39] fix tests --- packages/dioxus-tui/examples/hover.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/dioxus-tui/examples/hover.rs b/packages/dioxus-tui/examples/hover.rs index c8784a8bc..3af2d1616 100644 --- a/packages/dioxus-tui/examples/hover.rs +++ b/packages/dioxus-tui/examples/hover.rs @@ -13,7 +13,7 @@ fn app(cx: Scope) -> Element { let mut result = String::new(); result += "#"; for c in c.iter() { - write!(string, "{c:02X?}").unwrap(); + write!(result, "{c:02X?}").unwrap(); } result } From 18d255deccfa36648af8e1c5c30dd2106ffd6dc4 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 10 Aug 2023 17:17:25 -0700 Subject: [PATCH 39/39] add serde feature to signals --- packages/signals/Cargo.toml | 5 +++++ packages/signals/src/rt.rs | 22 ++++++++++++++++++++++ packages/signals/src/signal.rs | 14 ++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index 2c24758b5..0017a1545 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -11,8 +11,13 @@ dioxus-core = { workspace = true } generational-box = { workspace = true } log.workspace = true simple_logger = "4.2.0" +serde = { version = "1", features = ["derive"], optional = true } [dev-dependencies] dioxus = { workspace = true } dioxus-desktop = { workspace = true } tokio = { version = "1", features = ["full"] } + +[features] +default = [] +serialize = ["serde"] \ No newline at end of file diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index 0f0b3a8c2..7322d43b4 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -48,6 +48,28 @@ pub struct CopyValue { origin_scope: ScopeId, } +#[cfg(feature = "serde")] +impl serde::Serialize for CopyValue +where + T: serde::Serialize, +{ + fn serialize(&self, serializer: S) -> Result { + self.value.read().serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl<'de, T: 'static> serde::Deserialize<'de> for CopyValue +where + T: serde::Deserialize<'de>, +{ + fn deserialize>(deserializer: D) -> Result { + let value = T::deserialize(deserializer)?; + + Ok(Self::new(value)) + } +} + impl CopyValue { /// Create a new CopyValue. The value will be stored in the current component. /// diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 5d696ee17..a5599a1ce 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -118,6 +118,20 @@ pub struct Signal { pub(crate) inner: CopyValue>, } +#[cfg(feature = "serde")] +impl serde::Serialize for Signal { + fn serialize(&self, serializer: S) -> Result { + self.read().serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl<'de, T: serde::Deserialize<'de> + 'static> serde::Deserialize<'de> for Signal { + fn deserialize>(deserializer: D) -> Result { + Ok(Self::new(T::deserialize(deserializer)?)) + } +} + impl Signal { /// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking. pub fn new(value: T) -> Self {