make the signal runtime global

This commit is contained in:
Evan Almloff committed 2023-10-30 14:25:31 -05:00
1 parent 4ac6aed482
commit 90e04edcdf
8 files changed
+409 -260

No files matched your search

+3 -2
View File
@@ -2,13 +2,14 @@ use core::{self, fmt::Debug};
use std::fmt::{self, Formatter};
//
use dioxus_core::prelude::*;
use generational_box::SyncStorage;
use crate::use_signal;
use crate::{dependency::Dependency, CopyValue};
#[derive(Copy, Clone, PartialEq)]
pub(crate) struct EffectStack {
pub(crate) effects: CopyValue<Vec<Effect>>,
pub(crate) effects: CopyValue<Vec<Effect>, SyncStorage>,
}
impl Default for EffectStack {
@@ -68,7 +69,7 @@ pub fn use_effect_with_dependencies<D: Dependency>(
#[derive(Copy, Clone, PartialEq)]
pub struct Effect {
pub(crate) source: ScopeId,
pub(crate) callback: CopyValue<Box<dyn FnMut()>>,
pub(crate) callback: CopyValue<Box<dyn FnMut()>, SyncStorage>,
pub(crate) effect_stack: EffectStack,
}
+39 -25
View File
@@ -1,5 +1,7 @@
use crate::rt::CopyValue;
use crate::signal::{ReadOnlySignal, Signal, Write};
use crate::SignalData;
use generational_box::{MappableMut, Storage};
use parking_lot::{MappedRwLockReadGuard, MappedRwLockWriteGuard};
use std::{
@@ -203,19 +205,19 @@ macro_rules! write_impls {
};
}
read_impls!(CopyValue);
write_impls!(CopyValue);
read_impls!(Signal);
write_impls!(Signal);
read_impls!(ReadOnlySignal);
// read_impls!(CopyValue);
// write_impls!(CopyValue);
// read_impls!(Signal);
// write_impls!(Signal);
// read_impls!(ReadOnlySignal);
/// An iterator over the values of a `CopyValue<Vec<T>>`.
pub struct CopyValueIterator<T: 'static> {
pub struct CopyValueIterator<T: 'static, S: Storage<T>> {
index: usize,
value: CopyValue<Vec<T>>,
value: CopyValue<Vec<T>, S>,
}
impl<T: Clone> Iterator for CopyValueIterator<T> {
impl<T: Clone, S: Storage<T>> Iterator for CopyValueIterator<T, S> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
@@ -225,8 +227,8 @@ impl<T: Clone> Iterator for CopyValueIterator<T> {
}
}
impl<T: Clone + 'static> IntoIterator for CopyValue<Vec<T>> {
type IntoIter = CopyValueIterator<T>;
impl<T: Clone + 'static, S: Storage<T>> IntoIterator for CopyValue<Vec<T>, S> {
type IntoIter = CopyValueIterator<T, S>;
type Item = T;
@@ -238,27 +240,33 @@ impl<T: Clone + 'static> IntoIterator for CopyValue<Vec<T>> {
}
}
impl<T: 'static> CopyValue<Vec<T>> {
impl<T: 'static, S: Storage<Vec<T>>> CopyValue<Vec<T>, S>
where
<S as Storage<Vec<T>>>::Mut: MappableMut<Vec<T>, T>,
{
/// Write to an element in the inner vector.
pub fn get_mut(&self, index: usize) -> Option<MappedRwLockWriteGuard<'static, T>> {
pub fn get_mut(&self, index: usize) -> Option<<S::Mut as MappableMut<Vec<T>, T>>::Mapped> {
MappedRwLockWriteGuard::try_map(self.write(), |v| v.get_mut(index)).ok()
}
}
impl<T: 'static> CopyValue<Option<T>> {
impl<T: 'static, S: Storage<Option<T>>> CopyValue<Option<T>, S>
where
<S as Storage<Option<T>>>::Mut: MappableMut<Option<T>, T>,
{
/// Deref the inner value mutably.
pub fn as_mut(&self) -> Option<MappedRwLockWriteGuard<'static, T>> {
MappedRwLockWriteGuard::try_map(self.write(), |v| v.as_mut()).ok()
pub fn as_mut(&self) -> Option<<S::Mut as MappableMut<Option<T>, T>>::Mapped> {
S::Mut::map(self.try_write(), |v| v.as_mut()).ok()
}
}
/// An iterator over items in a `Signal<Vec<T>>`.
pub struct SignalIterator<T: 'static> {
pub struct SignalIterator<T: 'static, S: Storage<T>> {
index: usize,
value: Signal<Vec<T>>,
value: Signal<Vec<T>, S>,
}
impl<T: Clone> Iterator for SignalIterator<T> {
impl<T: Clone, S: Storage<T>> Iterator for SignalIterator<T, S> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
@@ -268,8 +276,8 @@ impl<T: Clone> Iterator for SignalIterator<T> {
}
}
impl<T: Clone + 'static> IntoIterator for Signal<Vec<T>> {
type IntoIter = SignalIterator<T>;
impl<T: Clone + 'static, S: Storage<T>> IntoIterator for Signal<Vec<T>, S> {
type IntoIter = SignalIterator<T, S>;
type Item = T;
@@ -281,16 +289,22 @@ impl<T: Clone + 'static> IntoIterator for Signal<Vec<T>> {
}
}
impl<T: 'static> Signal<Vec<T>> {
impl<T: 'static, S: Storage<SignalData<Vec<T>>>> Signal<Vec<T>, S>
where
S::Mut: MappableMut<Vec<T>, T>,
{
/// Returns a reference to an element or `None` if out of bounds.
pub fn get_mut(&self, index: usize) -> Option<Write<T, Vec<T>>> {
Write::filter_map(self.write(), |v| v.get_mut(index))
pub fn get_mut(
&self,
index: usize,
) -> Option<Write<T, <S::Mut as MappableMut<Vec<T>, T>>::Mapped, S, Vec<T>>> {
S::Mut::map(self.write(), |v| v.get_mut(index))
}
}
impl<T: 'static> Signal<Option<T>> {
impl<T: 'static, S: Storage<SignalData<Option<T>>>> Signal<Option<T>, S> {
/// Returns a reference to an element or `None` if out of bounds.
pub fn as_mut(&self) -> Option<Write<T, Option<T>>> {
pub fn as_mut(&self) -> Option<Write<SignalData<Option<T>>, S::Mut, S, Option<T>>> {
Write::filter_map(self.write(), |v| v.as_mut())
}
}
+22 -25
View File
@@ -5,23 +5,12 @@ use std::rc::Rc;
use dioxus_core::prelude::*;
use dioxus_core::ScopeId;
use generational_box::{GenerationalBox, Owner, Store};
use parking_lot::{MappedRwLockReadGuard, MappedRwLockWriteGuard};
use generational_box::AnyStorage;
use generational_box::Storage;
use generational_box::{GenerationalBox, Owner};
use crate::Effect;
static STORE: once_cell::sync::Lazy<Store> = once_cell::sync::Lazy::new(Store::default);
fn current_store() -> Store {
match consume_context() {
Some(rt) => rt,
None => {
let store = Store::default();
provide_root_context(store).expect("in a virtual dom")
}
}
}
fn current_owner() -> Rc<Owner> {
match Effect::current() {
// If we are inside of an effect, we should use the owner of the effect as the owner of the value.
@@ -50,14 +39,22 @@ fn owner_in_scope(scope: ScopeId) -> Rc<Owner> {
}
}
#[derive(Debug)]
/// 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<T: 'static> {
pub(crate) value: GenerationalBox<T>,
pub struct CopyValue<T: 'static, S: AnyStorage> {
pub(crate) value: GenerationalBox<T, S>,
origin_scope: ScopeId,
}
impl<T: 'static, S: AnyStorage + Copy> Copy for CopyValue<T, S> {}
impl<T: 'static, S: AnyStorage + Clone> Clone for CopyValue<T, S> {
fn clone(&self) -> Self {
*self
}
}
#[cfg(feature = "serde")]
impl<T: 'static> serde::Serialize for CopyValue<T>
where
@@ -80,7 +77,7 @@ where
}
}
impl<T: 'static> CopyValue<T> {
impl<T: 'static, S: Storage<T>> CopyValue<T, S> {
/// 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.
@@ -118,22 +115,22 @@ impl<T: 'static> CopyValue<T> {
}
/// Try to read the value. If the value has been dropped, this will return None.
pub fn try_read(&self) -> Option<MappedRwLockReadGuard<'static, T>> {
pub fn try_read(&self) -> Option<S::Ref> {
self.value.try_read()
}
/// Read the value. If the value has been dropped, this will panic.
pub fn read(&self) -> MappedRwLockReadGuard<'static, T> {
pub fn read(&self) -> S::Ref {
self.value.read()
}
/// Try to write the value. If the value has been dropped, this will return None.
pub fn try_write(&self) -> Option<MappedRwLockWriteGuard<'static, T>> {
pub fn try_write(&self) -> Option<S::Mut> {
self.value.try_write()
}
/// Write the value. If the value has been dropped, this will panic.
pub fn write(&self) -> MappedRwLockWriteGuard<'static, T> {
pub fn write(&self) -> S::Mut {
self.value.write()
}
@@ -155,21 +152,21 @@ impl<T: 'static> CopyValue<T> {
}
}
impl<T: Clone + 'static> CopyValue<T> {
impl<T: Clone + 'static, S: Storage<T>> CopyValue<T, S> {
/// Get the value. If the value has been dropped, this will panic.
pub fn value(&self) -> T {
self.read().clone()
}
}
impl<T: 'static> PartialEq for CopyValue<T> {
impl<T: 'static, S: Storage<T>> PartialEq for CopyValue<T, S> {
fn eq(&self, other: &Self) -> bool {
self.value.ptr_eq(&other.value)
}
}
impl<T> Deref for CopyValue<T> {
type Target = dyn Fn() -> MappedRwLockReadGuard<'static, T>;
impl<T, S: Storage<T>> Deref for CopyValue<T, S> {
type Target = dyn Fn() -> S::Ref;
fn deref(&self) -> &Self::Target {
// https://github.com/dtolnay/case-studies/tree/master/callable-types
+8 -5
View File
@@ -1,4 +1,5 @@
use dioxus_core::prelude::*;
use generational_box::Storage;
use crate::dependency::Dependency;
use crate::use_signal;
@@ -22,10 +23,10 @@ use crate::{get_effect_stack, signal::SignalData, CopyValue, Effect, ReadOnlySig
/// }
/// ```
#[must_use = "Consider using `use_effect` to rerun a callback when dependencies change"]
pub fn use_selector<R: PartialEq>(
pub fn use_selector<R: PartialEq, S: Storage<SignalData<R>>>(
cx: &ScopeState,
f: impl FnMut() -> R + 'static,
) -> ReadOnlySignal<R> {
) -> ReadOnlySignal<R, S> {
*cx.use_hook(|| selector(f))
}
@@ -46,11 +47,11 @@ pub fn use_selector<R: PartialEq>(
/// }
/// ```
#[must_use = "Consider using `use_effect` to rerun a callback when dependencies change"]
pub fn use_selector_with_dependencies<R: PartialEq, D: Dependency>(
pub fn use_selector_with_dependencies<R: PartialEq, D: Dependency, S: Storage<SignalData<R>>>(
cx: &ScopeState,
dependencies: D,
mut f: impl FnMut(D::Out) -> R + 'static,
) -> ReadOnlySignal<R>
) -> ReadOnlySignal<R, S>
where
D::Out: 'static,
{
@@ -71,7 +72,9 @@ where
/// 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<R: PartialEq>(mut f: impl FnMut() -> R + 'static) -> ReadOnlySignal<R> {
pub fn selector<R: PartialEq, S: Storage<SignalData<R>>>(
mut f: impl FnMut() -> R + 'static,
) -> ReadOnlySignal<R, S> {
let state = Signal::<R> {
inner: CopyValue::invalid(),
};
+53 -33
View File
@@ -10,6 +10,7 @@ use dioxus_core::{
prelude::{current_scope_id, has_context, provide_context, schedule_update_any},
ScopeId, ScopeState,
};
use generational_box::{AnyStorage, Mappable, MappableMut, Storage};
use parking_lot::{MappedRwLockReadGuard, MappedRwLockWriteGuard};
use crate::{get_effect_stack, CopyValue, Effect, EffectStack};
@@ -46,7 +47,10 @@ use crate::{get_effect_stack, CopyValue, Effect, EffectStack};
/// }
/// ```
#[must_use]
pub fn use_signal<T: 'static>(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal<T> {
pub fn use_signal<T: 'static, S: Storage<SignalData<T>>>(
cx: &ScopeState,
f: impl FnOnce() -> T,
) -> Signal<T, S> {
*cx.use_hook(|| Signal::new(f()))
}
@@ -119,8 +123,8 @@ pub(crate) struct SignalData<T> {
/// }
/// }
/// ```
pub struct Signal<T: 'static> {
pub(crate) inner: CopyValue<SignalData<T>>,
pub struct Signal<T: 'static, S: AnyStorage> {
pub(crate) inner: CopyValue<SignalData<T>, S>,
}
#[cfg(feature = "serde")]
@@ -137,7 +141,7 @@ impl<'de, T: serde::Deserialize<'de> + 'static> serde::Deserialize<'de> for Sign
}
}
impl<T: 'static> Signal<T> {
impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
pub fn new(value: T) -> Self {
Self {
@@ -174,7 +178,10 @@ impl<T: 'static> Signal<T> {
/// 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) -> MappedRwLockReadGuard<'static, T> {
pub fn read(&self) -> <<S as Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>, T>>::Mapped
where
<S as Storage<SignalData<T>>>::Ref: Mappable<SignalData<T>, T>,
{
let inner = self.inner.read();
if let Some(effect) = inner.effect_stack.current() {
let mut effect_subscribers = inner.effect_subscribers.borrow_mut();
@@ -198,14 +205,19 @@ impl<T: 'static> Signal<T> {
}
}
}
MappedRwLockReadGuard::map(inner, |v| &v.value)
S::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> {
pub fn write(
&self,
) -> Write<T, <<S as Storage<SignalData<T>>>::Mut as MappableMut<SignalData<T>, T>>::Mapped, S>
where
<S as Storage<SignalData<T>>>::Mut: MappableMut<SignalData<T>, T>,
{
let inner = self.inner.write();
let borrow = MappedRwLockWriteGuard::map(inner, |v| &mut v.value);
let borrow = S::Mut::map(inner, |v| &mut v.value);
Write {
write: borrow,
signal: SignalSubscriberDrop { signal: *self },
@@ -260,7 +272,7 @@ impl<T: 'static> Signal<T> {
}
}
impl<T: Clone + 'static> Signal<T> {
impl<T: Clone + 'static, S: Storage<SignalData<T>>> Signal<T, S> {
/// 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 {
@@ -268,21 +280,21 @@ impl<T: Clone + 'static> Signal<T> {
}
}
impl Signal<bool> {
impl<S: Storage<bool>> Signal<bool, S> {
/// Invert the boolean value of the signal. This will trigger an update on all subscribers.
pub fn toggle(&self) {
self.set(!self.value());
}
}
impl<T: 'static> PartialEq for Signal<T> {
impl<T: 'static, S: Storage<SignalData<T>>> PartialEq for Signal<T, S> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T> Deref for Signal<T> {
type Target = dyn Fn() -> MappedRwLockReadGuard<'static, T>;
impl<T, S: Storage<SignalData<T>>> Deref for Signal<T, S> {
type Target = dyn Fn() -> S::Ref;
fn deref(&self) -> &Self::Target {
// https://github.com/dtolnay/case-studies/tree/master/callable-types
@@ -314,28 +326,31 @@ impl<T> Deref for Signal<T> {
}
}
struct SignalSubscriberDrop<T: 'static> {
signal: Signal<T>,
struct SignalSubscriberDrop<T: 'static, S: Storage<SignalData<T>>> {
signal: Signal<T, S>,
}
impl<T: 'static> Drop for SignalSubscriberDrop<T> {
impl<T: 'static, S: Storage<SignalData<T>>> Drop for SignalSubscriberDrop<T, S> {
fn drop(&mut self) {
self.signal.update_subscribers();
}
}
/// A mutable reference to a signal's value.
pub struct Write<T: 'static, I: 'static = T> {
write: MappedRwLockWriteGuard<'static, T>,
signal: SignalSubscriberDrop<I>,
pub struct Write<T: 'static, B: DerefMut<Target = T>, S: Storage<SignalData<I>>, I: 'static = T> {
write: B,
signal: SignalSubscriberDrop<I, S>,
}
impl<T: 'static, I: 'static> Write<T, I> {
impl<T: 'static, B: DerefMut<Target = T>, S: Storage<SignalData<I>>, I: 'static> Write<T, B, S, I> {
/// Map the mutable reference to the signal's value to a new type.
pub fn map<O>(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<O, I> {
pub fn map<O>(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<O, S::Mapped, S, I>
where
S: MappableMut<T, O>,
{
let Self { write, signal } = myself;
Write {
write: MappedRwLockWriteGuard::map(write, f),
write: S::map(write, f),
signal,
}
}
@@ -344,14 +359,19 @@ impl<T: 'static, I: 'static> Write<T, I> {
pub fn filter_map<O>(
myself: Self,
f: impl FnOnce(&mut T) -> Option<&mut O>,
) -> Option<Write<O, I>> {
) -> Option<Write<O, S::Mapped, S, I>>
where
S: MappableMut<T, O>,
{
let Self { write, signal } = myself;
let write = MappedRwLockWriteGuard::try_map(write, f).ok();
write.map(|write| Write { write, signal })
}
}
impl<T: 'static, I: 'static> Deref for Write<T, I> {
impl<T: 'static, B: DerefMut<Target = T>, S: Storage<SignalData<I>>, I: 'static> Deref
for Write<T, B, S, I>
{
type Target = T;
fn deref(&self) -> &Self::Target {
@@ -359,20 +379,20 @@ impl<T: 'static, I: 'static> Deref for Write<T, I> {
}
}
impl<T, I> DerefMut for Write<T, I> {
impl<T, B: DerefMut<Target = T>, S: Storage<SignalData<I>>, I> DerefMut for Write<T, B, S, I> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.write
}
}
/// A signal that can only be read from.
pub struct ReadOnlySignal<T: 'static> {
inner: Signal<T>,
pub struct ReadOnlySignal<T: 'static, S: Storage<SignalData<T>>> {
inner: Signal<T, S>,
}
impl<T: 'static> ReadOnlySignal<T> {
impl<T: 'static, S: Storage<SignalData<T>>> ReadOnlySignal<T, S> {
/// Create a new read-only signal.
pub fn new(signal: Signal<T>) -> Self {
pub fn new(signal: Signal<T, S>) -> Self {
Self { inner: signal }
}
@@ -392,21 +412,21 @@ impl<T: 'static> ReadOnlySignal<T> {
}
}
impl<T: Clone + 'static> ReadOnlySignal<T> {
impl<T: Clone + 'static, S: Storage<SignalData<T>>> ReadOnlySignal<T, S> {
/// Get the current value of the signal. This will subscribe the current scope to the signal.
pub fn value(&self) -> T {
self.read().clone()
}
}
impl<T: 'static> PartialEq for ReadOnlySignal<T> {
impl<T: 'static, S: Storage<SignalData<T>>> PartialEq for ReadOnlySignal<T, S> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T> Deref for ReadOnlySignal<T> {
type Target = dyn Fn() -> MappedRwLockReadGuard<'static, T>;
impl<T, S: Storage<SignalData<T>>> Deref for ReadOnlySignal<T, S> {
type Target = dyn Fn() -> S::Ref;
fn deref(&self) -> &Self::Target {
// https://github.com/dtolnay/case-studies/tree/master/callable-types