Merge branch 'maybe-sync-signal' into breaking
This commit is contained in:
commit
611f0d3b5f
25 files changed
+2085
-694
No files matched your search
@@ -0,0 +1,141 @@
|
||||
use std::hash::Hash;
|
||||
|
||||
use dioxus_core::prelude::*;
|
||||
use generational_box::{Storage, UnsyncStorage};
|
||||
|
||||
use crate::{CopyValue, Effect, ReadOnlySignal, Signal, SignalData};
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
/// An object that can efficiently compare a value to a set of values.
|
||||
#[derive(Debug)]
|
||||
pub struct Comparer<R: 'static, S: Storage<SignalData<bool>> = UnsyncStorage> {
|
||||
subscribers: CopyValue<FxHashMap<R, Signal<bool, S>>>,
|
||||
}
|
||||
|
||||
impl<R: Eq + Hash> Comparer<R> {
|
||||
/// Creates a new Comparer which efficiently tracks when a value changes to check if it is equal to a set of values.
|
||||
///
|
||||
/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::use_selector`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
|
||||
pub fn new(mut f: impl FnMut() -> R + 'static) -> Comparer<R> {
|
||||
let subscribers: CopyValue<FxHashMap<R, Signal<bool>>> =
|
||||
CopyValue::new(FxHashMap::default());
|
||||
let previous = CopyValue::new(None);
|
||||
|
||||
Effect::new(move || {
|
||||
let subscribers = subscribers.read();
|
||||
let mut previous = previous.write();
|
||||
|
||||
if let Some(previous) = previous.take() {
|
||||
if let Some(value) = subscribers.get(&previous) {
|
||||
value.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
let current = f();
|
||||
|
||||
if let Some(value) = subscribers.get(¤t) {
|
||||
value.set(true);
|
||||
}
|
||||
|
||||
*previous = Some(current);
|
||||
});
|
||||
|
||||
Comparer { subscribers }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Eq + Hash, S: Storage<SignalData<bool>>> Comparer<R, S> {
|
||||
/// Creates a new Comparer that may be `Sync + Send` which efficiently tracks when a value changes to check if it is equal to a set of values.
|
||||
///
|
||||
/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::use_selector`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
|
||||
pub fn new_maybe_sync(mut f: impl FnMut() -> R + 'static) -> Comparer<R> {
|
||||
let subscribers: CopyValue<FxHashMap<R, Signal<bool>>> =
|
||||
CopyValue::new(FxHashMap::default());
|
||||
let previous = CopyValue::new(None);
|
||||
|
||||
Effect::new(move || {
|
||||
let subscribers = subscribers.read();
|
||||
let mut previous = previous.write();
|
||||
|
||||
if let Some(previous) = previous.take() {
|
||||
if let Some(value) = subscribers.get(&previous) {
|
||||
value.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
let current = f();
|
||||
|
||||
if let Some(value) = subscribers.get(¤t) {
|
||||
value.set(true);
|
||||
}
|
||||
|
||||
*previous = Some(current);
|
||||
});
|
||||
|
||||
Comparer { subscribers }
|
||||
}
|
||||
|
||||
/// Returns a signal which is true when the value is equal to the value passed to this function.
|
||||
pub fn equal(&self, value: R) -> ReadOnlySignal<bool, S> {
|
||||
let subscribers = self.subscribers.read();
|
||||
|
||||
match subscribers.get(&value) {
|
||||
Some(&signal) => signal.into(),
|
||||
None => {
|
||||
drop(subscribers);
|
||||
let mut subscribers = self.subscribers.write();
|
||||
let signal = Signal::new_maybe_sync(false);
|
||||
subscribers.insert(value, signal);
|
||||
signal.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, S: Storage<SignalData<bool>>> Clone for Comparer<R, S> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, S: Storage<SignalData<bool>>> Copy for Comparer<R, S> {}
|
||||
|
||||
/// Creates a new Comparer which efficiently tracks when a value changes to check if it is equal to a set of values.
|
||||
///
|
||||
/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::use_selector`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
|
||||
///
|
||||
/// ```rust
|
||||
/// use dioxus::prelude::*;
|
||||
/// use dioxus_signals::*;
|
||||
///
|
||||
/// fn App(cx: Scope) -> Element {
|
||||
/// let mut count = use_signal(cx, || 0);
|
||||
/// let comparer = use_comparer(cx, move || count.value());
|
||||
///
|
||||
/// render! {
|
||||
/// for i in 0..10 {
|
||||
/// // Child will only re-render when i == count
|
||||
/// Child { active: comparer.equal(i) }
|
||||
/// }
|
||||
/// button {
|
||||
/// // This will only rerender the child with the old and new value of i == count
|
||||
/// // Because we are using a comparer, this will be O(1) instead of the O(n) performance of a selector
|
||||
/// onclick: move |_| count += 1,
|
||||
/// "Increment"
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// fn Child(cx: Scope, active: ReadOnlySignal<bool>) -> Element {
|
||||
/// if *active() {
|
||||
/// render! { "Active" }
|
||||
/// } else {
|
||||
/// render! { "Inactive" }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn use_comparer<R: Eq + Hash>(cx: &ScopeState, f: impl FnMut() -> R + 'static) -> Comparer<R> {
|
||||
*cx.use_hook(move || Comparer::new(f))
|
||||
}
|
||||
@@ -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 try_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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,19 +83,44 @@ pub fn use_effect(callback: impl FnMut() + 'static) {
|
||||
#[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.
|
||||
@@ -67,10 +129,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
|
||||
@@ -78,14 +147,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()
|
||||
}
|
||||
}
|
||||
+245
-71
@@ -1,7 +1,8 @@
|
||||
use crate::rt::CopyValue;
|
||||
use crate::signal::{ReadOnlySignal, Signal, Write};
|
||||
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},
|
||||
@@ -9,162 +10,169 @@ 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(&mut self, value: T) {
|
||||
self.with_mut(|v| v.push(value))
|
||||
}
|
||||
|
||||
/// Pops the last value from the vector.
|
||||
#[track_caller]
|
||||
pub fn pop(&mut self) -> Option<T> {
|
||||
self.with_mut(|v| v.pop())
|
||||
}
|
||||
|
||||
/// Inserts a new value at the given index.
|
||||
#[track_caller]
|
||||
pub fn insert(&mut 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(&mut self, index: usize) -> T {
|
||||
self.with_mut(|v| v.remove(index))
|
||||
}
|
||||
|
||||
/// Clears the vector, removing all values.
|
||||
#[track_caller]
|
||||
pub fn clear(&mut self) {
|
||||
self.with_mut(|v| v.clear())
|
||||
}
|
||||
|
||||
/// Extends the vector with the given iterator.
|
||||
#[track_caller]
|
||||
pub fn extend(&mut 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(&mut self, len: usize) {
|
||||
self.with_mut(|v| v.truncate(len))
|
||||
}
|
||||
|
||||
/// Swaps two values in the vector.
|
||||
#[track_caller]
|
||||
pub fn swap_remove(&mut 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(&mut 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(&mut self, at: usize) -> Vec<T> {
|
||||
self.with_mut(|v| v.split_off(at))
|
||||
}
|
||||
@@ -172,21 +180,25 @@ macro_rules! write_impls {
|
||||
|
||||
impl<T: 'static> $ty<Option<T>> {
|
||||
/// Takes the value out of the Option.
|
||||
#[track_caller]
|
||||
pub fn take(&mut self) -> Option<T> {
|
||||
self.with_mut(|v| v.take())
|
||||
}
|
||||
|
||||
/// Replace the value in the Option.
|
||||
#[track_caller]
|
||||
pub fn replace(&mut 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(&mut 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.
|
||||
#[track_caller]
|
||||
pub fn get_or_insert_with(
|
||||
&mut self,
|
||||
default: impl FnOnce() -> T,
|
||||
@@ -204,32 +216,171 @@ macro_rules! write_impls {
|
||||
};
|
||||
}
|
||||
|
||||
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: Clone> Iterator for CopyValueIterator<T> {
|
||||
type Item = 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 as Mappable<Vec<T>>>::Mapped<T>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let index = self.index;
|
||||
self.index += 1;
|
||||
self.value.get(index).map(|v| v.clone())
|
||||
self.value.get(index)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone + '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 = CopyValueIterator<T, S>;
|
||||
|
||||
type Item = T;
|
||||
type Item = <S::Ref as Mappable<Vec<T>>>::Mapped<T>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
CopyValueIterator {
|
||||
@@ -239,40 +390,46 @@ 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> {
|
||||
/// 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: Clone> Iterator for SignalIterator<T> {
|
||||
type Item = T;
|
||||
impl<T, S: Storage<SignalData<Vec<T>>>> Iterator for SignalIterator<T, S> {
|
||||
type Item = <<<S as Storage<SignalData<Vec<T>>>>::Ref as Mappable<SignalData<Vec<T>>>>::Mapped<
|
||||
Vec<T>,
|
||||
> as Mappable<Vec<T>>>::Mapped<T>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let index = self.index;
|
||||
self.index += 1;
|
||||
self.value.get(index).map(|v| v.clone())
|
||||
self.value.get(index)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone + '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 = T;
|
||||
type Item = <<<S as Storage<SignalData<Vec<T>>>>::Ref as Mappable<SignalData<Vec<T>>>>::Mapped<
|
||||
Vec<T>,
|
||||
> as Mappable<Vec<T>>>::Mapped<T>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
SignalIterator {
|
||||
@@ -282,16 +439,33 @@ 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 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(&mut self, index: usize) -> Option<Write<T, Vec<T>>> {
|
||||
pub fn get_mut(
|
||||
&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))
|
||||
}
|
||||
}
|
||||
|
||||
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(&mut self) -> Option<Write<T, Option<T>>> {
|
||||
pub fn as_mut(&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::*;
|
||||
@@ -14,3 +15,8 @@ pub(crate) mod signal;
|
||||
pub use signal::*;
|
||||
mod dependency;
|
||||
pub use dependency::*;
|
||||
mod map;
|
||||
pub use generational_box::{Storage, SyncStorage, UnsyncStorage};
|
||||
pub use map::*;
|
||||
mod comparer;
|
||||
pub use comparer::*;
|
||||
@@ -0,0 +1,119 @@
|
||||
use crate::CopyValue;
|
||||
use crate::Signal;
|
||||
use crate::SignalData;
|
||||
use dioxus_core::ScopeId;
|
||||
use generational_box::Mappable;
|
||||
use generational_box::Storage;
|
||||
use std::fmt::Debug;
|
||||
use std::fmt::Display;
|
||||
|
||||
/// A read only signal that has been mapped to a new type.
|
||||
pub struct MappedSignal<U: 'static + ?Sized> {
|
||||
origin_scope: ScopeId,
|
||||
mapping: CopyValue<Box<dyn Fn() -> U>>,
|
||||
}
|
||||
|
||||
impl MappedSignal<()> {
|
||||
/// Create a new mapped signal.
|
||||
pub fn new<T, S: Storage<SignalData<T>>, U: ?Sized>(
|
||||
signal: Signal<T, S>,
|
||||
mapping: impl Fn(&T) -> &U + 'static,
|
||||
) -> MappedSignal<
|
||||
<<<S as generational_box::Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>>>::Mapped<
|
||||
T,
|
||||
> as generational_box::Mappable<T>>::Mapped<U>,
|
||||
> {
|
||||
MappedSignal {
|
||||
origin_scope: signal.origin_scope(),
|
||||
mapping: CopyValue::new(Box::new(move || {
|
||||
<<<S as Storage<SignalData<T>>>::Ref as Mappable<SignalData<T>>>::Mapped<T>>::map(
|
||||
signal.read(),
|
||||
&mapping,
|
||||
)
|
||||
})),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<U> MappedSignal<U> {
|
||||
/// Get the scope that the signal was created in.
|
||||
pub fn origin_scope(&self) -> ScopeId {
|
||||
self.origin_scope
|
||||
}
|
||||
|
||||
/// Get the current value of the signal. This will subscribe the current scope to the signal.
|
||||
pub fn read(&self) -> U {
|
||||
(self.mapping.read())()
|
||||
}
|
||||
|
||||
/// Run a closure with a reference to the signal's value.
|
||||
pub fn with<O>(&self, f: impl FnOnce(U) -> O) -> O {
|
||||
f(self.read())
|
||||
}
|
||||
}
|
||||
|
||||
impl<U: ?Sized + Clone> MappedSignal<U> {
|
||||
/// Get the current value of the signal. This will subscribe the current scope to the signal.
|
||||
pub fn value(&self) -> U {
|
||||
self.read().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl<U: ?Sized> PartialEq for MappedSignal<U> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.mapping == other.mapping
|
||||
}
|
||||
}
|
||||
|
||||
impl<U> std::clone::Clone for MappedSignal<U> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<U> Copy for MappedSignal<U> {}
|
||||
|
||||
impl<U: Display> Display for MappedSignal<U> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.with(|v| Display::fmt(&v, f))
|
||||
}
|
||||
}
|
||||
|
||||
impl<U: Debug> Debug for MappedSignal<U> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.with(|v| Debug::fmt(&v, f))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::ops::Deref for MappedSignal<T> {
|
||||
type Target = dyn Fn() -> T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
// https://github.com/dtolnay/case-studies/tree/master/callable-types
|
||||
|
||||
// First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
|
||||
let uninit_callable = std::mem::MaybeUninit::<Self>::uninit();
|
||||
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
|
||||
let uninit_closure = move || Self::read(unsafe { &*uninit_callable.as_ptr() });
|
||||
|
||||
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
|
||||
let size_of_closure = std::mem::size_of_val(&uninit_closure);
|
||||
assert_eq!(size_of_closure, std::mem::size_of::<Self>());
|
||||
|
||||
// Then cast the lifetime of the closure to the lifetime of &self.
|
||||
fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
|
||||
b
|
||||
}
|
||||
let reference_to_closure = cast_lifetime(
|
||||
{
|
||||
// The real closure that we will never use.
|
||||
&uninit_closure
|
||||
},
|
||||
// We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self.
|
||||
unsafe { std::mem::transmute(self) },
|
||||
);
|
||||
|
||||
// Cast the closure to a trait object.
|
||||
reference_to_closure as &Self::Target
|
||||
}
|
||||
}
|
||||
+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 try_consume_context::<Store>() {
|
||||
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,19 +22,19 @@ fn current_owner() -> Rc<Owner> {
|
||||
None => match has_context() {
|
||||
Some(rt) => rt,
|
||||
None => {
|
||||
let owner = Rc::new(current_store().owner());
|
||||
provide_context(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());
|
||||
scope.provide_context(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,19 +142,20 @@ 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()
|
||||
}
|
||||
|
||||
@@ -157,13 +165,13 @@ impl<T: 'static> CopyValue<T> {
|
||||
|
||||
/// 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(&self, value: T) {
|
||||
*self.write() = value;
|
||||
self.value.set(value);
|
||||
}
|
||||
|
||||
/// Run a function with a reference to the value. If the value has been dropped, this will panic.
|
||||
@@ -177,22 +185,27 @@ 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: 'static + Clone> Deref for CopyValue<T> {
|
||||
impl<T, S: Storage<T>> Deref for CopyValue<T, S> {
|
||||
type Target = dyn Fn() -> T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
|
||||
@@ -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,48 +22,165 @@ use crate::{get_effect_stack, signal::SignalData, CopyValue, Effect, ReadOnlySig
|
||||
/// rsx! { "{double}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
#[must_use = "Consider using `use_effect` to rerun a callback when dependencies change"]
|
||||
pub fn use_selector<R: PartialEq>(f: impl FnMut() -> R + 'static) -> ReadOnlySignal<R> {
|
||||
use_hook(|| selector(f))
|
||||
use_maybe_sync_selector(f)
|
||||
}
|
||||
|
||||
/// Creates a new Selector. The selector will be run immediately and whenever any signal it reads 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.
|
||||
pub fn selector<R: PartialEq>(mut f: impl FnMut() -> R + 'static) -> ReadOnlySignal<R> {
|
||||
let mut state = Signal::<R> {
|
||||
///
|
||||
/// ```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>>>(
|
||||
f: impl FnMut() -> R + 'static,
|
||||
) -> ReadOnlySignal<R, S> {
|
||||
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.
|
||||
///
|
||||
/// ```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_selector_with_dependencies<R: PartialEq, D: Dependency>(
|
||||
cx: &ScopeState,
|
||||
dependencies: D,
|
||||
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(|| {
|
||||
maybe_sync_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 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.
|
||||
#[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(),
|
||||
update_any: schedule_update_any(),
|
||||
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)
|
||||
}
|
||||
+207
-72
@@ -1,5 +1,7 @@
|
||||
use crate::MappedSignal;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
marker::PhantomData,
|
||||
mem::MaybeUninit,
|
||||
ops::{Deref, DerefMut},
|
||||
rc::Rc,
|
||||
@@ -13,9 +15,12 @@ use dioxus_core::{
|
||||
},
|
||||
ScopeId,
|
||||
};
|
||||
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.
|
||||
///
|
||||
@@ -50,7 +55,7 @@ use crate::{get_effect_stack, CopyValue, Effect, EffectStack};
|
||||
/// ```
|
||||
#[track_caller]
|
||||
#[must_use]
|
||||
pub fn use_signal<T: 'static>(f: impl FnOnce() -> T) -> Signal<T> {
|
||||
pub fn use_signal<T: 'static>(f: impl FnOnce() -> T) -> Signal<T, UnsyncStorage> {
|
||||
#[cfg(debug_assertions)]
|
||||
let caller = std::panic::Location::caller();
|
||||
|
||||
@@ -63,6 +68,57 @@ pub fn use_signal<T: 'static>(f: impl FnOnce() -> T) -> Signal<T> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -92,11 +148,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,
|
||||
}
|
||||
|
||||
@@ -132,8 +194,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")]
|
||||
@@ -154,13 +216,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(),
|
||||
value,
|
||||
effect_stack: get_effect_stack(),
|
||||
effect_ref: get_effect_ref(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -174,10 +250,9 @@ impl<T: 'static> Signal<T> {
|
||||
inner: CopyValue::new_with_caller(
|
||||
SignalData {
|
||||
subscribers: Default::default(),
|
||||
effect_subscribers: Default::default(),
|
||||
update_any: schedule_update_any(),
|
||||
value,
|
||||
effect_stack: get_effect_stack(),
|
||||
effect_ref: get_effect_ref(),
|
||||
},
|
||||
#[cfg(debug_assertions)]
|
||||
caller,
|
||||
@@ -186,15 +261,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(),
|
||||
value,
|
||||
effect_stack: get_effect_stack(),
|
||||
effect_ref: get_effect_ref(),
|
||||
},
|
||||
owner,
|
||||
),
|
||||
@@ -210,12 +286,16 @@ impl<T: 'static> Signal<T> {
|
||||
///
|
||||
/// If the signal has been dropped, this will panic.
|
||||
#[track_caller]
|
||||
pub fn read<'a>(&'a self) -> GenerationalRef<'a, 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
|
||||
@@ -225,50 +305,61 @@ 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<'a>(&'a mut self) -> Write<'a, T> {
|
||||
pub fn write<'a>(
|
||||
&'a mut self,
|
||||
) -> Write<T, <<S as Storage<SignalData<T>>>::Mut as MappableMut<SignalData<T>>>::Mapped<T>, S>
|
||||
{
|
||||
self.write_unchecked()
|
||||
}
|
||||
|
||||
/// Write to the value through an immutable reference.
|
||||
///
|
||||
/// This is public since it's useful in many scenarios, but we generally recommend mutation through [`Self::write`] instead.
|
||||
pub fn write_unchecked(&self) -> Write<T> {
|
||||
#[track_caller]
|
||||
pub fn write_unchecked(
|
||||
&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,
|
||||
@@ -278,18 +369,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,6 +414,23 @@ impl<T: 'static> Signal<T> {
|
||||
let mut write = self.write();
|
||||
f(&mut *write)
|
||||
}
|
||||
|
||||
/// Map the signal to a new type.
|
||||
pub fn map<O>(
|
||||
self,
|
||||
f: impl Fn(&T) -> &O + 'static,
|
||||
) -> MappedSignal<
|
||||
<<<S as generational_box::Storage<SignalData<T>>>::Ref as generational_box::Mappable<
|
||||
SignalData<T>,
|
||||
>>::Mapped<T> as generational_box::Mappable<T>>::Mapped<O>,
|
||||
> {
|
||||
MappedSignal::new(self, f)
|
||||
}
|
||||
|
||||
/// Get the generational id of the signal.
|
||||
pub fn id(&self) -> generational_box::GenerationalBoxId {
|
||||
self.inner.id()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoAttributeValue for Signal<T>
|
||||
@@ -333,7 +442,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
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]
|
||||
@@ -342,14 +451,14 @@ 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(&mut self) {
|
||||
self.set(!self.cloned());
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -358,7 +467,7 @@ impl<T: 'static> PartialEq for Signal<T> {
|
||||
/// Allow calling a signal with signal() syntax
|
||||
///
|
||||
/// Currently only limited to copy types, though could probably specialize for string/arc/rc
|
||||
impl<T: Copy> Deref for Signal<T> {
|
||||
impl<T, S: Storage<SignalData<T>> + 'static> Deref for Signal<T, S> {
|
||||
type Target = dyn Fn() -> T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
@@ -391,29 +500,36 @@ impl<T: Copy> 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<'a, T: 'static, I: 'static = T> {
|
||||
write: GenerationalRefMut<'a, 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<'a, T: 'static, I: 'static> Write<'a, 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<'a, 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,14 +537,20 @@ impl<'a, T: 'static, I: 'static> Write<'a, T, I> {
|
||||
pub fn filter_map<O>(
|
||||
myself: Self,
|
||||
f: impl FnOnce(&mut T) -> Option<&mut O>,
|
||||
) -> Option<Write<'a, 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<'a, T: 'static, I: 'static> Deref for Write<'a, 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 {
|
||||
@@ -436,20 +558,35 @@ impl<'a, T: 'static, I: 'static> Deref for Write<'a, T, I> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, I> DerefMut for Write<'a, 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, S: Storage<SignalData<T>>> From<Signal<T, S>> for ReadOnlySignal<T, S> {
|
||||
fn from(inner: Signal<T, S>) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
@@ -458,18 +595,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()
|
||||
}
|
||||
|
||||
@@ -480,20 +621,20 @@ 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: Copy> Deref for ReadOnlySignal<T> {
|
||||
impl<T, S: Storage<SignalData<T>> + 'static> Deref for ReadOnlySignal<T, S> {
|
||||
type Target = dyn Fn() -> T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
@@ -525,9 +666,3 @@ impl<T: Copy> Deref for ReadOnlySignal<T> {
|
||||
reference_to_closure as &Self::Target
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Signal<T>> for ReadOnlySignal<T> {
|
||||
fn from(signal: Signal<T>) -> Self {
|
||||
Self::new(signal)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user