Boxed and mapped signals preparing for stores (#4413)

This PR contains just the breaking changes required for the upcoming store implementation. It adds two new primitives:

Mutable mapped signals (without a different subscriber list). This lets you scope a writable value and pass it to a child component. It requires two closures to map the immutable and mutable references to the inner signal. With stores, these closures will be derived
Boxed readable and writable values (ReadSignal, and WriteSignal). Any readable or writable types can be converted to a read signal or write signal with the boxed method or built in types are automatically converted into the boxed variants when passing into props


* map signals mutably

* boxed signals

* remove mutable borrow type from boxed writable

* improve map mut example

* restore boxed_mut helper

* make boxed readable/writable types copy

* Move away from the ReadOnlySignal alias in examples

* automatically convert Write

* Fix some tests

* ReadSignal and WriteSignal

* move read only signal alias

* make maps copy

* store prototype

* implement derive macro

* Handle generics in the derive macro

* Make Selector boxable

* derive boxed conversion

* Get rid of store type

* Remove hardcoded type from derive macro

* selector -> store

* Refactor store implementation

* more vec methods

* todo mvc store example

* Implement Storable for HashMap

* fix write

* restore sorting logic in todomvc

* derive readable and writable

* improve todomvc store example

* Result store

* Option store

* collect dead subscribers

* fix clippy and formatting

* recognize some common foreign types automatically

* fix foreign stores in props

* slice and array selectors

* clean up store example

* remove stores

* writable is child owned

* fix typo

* fix clippy

* fix doc tests
This commit is contained in:
Evan Almloff authored and GitHub committed 2025-07-31 13:19:55 -07:00
1 parent 6919f72abc
commit d8d11db403
64 files changed
+1307 -726

No files matched your search

+22 -212
View File
@@ -2,15 +2,9 @@ use crate::{
default_impl, fmt_impls, read::*, write::*, write_impls, CopyValue, Global, GlobalMemo,
GlobalSignal, Memo, ReadableRef, WritableRef,
};
use dioxus_core::{IntoAttributeValue, IntoDynNode, ReactiveContext, ScopeId};
use generational_box::{AnyStorage, BorrowResult, Storage, SyncStorage, UnsyncStorage};
use std::{
any::Any,
collections::HashSet,
ops::{Deref, DerefMut},
sync::Arc,
sync::Mutex,
};
use dioxus_core::{IntoAttributeValue, IntoDynNode, ReactiveContext, ScopeId, Subscribers};
use generational_box::{BorrowResult, Storage, SyncStorage, UnsyncStorage};
use std::{any::Any, collections::HashSet, ops::Deref, sync::Arc, sync::Mutex};
#[doc = include_str!("../docs/signals.md")]
#[doc(alias = "State")]
@@ -261,7 +255,7 @@ impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
self.inner.id()
}
/// **This pattern is no longer recommended. Prefer [`peek`](Signal::peek) or creating new signals instead.**
/// **This pattern is no longer recommended. Prefer [`peek`](ReadableExt::peek) or creating new signals instead.**
///
/// This function is the equivalent of the [write_silent](https://docs.rs/dioxus/latest/dioxus/prelude/struct.UseRef.html#method.write_silent) method on use_ref.
///
@@ -289,7 +283,7 @@ impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
/// *signal.write_silent() += 1;
/// ```
///
/// Instead you can use the [`peek`](Signal::peek) and [`write`](Signal::write) methods instead. The peek method will not subscribe to the current scope which will avoid an infinite loop if you are reading and writing to the same signal in the same scope.
/// Instead you can use the [`peek`](ReadableExt::peek) and [`write`](Signal::write) methods instead. The peek method will not subscribe to the current scope which will avoid an infinite loop if you are reading and writing to the same signal in the same scope.
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// let mut signal = use_signal(|| 0);
@@ -342,7 +336,7 @@ impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
/// }
/// ```
///
/// Instead [`peek`](Signal::peek) locally opts out of automatic state updates explicitly for a specific read which is easier to reason about.
/// Instead [`peek`](ReadableExt::peek) locally opts out of automatic state updates explicitly for a specific read which is easier to reason about.
///
/// Here is the same example using peek:
/// main.rs:
@@ -378,8 +372,10 @@ impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
/// ```
#[track_caller]
#[deprecated = "This pattern is no longer recommended. Prefer `peek` or creating new signals instead."]
pub fn write_silent(&self) -> S::Mut<'static, T> {
S::map_mut(self.inner.write_unchecked(), |inner| &mut inner.value)
pub fn write_silent(&self) -> WriteLock<'static, T, S> {
WriteLock::map(self.inner.write_unchecked(), |inner: &mut SignalData<T>| {
&mut inner.value
})
}
}
@@ -408,34 +404,14 @@ impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
.try_read_unchecked()
.map(|inner| S::map(inner, |v| &v.value))
}
fn subscribers(&self) -> Option<Subscribers> {
Some(self.inner.read().subscribers.clone().into())
}
}
impl<T: 'static, S: Storage<SignalData<T>>> Writable for Signal<T, S> {
type Mut<'a, R: ?Sized + 'static> = Write<'a, R, S>;
fn map_mut<I: ?Sized, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
ref_: Self::Mut<'_, I>,
f: F,
) -> Self::Mut<'_, U> {
Write::map(ref_, f)
}
fn try_map_mut<
I: ?Sized + 'static,
U: ?Sized + 'static,
F: FnOnce(&mut I) -> Option<&mut U>,
>(
ref_: Self::Mut<'_, I>,
f: F,
) -> Option<Self::Mut<'_, U>> {
Write::filter_map(ref_, f)
}
fn downcast_lifetime_mut<'a: 'b, 'b, R: ?Sized + 'static>(
mut_: Self::Mut<'a, R>,
) -> Self::Mut<'b, R> {
Write::downcast_lifetime(mut_)
}
type WriteMetadata = Box<dyn Any>;
#[track_caller]
fn try_write_unchecked(
@@ -444,15 +420,15 @@ impl<T: 'static, S: Storage<SignalData<T>>> Writable for Signal<T, S> {
#[cfg(debug_assertions)]
let origin = std::panic::Location::caller();
self.inner.try_write_unchecked().map(|inner| {
let borrow = S::map_mut(inner, |v| &mut v.value);
Write {
write: borrow,
drop_signal: Box::new(SignalSubscriberDrop {
let borrow = S::map_mut(inner.into_inner(), |v| &mut v.value);
WriteLock::new_with_metadata(
borrow,
Box::new(SignalSubscriberDrop {
signal: *self,
#[cfg(debug_assertions)]
origin,
}),
}
}) as Box<dyn Any>,
)
})
}
}
@@ -490,7 +466,7 @@ impl<T: Clone, S: Storage<SignalData<T>> + 'static> Deref for Signal<T, S> {
type Target = dyn Fn() -> T;
fn deref(&self) -> &Self::Target {
unsafe { Readable::deref_impl(self) }
unsafe { ReadableExt::deref_impl(self) }
}
}
@@ -512,172 +488,6 @@ impl<'de, T: serde::Deserialize<'de> + 'static, Store: Storage<SignalData<T>>>
}
}
/// A mutable reference to a signal's value. This reference acts similarly to [`std::cell::RefMut`], but it has extra debug information
/// and integrates with the reactive system to automatically update dependents.
///
/// [`Write`] implements [`DerefMut`] which means you can call methods on the inner value just like you would on a mutable reference
/// to the inner value. If you need to get the inner reference directly, you can call [`Write::deref_mut`].
///
/// # Example
/// ```rust
/// # use dioxus::prelude::*;
/// fn app() -> Element {
/// let mut value = use_signal(|| String::from("hello"));
///
/// rsx! {
/// button {
/// onclick: move |_| {
/// let mut mutable_reference = value.write();
///
/// // You call methods like `push_str` on the reference just like you would with the inner String
/// mutable_reference.push_str("world");
/// },
/// "Click to add world to the string"
/// }
/// div { "{value}" }
/// }
/// }
/// ```
///
/// ## Matching on Write
///
/// You need to get the inner mutable reference with [`Write::deref_mut`] before you match the inner value. If you try to match
/// without calling [`Write::deref_mut`], you will get an error like this:
///
/// ```compile_fail
/// # use dioxus::prelude::*;
/// #[derive(Debug)]
/// enum Colors {
/// Red(u32),
/// Green
/// }
/// fn app() -> Element {
/// let mut value = use_signal(|| Colors::Red(0));
///
/// rsx! {
/// button {
/// onclick: move |_| {
/// let mut mutable_reference = value.write();
///
/// match mutable_reference {
/// // Since we are matching on the `Write` type instead of &mut Colors, we can't match on the enum directly
/// Colors::Red(brightness) => *brightness += 1,
/// Colors::Green => {}
/// }
/// },
/// "Click to add brightness to the red color"
/// }
/// div { "{value:?}" }
/// }
/// }
/// ```
///
/// ```text
/// error[E0308]: mismatched types
/// --> src/main.rs:18:21
/// |
/// 16 | match mutable_reference {
/// | ----------------- this expression has type `dioxus::prelude::Write<'_, Colors>`
/// 17 | // Since we are matching on the `Write` t...
/// 18 | Colors::Red(brightness) => *brightness += 1,
/// | ^^^^^^^^^^^^^^^^^^^^^^^ expected `Write<'_, Colors>`, found `Colors`
/// |
/// = note: expected struct `dioxus::prelude::Write<'_, Colors, >`
/// found enum `Colors`
/// ```
///
/// Instead, you need to call deref mut on the reference to get the inner value **before** you match on it:
///
/// ```rust
/// use std::ops::DerefMut;
/// # use dioxus::prelude::*;
/// #[derive(Debug)]
/// enum Colors {
/// Red(u32),
/// Green
/// }
/// fn app() -> Element {
/// let mut value = use_signal(|| Colors::Red(0));
///
/// rsx! {
/// button {
/// onclick: move |_| {
/// let mut mutable_reference = value.write();
///
/// // DerefMut converts the `Write` into a `&mut Colors`
/// match mutable_reference.deref_mut() {
/// // Now we can match on the inner value
/// Colors::Red(brightness) => *brightness += 1,
/// Colors::Green => {}
/// }
/// },
/// "Click to add brightness to the red color"
/// }
/// div { "{value:?}" }
/// }
/// }
/// ```
///
/// ## Generics
/// - T is the current type of the write
/// - S is the storage type of the signal. This type determines if the signal is local to the current thread, or it can be shared across threads.
pub struct Write<'a, T: ?Sized + 'static, S: AnyStorage = UnsyncStorage> {
write: S::Mut<'a, T>,
drop_signal: Box<dyn Any>,
}
impl<'a, T: ?Sized + 'static, S: AnyStorage> Write<'a, T, S> {
/// Map the mutable reference to the signal's value to a new type.
pub fn map<O: ?Sized>(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<'a, O, S> {
let Self {
write, drop_signal, ..
} = myself;
Write {
write: S::map_mut(write, f),
drop_signal,
}
}
/// Try to map the mutable reference to the signal's value to a new type
pub fn filter_map<O: ?Sized>(
myself: Self,
f: impl FnOnce(&mut T) -> Option<&mut O>,
) -> Option<Write<'a, O, S>> {
let Self {
write, drop_signal, ..
} = myself;
let write = S::try_map_mut(write, f);
write.map(|write| Write { write, drop_signal })
}
/// Downcast the lifetime of the mutable reference to the signal's value.
///
/// This function enforces the variance of the lifetime parameter `'a` in Mut. Rust will typically infer this cast with a concrete type, but it cannot with a generic type.
pub fn downcast_lifetime<'b>(mut_: Self) -> Write<'b, T, S>
where
'a: 'b,
{
Write {
write: S::downcast_lifetime_mut(mut_.write),
drop_signal: mut_.drop_signal,
}
}
}
impl<T: ?Sized + 'static, S: AnyStorage> Deref for Write<'_, T, S> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.write
}
}
impl<T: ?Sized, S: AnyStorage> DerefMut for Write<'_, T, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.write
}
}
struct SignalSubscriberDrop<T: 'static, S: Storage<SignalData<T>>> {
signal: Signal<T, S>,
#[cfg(debug_assertions)]