Merge branch 'maybe-sync-signal' into map-signal
This commit is contained in:
commit
cddcd69200
20 files changed
+1706
-710
No files matched your search
@@ -1,20 +1,29 @@
|
||||
use core::{self, fmt::Debug};
|
||||
use std::fmt::{self, Formatter};
|
||||
//
|
||||
use dioxus_core::prelude::*;
|
||||
use futures_channel::mpsc::UnboundedSender;
|
||||
use futures_util::StreamExt;
|
||||
use generational_box::GenerationalBoxId;
|
||||
use parking_lot::RwLock;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::fmt::{self, Formatter};
|
||||
|
||||
use crate::use_signal;
|
||||
use crate::{dependency::Dependency, CopyValue};
|
||||
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
thread_local! {
|
||||
pub(crate)static EFFECT_STACK: EffectStack = EffectStack::default();
|
||||
}
|
||||
|
||||
pub(crate) struct EffectStack {
|
||||
pub(crate) effects: CopyValue<Vec<Effect>>,
|
||||
pub(crate) effects: RwLock<Vec<Effect>>,
|
||||
pub(crate) effect_mapping: RwLock<FxHashMap<GenerationalBoxId, Effect>>,
|
||||
}
|
||||
|
||||
impl Default for EffectStack {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
effects: CopyValue::new_in_scope(Vec::new(), ScopeId::ROOT),
|
||||
effects: RwLock::new(Vec::new()),
|
||||
effect_mapping: RwLock::new(FxHashMap::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,13 +34,41 @@ impl EffectStack {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_effect_stack() -> EffectStack {
|
||||
/// This is a thread safe reference to an effect stack running on another thread.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct EffectStackRef {
|
||||
rerun_effect: UnboundedSender<GenerationalBoxId>,
|
||||
}
|
||||
|
||||
impl EffectStackRef {
|
||||
pub(crate) fn rerun_effect(&self, id: GenerationalBoxId) {
|
||||
self.rerun_effect.unbounded_send(id).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_effect_ref() -> EffectStackRef {
|
||||
match consume_context() {
|
||||
Some(rt) => rt,
|
||||
None => {
|
||||
let store = EffectStack::default();
|
||||
provide_root_context(store);
|
||||
store
|
||||
let (sender, mut receiver) = futures_channel::mpsc::unbounded();
|
||||
spawn_forever(async move {
|
||||
while let Some(id) = receiver.next().await {
|
||||
EFFECT_STACK.with(|stack| {
|
||||
let effect_mapping = stack.effect_mapping.read();
|
||||
if let Some(effect) = effect_mapping.get(&id) {
|
||||
tracing::trace!("Rerunning effect: {:?}", id);
|
||||
effect.try_run();
|
||||
} else {
|
||||
tracing::trace!("Effect not found: {:?}", id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let stack_ref = EffectStackRef {
|
||||
rerun_effect: sender,
|
||||
};
|
||||
provide_root_context(stack_ref.clone());
|
||||
stack_ref
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,19 +105,44 @@ 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) effect_stack: EffectStack,
|
||||
pub(crate) inner: CopyValue<EffectInner>,
|
||||
}
|
||||
|
||||
pub(crate) struct EffectInner {
|
||||
pub(crate) callback: Box<dyn FnMut()>,
|
||||
pub(crate) id: GenerationalBoxId,
|
||||
}
|
||||
|
||||
impl EffectInner {
|
||||
pub(crate) fn new(callback: Box<dyn FnMut()>) -> CopyValue<Self> {
|
||||
let copy = CopyValue::invalid();
|
||||
let inner = EffectInner {
|
||||
callback: Box::new(callback),
|
||||
id: copy.id(),
|
||||
};
|
||||
copy.set(inner);
|
||||
copy
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EffectInner {
|
||||
fn drop(&mut self) {
|
||||
EFFECT_STACK.with(|stack| {
|
||||
tracing::trace!("Dropping effect: {:?}", self.id);
|
||||
stack.effect_mapping.write().remove(&self.id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for Effect {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.write_fmt(format_args!("{:?}", self.callback.value))
|
||||
f.write_fmt(format_args!("{:?}", self.inner.value))
|
||||
}
|
||||
}
|
||||
|
||||
impl Effect {
|
||||
pub(crate) fn current() -> Option<Self> {
|
||||
get_effect_stack().effects.read().last().copied()
|
||||
EFFECT_STACK.with(|stack| stack.effects.read().last().copied())
|
||||
}
|
||||
|
||||
/// Create a new effect. The effect will be run immediately and whenever any signal it reads changes.
|
||||
@@ -89,10 +151,17 @@ impl Effect {
|
||||
pub fn new(callback: impl FnMut() + 'static) -> Self {
|
||||
let myself = Self {
|
||||
source: current_scope_id().expect("in a virtual dom"),
|
||||
callback: CopyValue::new(Box::new(callback)),
|
||||
effect_stack: get_effect_stack(),
|
||||
inner: EffectInner::new(Box::new(callback)),
|
||||
};
|
||||
|
||||
EFFECT_STACK.with(|stack| {
|
||||
stack
|
||||
.effect_mapping
|
||||
.write()
|
||||
.insert(myself.inner.id(), myself);
|
||||
});
|
||||
tracing::trace!("Created effect: {:?}", myself);
|
||||
|
||||
myself.try_run();
|
||||
|
||||
myself
|
||||
@@ -100,14 +169,24 @@ impl Effect {
|
||||
|
||||
/// 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 Ok(mut callback) = self.callback.try_write() {
|
||||
tracing::trace!("Running effect: {:?}", self);
|
||||
if let Ok(mut inner) = self.inner.try_write() {
|
||||
{
|
||||
self.effect_stack.effects.write().push(*self);
|
||||
EFFECT_STACK.with(|stack| {
|
||||
stack.effects.write().push(*self);
|
||||
});
|
||||
}
|
||||
callback();
|
||||
(inner.callback)();
|
||||
{
|
||||
self.effect_stack.effects.write().pop();
|
||||
EFFECT_STACK.with(|stack| {
|
||||
stack.effects.write().pop();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the id of this effect.
|
||||
pub fn id(&self) -> GenerationalBoxId {
|
||||
self.inner.id()
|
||||
}
|
||||
}
|
||||
+237
-100
@@ -1,8 +1,9 @@
|
||||
use crate::rt::CopyValue;
|
||||
use crate::signal::{ReadOnlySignal, Signal, Write};
|
||||
use crate::MappedSignal;
|
||||
use generational_box::GenerationalRef;
|
||||
use generational_box::GenerationalRefMut;
|
||||
use crate::SignalData;
|
||||
use generational_box::Mappable;
|
||||
use generational_box::{MappableMut, Storage};
|
||||
|
||||
use std::{
|
||||
fmt::{Debug, Display},
|
||||
@@ -10,212 +11,329 @@ use std::{
|
||||
};
|
||||
|
||||
macro_rules! read_impls {
|
||||
($ty:ident) => {
|
||||
impl<T: Default + 'static> Default for $ty<T> {
|
||||
($ty:ident, $bound:path) => {
|
||||
impl<T: Default + 'static, S: $bound> Default for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn default() -> Self {
|
||||
Self::new(Default::default())
|
||||
Self::new_maybe_sync(Default::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::clone::Clone for $ty<T> {
|
||||
impl<T, S: $bound> std::clone::Clone for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Copy for $ty<T> {}
|
||||
impl<T, S: $bound> Copy for $ty<T, S> {}
|
||||
|
||||
impl<T: Display + 'static> Display for $ty<T> {
|
||||
impl<T: Display + 'static, S: $bound> Display for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.with(|v| Display::fmt(v, f))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Debug + 'static> Debug for $ty<T> {
|
||||
impl<T: Debug + 'static, S: $bound> Debug for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.with(|v| Debug::fmt(v, f))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> $ty<Vec<T>> {
|
||||
/// Read a value from the inner vector.
|
||||
pub fn get(&self, index: usize) -> Option<GenerationalRef<T>> {
|
||||
GenerationalRef::filter_map(self.read(), |v| v.get(index))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> $ty<Option<T>> {
|
||||
/// Unwraps the inner value and clones it.
|
||||
pub fn unwrap(&self) -> T
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
self.with(|v| v.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// Attempts to read the inner value of the Option.
|
||||
pub fn as_ref(&self) -> Option<GenerationalRef<T>> {
|
||||
GenerationalRef::filter_map(self.read(), |v| v.as_ref())
|
||||
impl<T: PartialEq + 'static, S: $bound> PartialEq<T> for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn eq(&self, other: &T) -> bool {
|
||||
self.with(|v| *v == *other)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! write_impls {
|
||||
($ty:ident) => {
|
||||
impl<T: Add<Output = T> + Copy + 'static> std::ops::Add<T> for $ty<T> {
|
||||
($ty:ident, $bound:path, $vec_bound:path) => {
|
||||
impl<T: Add<Output = T> + Copy + 'static, S: $bound> std::ops::Add<T> for $ty<T, S> {
|
||||
type Output = T;
|
||||
|
||||
#[track_caller]
|
||||
fn add(self, rhs: T) -> Self::Output {
|
||||
self.with(|v| *v + rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Add<Output = T> + Copy + 'static> std::ops::AddAssign<T> for $ty<T> {
|
||||
impl<T: Add<Output = T> + Copy + 'static, S: $bound> std::ops::AddAssign<T> for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn add_assign(&mut self, rhs: T) {
|
||||
self.with_mut(|v| *v = *v + rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Sub<Output = T> + Copy + 'static> std::ops::SubAssign<T> for $ty<T> {
|
||||
impl<T: Sub<Output = T> + Copy + 'static, S: $bound> std::ops::SubAssign<T> for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn sub_assign(&mut self, rhs: T) {
|
||||
self.with_mut(|v| *v = *v - rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Sub<Output = T> + Copy + 'static> std::ops::Sub<T> for $ty<T> {
|
||||
impl<T: Sub<Output = T> + Copy + 'static, S: $bound> std::ops::Sub<T> for $ty<T, S> {
|
||||
type Output = T;
|
||||
|
||||
#[track_caller]
|
||||
fn sub(self, rhs: T) -> Self::Output {
|
||||
self.with(|v| *v - rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Mul<Output = T> + Copy + 'static> std::ops::MulAssign<T> for $ty<T> {
|
||||
impl<T: Mul<Output = T> + Copy + 'static, S: $bound> std::ops::MulAssign<T> for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn mul_assign(&mut self, rhs: T) {
|
||||
self.with_mut(|v| *v = *v * rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Mul<Output = T> + Copy + 'static> std::ops::Mul<T> for $ty<T> {
|
||||
impl<T: Mul<Output = T> + Copy + 'static, S: $bound> std::ops::Mul<T> for $ty<T, S> {
|
||||
type Output = T;
|
||||
|
||||
#[track_caller]
|
||||
fn mul(self, rhs: T) -> Self::Output {
|
||||
self.with(|v| *v * rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Div<Output = T> + Copy + 'static> std::ops::DivAssign<T> for $ty<T> {
|
||||
impl<T: Div<Output = T> + Copy + 'static, S: $bound> std::ops::DivAssign<T> for $ty<T, S> {
|
||||
#[track_caller]
|
||||
fn div_assign(&mut self, rhs: T) {
|
||||
self.with_mut(|v| *v = *v / rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Div<Output = T> + Copy + 'static> std::ops::Div<T> for $ty<T> {
|
||||
impl<T: Div<Output = T> + Copy + 'static, S: $bound> std::ops::Div<T> for $ty<T, S> {
|
||||
type Output = T;
|
||||
|
||||
#[track_caller]
|
||||
fn div(self, rhs: T) -> Self::Output {
|
||||
self.with(|v| *v / rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> $ty<Vec<T>> {
|
||||
impl<T: 'static, S: $vec_bound> $ty<Vec<T>, S> {
|
||||
/// Pushes a new value to the end of the vector.
|
||||
#[track_caller]
|
||||
pub fn push(&self, value: T) {
|
||||
self.with_mut(|v| v.push(value))
|
||||
}
|
||||
|
||||
/// Pops the last value from the vector.
|
||||
#[track_caller]
|
||||
pub fn pop(&self) -> Option<T> {
|
||||
self.with_mut(|v| v.pop())
|
||||
}
|
||||
|
||||
/// Inserts a new value at the given index.
|
||||
#[track_caller]
|
||||
pub fn insert(&self, index: usize, value: T) {
|
||||
self.with_mut(|v| v.insert(index, value))
|
||||
}
|
||||
|
||||
/// Removes the value at the given index.
|
||||
#[track_caller]
|
||||
pub fn remove(&self, index: usize) -> T {
|
||||
self.with_mut(|v| v.remove(index))
|
||||
}
|
||||
|
||||
/// Clears the vector, removing all values.
|
||||
#[track_caller]
|
||||
pub fn clear(&self) {
|
||||
self.with_mut(|v| v.clear())
|
||||
}
|
||||
|
||||
/// Extends the vector with the given iterator.
|
||||
#[track_caller]
|
||||
pub fn extend(&self, iter: impl IntoIterator<Item = T>) {
|
||||
self.with_mut(|v| v.extend(iter))
|
||||
}
|
||||
|
||||
/// Truncates the vector to the given length.
|
||||
#[track_caller]
|
||||
pub fn truncate(&self, len: usize) {
|
||||
self.with_mut(|v| v.truncate(len))
|
||||
}
|
||||
|
||||
/// Swaps two values in the vector.
|
||||
#[track_caller]
|
||||
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.
|
||||
#[track_caller]
|
||||
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.
|
||||
#[track_caller]
|
||||
pub fn split_off(&self, at: usize) -> Vec<T> {
|
||||
self.with_mut(|v| v.split_off(at))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> $ty<Option<T>> {
|
||||
/// Takes the value out of the Option.
|
||||
pub fn take(&self) -> Option<T> {
|
||||
self.with_mut(|v| v.take())
|
||||
}
|
||||
|
||||
/// Replace the value in the Option.
|
||||
pub fn replace(&self, value: T) -> Option<T> {
|
||||
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) -> GenerationalRef<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) -> GenerationalRef<T> {
|
||||
let borrow = self.read();
|
||||
if borrow.is_none() {
|
||||
drop(borrow);
|
||||
self.with_mut(|v| *v = Some(default()));
|
||||
GenerationalRef::map(self.read(), |v| v.as_ref().unwrap())
|
||||
} else {
|
||||
GenerationalRef::map(borrow, |v| v.as_ref().unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
read_impls!(CopyValue);
|
||||
write_impls!(CopyValue);
|
||||
read_impls!(Signal);
|
||||
write_impls!(Signal);
|
||||
read_impls!(ReadOnlySignal);
|
||||
read_impls!(CopyValue, Storage<T>);
|
||||
|
||||
/// An iterator over the values of a `CopyValue<Vec<T>>`.
|
||||
pub struct CopyValueIterator<T: 'static> {
|
||||
index: usize,
|
||||
value: CopyValue<Vec<T>>,
|
||||
impl<T: 'static, S: Storage<Vec<T>>> CopyValue<Vec<T>, S> {
|
||||
/// Read a value from the inner vector.
|
||||
#[track_caller]
|
||||
pub fn get(&self, index: usize) -> Option<<S::Ref as Mappable<Vec<T>>>::Mapped<T>> {
|
||||
S::Ref::try_map(self.read(), move |v| v.get(index))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Iterator for CopyValueIterator<T> {
|
||||
type Item = GenerationalRef<T>;
|
||||
impl<T: 'static, S: Storage<Option<T>>> CopyValue<Option<T>, S> {
|
||||
/// Unwraps the inner value and clones it.
|
||||
#[track_caller]
|
||||
pub fn unwrap(&self) -> T
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
self.with(|v| v.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// Attempts to read the inner value of the Option.
|
||||
#[track_caller]
|
||||
pub fn as_ref(&self) -> Option<<S::Ref as Mappable<Option<T>>>::Mapped<T>> {
|
||||
S::Ref::try_map(self.read(), |v| v.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
write_impls!(CopyValue, Storage<T>, Storage<Vec<T>>);
|
||||
|
||||
impl<T: 'static, S: Storage<Option<T>>> CopyValue<Option<T>, S> {
|
||||
/// Takes the value out of the Option.
|
||||
#[track_caller]
|
||||
pub fn take(&self) -> Option<T> {
|
||||
self.with_mut(|v| v.take())
|
||||
}
|
||||
|
||||
/// Replace the value in the Option.
|
||||
#[track_caller]
|
||||
pub fn replace(&self, value: T) -> Option<T> {
|
||||
self.with_mut(|v| v.replace(value))
|
||||
}
|
||||
|
||||
/// Gets the value out of the Option, or inserts the given value if the Option is empty.
|
||||
#[track_caller]
|
||||
pub fn get_or_insert(&self, default: T) -> <S::Ref as Mappable<Option<T>>>::Mapped<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.
|
||||
#[track_caller]
|
||||
pub fn get_or_insert_with(
|
||||
&self,
|
||||
default: impl FnOnce() -> T,
|
||||
) -> <S::Ref as Mappable<Option<T>>>::Mapped<T> {
|
||||
let borrow = self.read();
|
||||
if borrow.is_none() {
|
||||
drop(borrow);
|
||||
self.with_mut(|v| *v = Some(default()));
|
||||
S::Ref::map(self.read(), |v| v.as_ref().unwrap())
|
||||
} else {
|
||||
S::Ref::map(borrow, |v| v.as_ref().unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
read_impls!(Signal, Storage<SignalData<T>>);
|
||||
|
||||
impl<T: 'static, S: Storage<SignalData<Vec<T>>>> Signal<Vec<T>, S> {
|
||||
/// Read a value from the inner vector.
|
||||
pub fn get(
|
||||
&self,
|
||||
index: usize,
|
||||
) -> Option<
|
||||
<<<S as Storage<SignalData<Vec<T>>>>::Ref as Mappable<SignalData<Vec<T>>>>::Mapped<Vec<T>> as Mappable<
|
||||
Vec<T>,
|
||||
>>::Mapped<T>,
|
||||
>{
|
||||
<<S as Storage<SignalData<Vec<T>>>>::Ref as Mappable<SignalData<Vec<T>>>>::Mapped::<Vec<T>>::try_map(self.read(), move |v| v.get(index))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static, S: Storage<SignalData<Option<T>>>> Signal<Option<T>, S> {
|
||||
/// Unwraps the inner value and clones it.
|
||||
pub fn unwrap(&self) -> T
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
self.with(|v| v.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// Attempts to read the inner value of the Option.
|
||||
pub fn as_ref(
|
||||
&self,
|
||||
) -> Option<
|
||||
<<<S as Storage<SignalData<Option<T>>>>::Ref as Mappable<SignalData<Option<T>>>>::Mapped<
|
||||
Option<T>,
|
||||
> as Mappable<Option<T>>>::Mapped<T>,
|
||||
> {
|
||||
<<S as Storage<SignalData<Option<T>>>>::Ref as Mappable<SignalData<Option<T>>>>::Mapped::<
|
||||
Option<T>,
|
||||
>::try_map(self.read(), |v| v.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
write_impls!(Signal, Storage<SignalData<T>>, Storage<SignalData<Vec<T>>>);
|
||||
|
||||
impl<T: 'static, S: Storage<SignalData<Option<T>>>> Signal<Option<T>, S> {
|
||||
/// Takes the value out of the Option.
|
||||
pub fn take(&self) -> Option<T> {
|
||||
self.with_mut(|v| v.take())
|
||||
}
|
||||
|
||||
/// Replace the value in the Option.
|
||||
pub fn replace(&self, value: T) -> Option<T> {
|
||||
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) -> <<S::Ref as Mappable<SignalData<Option<T>>>>::Mapped<Option<T>> as Mappable<Option<T>>>::Mapped<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,
|
||||
) -><<S::Ref as Mappable<SignalData<Option<T>>>>::Mapped<Option<T>> as Mappable<Option<T>>>::Mapped<T>{
|
||||
let borrow = self.read();
|
||||
if borrow.is_none() {
|
||||
drop(borrow);
|
||||
self.with_mut(|v| *v = Some(default()));
|
||||
<S::Ref as Mappable<SignalData<Option<T>>>>::Mapped::<Option<T>>::map(
|
||||
self.read(),
|
||||
|v| v.as_ref().unwrap(),
|
||||
)
|
||||
} else {
|
||||
<S::Ref as Mappable<SignalData<Option<T>>>>::Mapped::<Option<T>>::map(borrow, |v| {
|
||||
v.as_ref().unwrap()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
read_impls!(ReadOnlySignal, Storage<SignalData<T>>);
|
||||
|
||||
/// An iterator over the values of a `CopyValue<Vec<T>>`.
|
||||
pub struct CopyValueIterator<T: 'static, S: Storage<Vec<T>>> {
|
||||
index: usize,
|
||||
value: CopyValue<Vec<T>, S>,
|
||||
}
|
||||
|
||||
impl<T, S: Storage<Vec<T>>> Iterator for CopyValueIterator<T, S> {
|
||||
type Item = S::Ref;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let index = self.index;
|
||||
@@ -224,8 +342,8 @@ impl<T> Iterator for CopyValueIterator<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> IntoIterator for CopyValue<Vec<T>> {
|
||||
type IntoIter = CopyValueIterator<T>;
|
||||
impl<T: 'static, S: Storage<Vec<T>>> IntoIterator for CopyValue<Vec<T>, S> {
|
||||
type IntoIter = S::Ref;
|
||||
|
||||
type Item = GenerationalRef<T>;
|
||||
|
||||
@@ -237,28 +355,30 @@ impl<T: 'static> IntoIterator for CopyValue<Vec<T>> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> CopyValue<Vec<T>> {
|
||||
impl<T: 'static, S: Storage<Vec<T>>> CopyValue<Vec<T>, S> {
|
||||
/// Write to an element in the inner vector.
|
||||
pub fn get_mut(&self, index: usize) -> Option<GenerationalRefMut<T>> {
|
||||
GenerationalRefMut::filter_map(self.write(), |v| v.get_mut(index))
|
||||
pub fn get_mut(&self, index: usize) -> Option<<S::Mut as MappableMut<Vec<T>>>::Mapped<T>> {
|
||||
S::Mut::try_map(self.write(), |v: &mut Vec<T>| v.get_mut(index))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> CopyValue<Option<T>> {
|
||||
impl<T: 'static, S: Storage<Option<T>>> CopyValue<Option<T>, S> {
|
||||
/// Deref the inner value mutably.
|
||||
pub fn as_mut(&self) -> Option<GenerationalRefMut<T>> {
|
||||
GenerationalRefMut::filter_map(self.write(), |v| v.as_mut())
|
||||
pub fn as_mut(
|
||||
&self,
|
||||
) -> Option<<<S as Storage<Option<T>>>::Mut as MappableMut<Option<T>>>::Mapped<T>> {
|
||||
S::Mut::try_map(self.write(), |v: &mut Option<T>| v.as_mut())
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator over items in a `Signal<Vec<T>>`.
|
||||
pub struct SignalIterator<T: 'static> {
|
||||
pub struct SignalIterator<T: 'static, S: Storage<SignalData<Vec<T>>>> {
|
||||
index: usize,
|
||||
value: Signal<Vec<T>>,
|
||||
value: Signal<Vec<T>, S>,
|
||||
}
|
||||
|
||||
impl<T> Iterator for SignalIterator<T> {
|
||||
type Item = GenerationalRef<T>;
|
||||
impl<T, S: Storage<SignalData<Vec<T>>>> Iterator for SignalIterator<T, S> {
|
||||
type Item = S::Ref;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let index = self.index;
|
||||
@@ -267,8 +387,8 @@ impl<T> Iterator for SignalIterator<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> IntoIterator for Signal<Vec<T>> {
|
||||
type IntoIter = SignalIterator<T>;
|
||||
impl<T: 'static, S: Storage<SignalData<Vec<T>>>> IntoIterator for Signal<Vec<T>, S> {
|
||||
type IntoIter = SignalIterator<T, S>;
|
||||
|
||||
type Item = GenerationalRef<T>;
|
||||
|
||||
@@ -281,14 +401,14 @@ impl<T: 'static> IntoIterator for Signal<Vec<T>> {
|
||||
}
|
||||
|
||||
/// An iterator over items in a `Signal<Vec<T>>` that yields [`MappedSignal`]s.
|
||||
pub struct MappedSignalIterator<T: 'static> {
|
||||
pub struct MappedSignalIterator<T: 'static, S: Storage<SignalData<Vec<T>>>> {
|
||||
index: usize,
|
||||
length: usize,
|
||||
value: Signal<Vec<T>>,
|
||||
value: Signal<Vec<T>, S>,
|
||||
}
|
||||
|
||||
impl<T> Iterator for MappedSignalIterator<T> {
|
||||
type Item = MappedSignal<T>;
|
||||
impl<T, S: Storage<SignalData<Vec<T>>>> Iterator for MappedSignalIterator<T, S> {
|
||||
type Item = MappedSignal<T, S>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let index = self.index;
|
||||
@@ -297,9 +417,26 @@ impl<T> Iterator for MappedSignalIterator<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> Signal<Vec<T>> {
|
||||
impl<T: 'static, S: Storage<SignalData<Vec<T>>>> Signal<Vec<T>, S>
|
||||
where
|
||||
<<S as Storage<SignalData<std::vec::Vec<T>>>>::Mut as MappableMut<
|
||||
SignalData<std::vec::Vec<T>>,
|
||||
>>::Mapped<std::vec::Vec<T>>: MappableMut<std::vec::Vec<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>>> {
|
||||
pub fn get_mut(
|
||||
&self,
|
||||
index: usize,
|
||||
) -> Option<
|
||||
Write<
|
||||
T,
|
||||
<<<S as Storage<SignalData<Vec<T>>>>::Mut as MappableMut<SignalData<Vec<T>>>>::Mapped<
|
||||
Vec<T>,
|
||||
> as MappableMut<Vec<T>>>::Mapped<T>,
|
||||
S,
|
||||
Vec<T>,
|
||||
>,
|
||||
> {
|
||||
Write::filter_map(self.write(), |v| v.get_mut(index))
|
||||
}
|
||||
|
||||
@@ -313,9 +450,9 @@ impl<T: 'static> Signal<Vec<T>> {
|
||||
}
|
||||
}
|
||||
|
||||
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<T, <<<S as Storage<SignalData<Option<T>>>>::Mut as MappableMut<SignalData<Option<T>>>>::Mapped<Option<T>> as MappableMut<Option<T>>>::Mapped<T>, S, Option<T>>>{
|
||||
Write::filter_map(self.write(), |v| v.as_mut())
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
|
||||
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
|
||||
#![warn(missing_docs)]
|
||||
#![allow(clippy::type_complexity)]
|
||||
|
||||
mod rt;
|
||||
pub use rt::*;
|
||||
@@ -15,4 +16,5 @@ pub use signal::*;
|
||||
mod dependency;
|
||||
pub use dependency::*;
|
||||
mod map;
|
||||
pub use generational_box::{Storage, SyncStorage, UnsyncStorage};
|
||||
pub use map::*;
|
||||
+43
-30
@@ -1,3 +1,5 @@
|
||||
use generational_box::GenerationalBoxId;
|
||||
use generational_box::UnsyncStorage;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::ops::Deref;
|
||||
use std::rc::Rc;
|
||||
@@ -5,23 +7,11 @@ use std::rc::Rc;
|
||||
use dioxus_core::prelude::*;
|
||||
use dioxus_core::ScopeId;
|
||||
|
||||
use generational_box::{
|
||||
BorrowError, BorrowMutError, GenerationalBox, GenerationalRef, GenerationalRefMut, Owner, Store,
|
||||
};
|
||||
use generational_box::{GenerationalBox, Owner, Storage};
|
||||
|
||||
use crate::Effect;
|
||||
|
||||
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> {
|
||||
fn current_owner<S: Storage<T>, T>() -> Rc<Owner<S>> {
|
||||
match Effect::current() {
|
||||
// If we are inside of an effect, we should use the owner of the effect as the owner of the value.
|
||||
Some(effect) => {
|
||||
@@ -32,18 +22,18 @@ fn current_owner() -> Rc<Owner> {
|
||||
None => match has_context() {
|
||||
Some(rt) => rt,
|
||||
None => {
|
||||
let owner = Rc::new(current_store().owner());
|
||||
let owner = Rc::new(S::owner());
|
||||
provide_context(owner).expect("in a virtual dom")
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_in_scope(scope: ScopeId) -> Rc<Owner> {
|
||||
fn owner_in_scope<S: Storage<T>, T>(scope: ScopeId) -> Rc<Owner<S>> {
|
||||
match consume_context_from_scope(scope) {
|
||||
Some(rt) => rt,
|
||||
None => {
|
||||
let owner = Rc::new(current_store().owner());
|
||||
let owner = Rc::new(S::owner());
|
||||
provide_context_to_scope(scope, owner).expect("in a virtual dom")
|
||||
}
|
||||
}
|
||||
@@ -52,8 +42,8 @@ fn owner_in_scope(scope: ScopeId) -> Rc<Owner> {
|
||||
/// 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: Storage<T> = UnsyncStorage> {
|
||||
pub(crate) value: GenerationalBox<T, S>,
|
||||
origin_scope: ScopeId,
|
||||
}
|
||||
|
||||
@@ -85,6 +75,22 @@ impl<T: 'static> CopyValue<T> {
|
||||
/// Once the component this value is created in is dropped, the value will be dropped.
|
||||
#[track_caller]
|
||||
pub fn new(value: T) -> Self {
|
||||
Self::new_maybe_sync(value)
|
||||
}
|
||||
|
||||
/// Create a new CopyValue. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped.
|
||||
#[track_caller]
|
||||
pub fn new_in_scope(value: T, scope: ScopeId) -> Self {
|
||||
Self::new_maybe_sync_in_scope(value, scope)
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
#[track_caller]
|
||||
pub fn new_maybe_sync(value: T) -> Self {
|
||||
let owner = current_owner();
|
||||
|
||||
Self {
|
||||
@@ -110,7 +116,8 @@ impl<T: 'static> CopyValue<T> {
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
#[track_caller]
|
||||
pub fn new_maybe_sync_in_scope(value: T, scope: ScopeId) -> Self {
|
||||
let owner = owner_in_scope(scope);
|
||||
|
||||
Self {
|
||||
@@ -135,31 +142,32 @@ impl<T: 'static> CopyValue<T> {
|
||||
|
||||
/// Try to read the value. If the value has been dropped, this will return None.
|
||||
#[track_caller]
|
||||
pub fn try_read(&self) -> Result<GenerationalRef<T>, BorrowError> {
|
||||
|
||||
pub fn try_read(&self) -> Result<S::Ref, generational_box::BorrowError> {
|
||||
self.value.try_read()
|
||||
}
|
||||
|
||||
/// Read the value. If the value has been dropped, this will panic.
|
||||
#[track_caller]
|
||||
pub fn read(&self) -> GenerationalRef<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.
|
||||
#[track_caller]
|
||||
pub fn try_write(&self) -> Result<GenerationalRefMut<T>, BorrowMutError> {
|
||||
pub fn try_write(&self) -> Result<S::Mut, generational_box::BorrowMutError> {
|
||||
self.value.try_write()
|
||||
}
|
||||
|
||||
/// Write the value. If the value has been dropped, this will panic.
|
||||
#[track_caller]
|
||||
pub fn write(&self) -> GenerationalRefMut<T> {
|
||||
pub fn write(&self) -> S::Mut {
|
||||
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;
|
||||
pub fn set(&self, value: T) {
|
||||
self.value.set(value);
|
||||
}
|
||||
|
||||
/// Run a function with a reference to the value. If the value has been dropped, this will panic.
|
||||
@@ -173,23 +181,28 @@ impl<T: 'static> CopyValue<T> {
|
||||
let mut write = self.write();
|
||||
f(&mut *write)
|
||||
}
|
||||
|
||||
/// Get the generational id of the value.
|
||||
pub fn id(&self) -> GenerationalBoxId {
|
||||
self.value.id()
|
||||
}
|
||||
}
|
||||
|
||||
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() -> GenerationalRef<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
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use dioxus_core::prelude::*;
|
||||
use generational_box::Storage;
|
||||
|
||||
use crate::dependency::Dependency;
|
||||
use crate::use_signal;
|
||||
use crate::{get_effect_stack, signal::SignalData, CopyValue, Effect, ReadOnlySignal, Signal};
|
||||
use crate::{get_effect_ref, signal::SignalData, CopyValue, Effect, ReadOnlySignal, Signal};
|
||||
use crate::{use_signal, EffectInner, EFFECT_STACK};
|
||||
|
||||
/// Creates a new Selector. The selector will be run immediately and whenever any signal it reads changes.
|
||||
/// Creates a new unsync 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.
|
||||
///
|
||||
@@ -21,15 +22,42 @@ use crate::{get_effect_stack, signal::SignalData, CopyValue, Effect, ReadOnlySig
|
||||
/// render! { "{double}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
#[must_use = "Consider using `use_effect` to rerun a callback when dependencies change"]
|
||||
pub fn use_selector<R: PartialEq>(
|
||||
cx: &ScopeState,
|
||||
f: impl FnMut() -> R + 'static,
|
||||
) -> ReadOnlySignal<R> {
|
||||
*cx.use_hook(|| selector(f))
|
||||
use_maybe_sync_selector(cx, 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
|
||||
/// Creates a new Selector that may be sync. 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}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
#[must_use = "Consider using `use_effect` to rerun a callback when dependencies change"]
|
||||
pub fn use_maybe_sync_selector<R: PartialEq, S: Storage<SignalData<R>>>(
|
||||
cx: &ScopeState,
|
||||
f: impl FnMut() -> R + 'static,
|
||||
) -> ReadOnlySignal<R, S> {
|
||||
*cx.use_hook(|| maybe_sync_selector(f))
|
||||
}
|
||||
|
||||
/// Creates a new unsync 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.
|
||||
///
|
||||
@@ -45,18 +73,52 @@ pub fn use_selector<R: PartialEq>(
|
||||
/// render! { "{double}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
#[must_use = "Consider using `use_effect` to rerun a callback when dependencies change"]
|
||||
pub fn use_selector_with_dependencies<R: PartialEq, D: Dependency>(
|
||||
cx: &ScopeState,
|
||||
dependencies: D,
|
||||
mut f: impl FnMut(D::Out) -> R + 'static,
|
||||
f: impl FnMut(D::Out) -> R + 'static,
|
||||
) -> ReadOnlySignal<R>
|
||||
where
|
||||
D::Out: 'static,
|
||||
{
|
||||
use_maybe_sync_selector_with_dependencies(cx, dependencies, f)
|
||||
}
|
||||
|
||||
/// Creates a new Selector that may be sync 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}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
#[must_use = "Consider using `use_effect` to rerun a callback when dependencies change"]
|
||||
pub fn use_maybe_sync_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, S>
|
||||
where
|
||||
D::Out: 'static,
|
||||
{
|
||||
let dependencies_signal = use_signal(cx, || dependencies.out());
|
||||
let selector = *cx.use_hook(|| {
|
||||
selector(move || {
|
||||
maybe_sync_selector(move || {
|
||||
let deref = &*dependencies_signal.read();
|
||||
f(deref.clone())
|
||||
})
|
||||
@@ -68,43 +130,60 @@ where
|
||||
selector
|
||||
}
|
||||
|
||||
/// Creates a new Selector. The selector will be run immediately and whenever any signal it reads changes.
|
||||
/// Creates a new unsync 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> {
|
||||
let state = Signal::<R> {
|
||||
#[track_caller]
|
||||
pub fn selector<R: PartialEq>(f: impl FnMut() -> R + 'static) -> ReadOnlySignal<R> {
|
||||
maybe_sync_selector(f)
|
||||
}
|
||||
|
||||
/// Creates a new Selector that may be Sync + Send. The selector will be run immediately and whenever any signal it reads changes.
|
||||
///
|
||||
/// Selectors can be used to efficiently compute derived data from signals.
|
||||
#[track_caller]
|
||||
pub fn maybe_sync_selector<R: PartialEq, S: Storage<SignalData<R>>>(
|
||||
mut f: impl FnMut() -> R + 'static,
|
||||
) -> ReadOnlySignal<R, S> {
|
||||
let state = Signal::<R, S> {
|
||||
inner: CopyValue::invalid(),
|
||||
};
|
||||
let effect = Effect {
|
||||
source: current_scope_id().expect("in a virtual dom"),
|
||||
callback: CopyValue::invalid(),
|
||||
effect_stack: get_effect_stack(),
|
||||
inner: CopyValue::invalid(),
|
||||
};
|
||||
|
||||
{
|
||||
get_effect_stack().effects.write().push(effect);
|
||||
EFFECT_STACK.with(|stack| 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(),
|
||||
effect_stack: get_effect_stack(),
|
||||
effect_ref: get_effect_ref(),
|
||||
});
|
||||
{
|
||||
get_effect_stack().effects.write().pop();
|
||||
EFFECT_STACK.with(|stack| stack.effects.write().pop());
|
||||
}
|
||||
|
||||
effect.callback.value.set(Box::new(move || {
|
||||
let value = f();
|
||||
let changed = {
|
||||
let old = state.inner.read();
|
||||
value != old.value
|
||||
};
|
||||
if changed {
|
||||
state.set(value)
|
||||
}
|
||||
}));
|
||||
let invalid_id = effect.id();
|
||||
tracing::trace!("Creating effect: {:?}", invalid_id);
|
||||
effect.inner.value.set(EffectInner {
|
||||
callback: Box::new(move || {
|
||||
let value = f();
|
||||
let changed = {
|
||||
let old = state.inner.read();
|
||||
value != old.value
|
||||
};
|
||||
if changed {
|
||||
state.set(value)
|
||||
}
|
||||
}),
|
||||
id: invalid_id,
|
||||
});
|
||||
{
|
||||
EFFECT_STACK.with(|stack| stack.effect_mapping.write().insert(invalid_id, effect));
|
||||
}
|
||||
|
||||
ReadOnlySignal::new(state)
|
||||
ReadOnlySignal::new_maybe_sync(state)
|
||||
}
|
||||
+187
-67
@@ -1,6 +1,7 @@
|
||||
use crate::MappedSignal;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
marker::PhantomData,
|
||||
mem::MaybeUninit,
|
||||
ops::{Deref, DerefMut},
|
||||
rc::Rc,
|
||||
@@ -11,9 +12,12 @@ use dioxus_core::{
|
||||
prelude::{current_scope_id, has_context, provide_context, schedule_update_any},
|
||||
ScopeId, ScopeState,
|
||||
};
|
||||
use generational_box::{GenerationalRef, GenerationalRefMut};
|
||||
use generational_box::{
|
||||
GenerationalBoxId, Mappable, MappableMut, Storage, SyncStorage, UnsyncStorage,
|
||||
};
|
||||
use parking_lot::RwLock;
|
||||
|
||||
use crate::{get_effect_stack, CopyValue, Effect, EffectStack};
|
||||
use crate::{get_effect_ref, CopyValue, EffectStackRef, EFFECT_STACK};
|
||||
|
||||
/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
|
||||
///
|
||||
@@ -48,7 +52,7 @@ use crate::{get_effect_stack, CopyValue, Effect, EffectStack};
|
||||
/// ```
|
||||
#[track_caller]
|
||||
#[must_use]
|
||||
pub fn use_signal<T: 'static>(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal<T> {
|
||||
pub fn use_signal<T: 'static>(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal<T, UnsyncStorage> {
|
||||
#[cfg(debug_assertions)]
|
||||
let caller = std::panic::Location::caller();
|
||||
|
||||
@@ -61,6 +65,57 @@ pub fn use_signal<T: 'static>(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal<
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a new `Send + Sync`` 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_sync(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 } }
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// fn Child(cx: Scope, state: Signal<u32, SyncStorage>) -> Element {
|
||||
/// let state = *state;
|
||||
///
|
||||
/// use_future!(cx, |()| async move {
|
||||
/// // This signal is Send + Sync, so we can use it in an another thread
|
||||
/// tokio::spawn(async move {
|
||||
/// // Because the signal is a Copy type, we can use it in an async block without cloning it.
|
||||
/// *state.write() += 1;
|
||||
/// }).await;
|
||||
/// });
|
||||
///
|
||||
/// render! {
|
||||
/// button {
|
||||
/// onclick: move |_| *state.write() += 1,
|
||||
/// "{state}"
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[track_caller]
|
||||
pub fn use_signal_sync<T: Send + Sync + 'static>(
|
||||
cx: &ScopeState,
|
||||
f: impl FnOnce() -> T,
|
||||
) -> Signal<T, SyncStorage> {
|
||||
#[cfg(debug_assertions)]
|
||||
let caller = std::panic::Location::caller();
|
||||
*cx.use_hook(|| {
|
||||
Signal::new_with_caller(
|
||||
f(),
|
||||
#[cfg(debug_assertions)]
|
||||
caller,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Unsubscriber {
|
||||
scope: ScopeId,
|
||||
@@ -90,11 +145,17 @@ fn current_unsubscriber() -> Unsubscriber {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct SignalData<T> {
|
||||
pub(crate) subscribers: Rc<RefCell<Vec<ScopeId>>>,
|
||||
pub(crate) effect_subscribers: Rc<RefCell<Vec<Effect>>>,
|
||||
pub(crate) update_any: Arc<dyn Fn(ScopeId)>,
|
||||
pub(crate) effect_stack: EffectStack,
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SignalSubscribers {
|
||||
pub(crate) subscribers: Vec<ScopeId>,
|
||||
pub(crate) effect_subscribers: Vec<GenerationalBoxId>,
|
||||
}
|
||||
|
||||
/// The data stored for tracking in a signal.
|
||||
pub struct SignalData<T> {
|
||||
pub(crate) subscribers: Arc<RwLock<SignalSubscribers>>,
|
||||
pub(crate) update_any: Arc<dyn Fn(ScopeId) + Sync + Send>,
|
||||
pub(crate) effect_ref: EffectStackRef,
|
||||
pub(crate) value: T,
|
||||
}
|
||||
|
||||
@@ -130,8 +191,8 @@ pub(crate) struct SignalData<T> {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub struct Signal<T: 'static> {
|
||||
pub(crate) inner: CopyValue<SignalData<T>>,
|
||||
pub struct Signal<T: 'static, S: Storage<SignalData<T>> = UnsyncStorage> {
|
||||
pub(crate) inner: CopyValue<SignalData<T>, S>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
@@ -152,13 +213,27 @@ impl<T: 'static> Signal<T> {
|
||||
/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
|
||||
#[track_caller]
|
||||
pub fn new(value: T) -> Self {
|
||||
Self::new_maybe_sync(value)
|
||||
}
|
||||
|
||||
/// Create a new signal with a custom owner scope. The signal will be dropped when the owner scope is dropped instead of the current scope.
|
||||
#[track_caller]
|
||||
pub fn new_in_scope(value: T, owner: ScopeId) -> Self {
|
||||
Self::new_maybe_sync_in_scope(value, owner)
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
#[track_caller]
|
||||
#[tracing::instrument(skip(value))]
|
||||
pub fn new_maybe_sync(value: T) -> Self {
|
||||
Self {
|
||||
inner: CopyValue::new(SignalData {
|
||||
inner: CopyValue::<SignalData<T>, S>::new_maybe_sync(SignalData {
|
||||
subscribers: Default::default(),
|
||||
effect_subscribers: Default::default(),
|
||||
update_any: schedule_update_any().expect("in a virtual dom"),
|
||||
value,
|
||||
effect_stack: get_effect_stack(),
|
||||
effect_ref: get_effect_ref(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -172,10 +247,9 @@ impl<T: 'static> Signal<T> {
|
||||
inner: CopyValue::new_with_caller(
|
||||
SignalData {
|
||||
subscribers: Default::default(),
|
||||
effect_subscribers: Default::default(),
|
||||
update_any: schedule_update_any().expect("in a virtual dom"),
|
||||
value,
|
||||
effect_stack: get_effect_stack(),
|
||||
effect_ref: get_effect_ref(),
|
||||
},
|
||||
#[cfg(debug_assertions)]
|
||||
caller,
|
||||
@@ -184,15 +258,16 @@ impl<T: 'static> Signal<T> {
|
||||
}
|
||||
|
||||
/// Create a new signal with a custom owner scope. The signal will be dropped when the owner scope is dropped instead of the current scope.
|
||||
pub fn new_in_scope(value: T, owner: ScopeId) -> Self {
|
||||
#[track_caller]
|
||||
#[tracing::instrument(skip(value))]
|
||||
pub fn new_maybe_sync_in_scope(value: T, owner: ScopeId) -> Self {
|
||||
Self {
|
||||
inner: CopyValue::new_in_scope(
|
||||
inner: CopyValue::<SignalData<T>, S>::new_maybe_sync_in_scope(
|
||||
SignalData {
|
||||
subscribers: Default::default(),
|
||||
effect_subscribers: Default::default(),
|
||||
update_any: schedule_update_any().expect("in a virtual dom"),
|
||||
value,
|
||||
effect_stack: get_effect_stack(),
|
||||
effect_ref: get_effect_ref(),
|
||||
},
|
||||
owner,
|
||||
),
|
||||
@@ -208,12 +283,16 @@ impl<T: 'static> Signal<T> {
|
||||
///
|
||||
/// If the signal has been dropped, this will panic.
|
||||
#[track_caller]
|
||||
pub fn read(&self) -> GenerationalRef<T> {
|
||||
pub fn read(
|
||||
&self,
|
||||
) -> <<S as Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>>>::Mapped<T> {
|
||||
let inner = self.inner.read();
|
||||
if let Some(effect) = inner.effect_stack.current() {
|
||||
let mut effect_subscribers = inner.effect_subscribers.borrow_mut();
|
||||
if !effect_subscribers.contains(&effect) {
|
||||
effect_subscribers.push(effect);
|
||||
if let Some(effect) = EFFECT_STACK.with(|stack| stack.current()) {
|
||||
let subscribers = inner.subscribers.read();
|
||||
if !subscribers.effect_subscribers.contains(&effect.inner.id()) {
|
||||
drop(subscribers);
|
||||
let mut subscribers = inner.subscribers.write();
|
||||
subscribers.effect_subscribers.push(effect.inner.id());
|
||||
}
|
||||
} else if let Some(current_scope_id) = current_scope_id() {
|
||||
// only subscribe if the vdom is rendering
|
||||
@@ -223,43 +302,50 @@ impl<T: 'static> Signal<T> {
|
||||
self.inner.value,
|
||||
current_scope_id
|
||||
);
|
||||
let mut subscribers = inner.subscribers.borrow_mut();
|
||||
if !subscribers.contains(¤t_scope_id) {
|
||||
subscribers.push(current_scope_id);
|
||||
let subscribers = inner.subscribers.read();
|
||||
if !subscribers.subscribers.contains(¤t_scope_id) {
|
||||
drop(subscribers);
|
||||
let mut subscribers = inner.subscribers.write();
|
||||
subscribers.subscribers.push(current_scope_id);
|
||||
let unsubscriber = current_unsubscriber();
|
||||
inner.subscribers.borrow_mut().push(unsubscriber.scope);
|
||||
subscribers.subscribers.push(unsubscriber.scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
GenerationalRef::map(inner, |v| &v.value)
|
||||
S::Ref::map(inner, |v| &v.value)
|
||||
}
|
||||
|
||||
/// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
|
||||
///
|
||||
/// If the signal has been dropped, this will panic.
|
||||
pub fn peek(&self) -> GenerationalRef<T> {
|
||||
pub fn peek(
|
||||
&self,
|
||||
) -> <<S as Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>>>::Mapped<T> {
|
||||
let inner = self.inner.read();
|
||||
GenerationalRef::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.
|
||||
#[track_caller]
|
||||
pub fn write(&self) -> Write<T> {
|
||||
pub fn write(
|
||||
&self,
|
||||
) -> Write<T, <<S as Storage<SignalData<T>>>::Mut as MappableMut<SignalData<T>>>::Mapped<T>, S>
|
||||
{
|
||||
let inner = self.inner.write();
|
||||
let borrow = GenerationalRefMut::map(inner, |v| &mut v.value);
|
||||
let borrow = S::Mut::map(inner, |v| &mut v.value);
|
||||
Write {
|
||||
write: borrow,
|
||||
signal: SignalSubscriberDrop { signal: *self },
|
||||
phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
fn update_subscribers(&self) {
|
||||
{
|
||||
let inner = self.inner.read();
|
||||
for &scope_id in &*inner.subscribers.borrow() {
|
||||
for &scope_id in &*inner.subscribers.read().subscribers {
|
||||
tracing::trace!(
|
||||
"Write on {:?} triggered update on {:?}",
|
||||
self.inner.value,
|
||||
@@ -269,18 +355,19 @@ impl<T: 'static> Signal<T> {
|
||||
}
|
||||
}
|
||||
|
||||
let self_read = &self.inner.read();
|
||||
let subscribers = {
|
||||
let self_read = self.inner.read();
|
||||
let mut effects = self_read.effect_subscribers.borrow_mut();
|
||||
let effects = &mut self_read.subscribers.write().effect_subscribers;
|
||||
std::mem::take(&mut *effects)
|
||||
};
|
||||
let effect_ref = &self_read.effect_ref;
|
||||
for effect in subscribers {
|
||||
tracing::trace!(
|
||||
"Write on {:?} triggered effect {:?}",
|
||||
self.inner.value,
|
||||
effect
|
||||
);
|
||||
effect.try_run();
|
||||
effect_ref.rerun_effect(effect);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,9 +397,14 @@ impl<T: 'static> Signal<T> {
|
||||
pub fn map<O>(self, f: impl Fn(&T) -> &O + 'static) -> MappedSignal<O> {
|
||||
MappedSignal::new(self, f)
|
||||
}
|
||||
|
||||
/// Get the generational id of the signal.
|
||||
pub fn id(&self) -> generational_box::GenerationalBoxId {
|
||||
self.inner.id()
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
#[track_caller]
|
||||
@@ -321,21 +413,22 @@ impl<T: Clone + 'static> Signal<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Signal<bool> {
|
||||
impl<S: Storage<SignalData<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() -> GenerationalRef<T>;
|
||||
impl<T, S: Storage<SignalData<T>> + 'static> Deref for Signal<T, S> {
|
||||
type Target =
|
||||
dyn Fn() -> <<S as Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>>>::Mapped<T>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
// https://github.com/dtolnay/case-studies/tree/master/callable-types
|
||||
@@ -367,29 +460,36 @@ 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: GenerationalRefMut<T>,
|
||||
signal: SignalSubscriberDrop<I>,
|
||||
///
|
||||
/// T is the current type of the write
|
||||
/// B is the dynamicly checked type of the write (RefMut)
|
||||
/// S is the storage type of the signal
|
||||
/// I is the type of the original signal
|
||||
pub struct Write<T: 'static, B: MappableMut<T>, S: Storage<SignalData<I>>, I: 'static = T> {
|
||||
write: B,
|
||||
signal: SignalSubscriberDrop<I, S>,
|
||||
phantom: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: 'static, I: 'static> Write<T, I> {
|
||||
impl<T: 'static, B: MappableMut<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> {
|
||||
let Self { write, signal } = myself;
|
||||
pub fn map<O>(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<O, B::Mapped<O>, S, I> {
|
||||
let Self { write, signal, .. } = myself;
|
||||
Write {
|
||||
write: GenerationalRefMut::map(write, f),
|
||||
write: B::map(write, f),
|
||||
signal,
|
||||
phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,14 +497,20 @@ 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>> {
|
||||
let Self { write, signal } = myself;
|
||||
let write = GenerationalRefMut::filter_map(write, f);
|
||||
write.map(|write| Write { write, signal })
|
||||
) -> Option<Write<O, B::Mapped<O>, S, I>> {
|
||||
let Self { write, signal, .. } = myself;
|
||||
let write = B::try_map(write, f);
|
||||
write.map(|write| Write {
|
||||
write,
|
||||
signal,
|
||||
phantom: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static, I: 'static> Deref for Write<T, I> {
|
||||
impl<T: 'static, B: MappableMut<T>, S: Storage<SignalData<I>>, I: 'static> Deref
|
||||
for Write<T, B, S, I>
|
||||
{
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
@@ -412,20 +518,29 @@ impl<T: 'static, I: 'static> Deref for Write<T, I> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, I> DerefMut for Write<T, I> {
|
||||
impl<T, B: MappableMut<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>> = UnsyncStorage> {
|
||||
inner: Signal<T, S>,
|
||||
}
|
||||
|
||||
impl<T: 'static> ReadOnlySignal<T> {
|
||||
/// Create a new read-only signal.
|
||||
#[track_caller]
|
||||
pub fn new(signal: Signal<T>) -> Self {
|
||||
Self::new_maybe_sync(signal)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static, S: Storage<SignalData<T>>> ReadOnlySignal<T, S> {
|
||||
/// Create a new read-only signal that is maybe sync.
|
||||
#[track_caller]
|
||||
pub fn new_maybe_sync(signal: Signal<T, S>) -> Self {
|
||||
Self { inner: signal }
|
||||
}
|
||||
|
||||
@@ -434,18 +549,22 @@ impl<T: 'static> ReadOnlySignal<T> {
|
||||
self.inner.origin_scope()
|
||||
}
|
||||
|
||||
/// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peek`] instead.
|
||||
/// 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.
|
||||
#[track_caller]
|
||||
pub fn read(&self) -> GenerationalRef<T> {
|
||||
pub fn read(
|
||||
&self,
|
||||
) -> <<S as Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>>>::Mapped<T> {
|
||||
self.inner.read()
|
||||
}
|
||||
|
||||
/// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
|
||||
///
|
||||
/// If the signal has been dropped, this will panic.
|
||||
pub fn peek(&self) -> GenerationalRef<T> {
|
||||
pub fn peek(
|
||||
&self,
|
||||
) -> <<S as Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>>>::Mapped<T> {
|
||||
self.inner.peek()
|
||||
}
|
||||
|
||||
@@ -456,21 +575,22 @@ 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() -> GenerationalRef<T>;
|
||||
impl<T, S: Storage<SignalData<T>> + 'static> Deref for ReadOnlySignal<T, S> {
|
||||
type Target =
|
||||
dyn Fn() -> <<S as Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>>>::Mapped<T>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
// https://github.com/dtolnay/case-studies/tree/master/callable-types
|
||||
|
||||
Reference in new issue
Block a user