Merge branch 'master' into debug-signals

This commit is contained in:
Evan Almloff committed 2023-10-31 13:55:20 -05:00
commit 8a62e4a987
149 files changed
+2440 -6196

No files matched your search

+22 -8
View File
@@ -1,16 +1,28 @@
use core::{self, fmt::Debug};
use std::cell::RefCell;
use std::fmt::{self, Formatter};
use std::rc::Rc;
//
use dioxus_core::prelude::*;
use crate::use_signal;
use crate::{dependency::Dependency, CopyValue};
#[derive(Default, Clone)]
#[derive(Copy, Clone, PartialEq)]
pub(crate) struct EffectStack {
pub(crate) effects: Rc<RefCell<Vec<Effect>>>,
pub(crate) effects: CopyValue<Vec<Effect>>,
}
impl Default for EffectStack {
fn default() -> Self {
Self {
effects: CopyValue::new_in_scope(Vec::new(), ScopeId::ROOT),
}
}
}
impl EffectStack {
pub(crate) fn current(&self) -> Option<Effect> {
self.effects.read().last().copied()
}
}
pub(crate) fn get_effect_stack() -> EffectStack {
@@ -18,7 +30,7 @@ pub(crate) fn get_effect_stack() -> EffectStack {
Some(rt) => rt,
None => {
let store = EffectStack::default();
provide_root_context(store.clone());
provide_root_context(store);
store
}
}
@@ -57,6 +69,7 @@ pub fn use_effect_with_dependencies<D: Dependency>(
pub struct Effect {
pub(crate) source: ScopeId,
pub(crate) callback: CopyValue<Box<dyn FnMut()>>,
pub(crate) effect_stack: EffectStack,
}
impl Debug for Effect {
@@ -67,7 +80,7 @@ impl Debug for Effect {
impl Effect {
pub(crate) fn current() -> Option<Self> {
get_effect_stack().effects.borrow().last().copied()
get_effect_stack().effects.read().last().copied()
}
/// Create a new effect. The effect will be run immediately and whenever any signal it reads changes.
@@ -77,6 +90,7 @@ impl Effect {
let myself = Self {
source: current_scope_id().expect("in a virtual dom"),
callback: CopyValue::new(Box::new(callback)),
effect_stack: get_effect_stack(),
};
myself.try_run();
@@ -88,11 +102,11 @@ impl Effect {
pub fn try_run(&self) {
if let Ok(mut callback) = self.callback.try_write() {
{
get_effect_stack().effects.borrow_mut().push(*self);
self.effect_stack.effects.write().push(*self);
}
callback();
{
get_effect_stack().effects.borrow_mut().pop();
self.effect_stack.effects.write().pop();
}
}
}
+8 -11
View File
@@ -38,7 +38,7 @@ macro_rules! read_impls {
impl<T: 'static> $ty<Vec<T>> {
/// Read a value from the inner vector.
pub fn get(&self, index: usize) -> Option<GenerationalRef<'_, T>> {
pub fn get(&self, index: usize) -> Option<GenerationalRef<T>> {
GenerationalRef::filter_map(self.read(), |v| v.get(index))
}
}
@@ -53,7 +53,7 @@ macro_rules! read_impls {
}
/// Attempts to read the inner value of the Option.
pub fn as_ref(&self) -> Option<GenerationalRef<'_, T>> {
pub fn as_ref(&self) -> Option<GenerationalRef<T>> {
GenerationalRef::filter_map(self.read(), |v| v.as_ref())
}
}
@@ -182,15 +182,12 @@ macro_rules! write_impls {
}
/// 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> {
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> {
pub fn get_or_insert_with(&self, default: impl FnOnce() -> T) -> GenerationalRef<T> {
let borrow = self.read();
if borrow.is_none() {
drop(borrow);
@@ -241,14 +238,14 @@ impl<T: Clone + 'static> IntoIterator for CopyValue<Vec<T>> {
impl<T: 'static> CopyValue<Vec<T>> {
/// Write to an element in the inner vector.
pub fn get_mut(&self, index: usize) -> Option<GenerationalRefMut<'_, T>> {
pub fn get_mut(&self, index: usize) -> Option<GenerationalRefMut<T>> {
GenerationalRefMut::filter_map(self.write(), |v| v.get_mut(index))
}
}
impl<T: 'static> CopyValue<Option<T>> {
/// Deref the inner value mutably.
pub fn as_mut(&self) -> Option<GenerationalRefMut<'_, T>> {
pub fn as_mut(&self) -> Option<GenerationalRefMut<T>> {
GenerationalRefMut::filter_map(self.write(), |v| v.as_mut())
}
}
@@ -284,14 +281,14 @@ impl<T: Clone + 'static> IntoIterator for Signal<Vec<T>> {
impl<T: 'static> Signal<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, Vec<T>>> {
Write::filter_map(self.write(), |v| v.get_mut(index))
}
}
impl<T: 'static> Signal<Option<T>> {
/// 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, Option<T>>> {
Write::filter_map(self.write(), |v| v.as_mut())
}
}
+2
View File
@@ -1,4 +1,6 @@
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
#![warn(missing_docs)]
mod rt;
+39 -4
View File
@@ -1,3 +1,5 @@
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::rc::Rc;
use dioxus_core::prelude::*;
@@ -133,25 +135,25 @@ 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<GenerationalRef<T>, 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) -> GenerationalRef<T> {
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<GenerationalRefMut<T>, 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) -> GenerationalRefMut<T> {
self.value.write()
}
@@ -185,3 +187,36 @@ impl<T: 'static> PartialEq for CopyValue<T> {
self.value.ptr_eq(&other.value)
}
}
impl<T> Deref for CopyValue<T> {
type Target = dyn Fn() -> GenerationalRef<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 = 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
}
}
+6 -2
View File
@@ -21,6 +21,7 @@ use crate::{get_effect_stack, signal::SignalData, CopyValue, Effect, ReadOnlySig
/// render! { "{double}" }
/// }
/// ```
#[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,
@@ -44,6 +45,7 @@ pub fn use_selector<R: PartialEq>(
/// render! { "{double}" }
/// }
/// ```
#[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,
@@ -76,19 +78,21 @@ pub fn selector<R: PartialEq>(mut f: impl FnMut() -> R + 'static) -> ReadOnlySig
let effect = Effect {
source: current_scope_id().expect("in a virtual dom"),
callback: CopyValue::invalid(),
effect_stack: get_effect_stack(),
};
{
get_effect_stack().effects.borrow_mut().push(effect);
get_effect_stack().effects.write().push(effect);
}
state.inner.value.set(SignalData {
subscribers: Default::default(),
effect_subscribers: Default::default(),
update_any: schedule_update_any().expect("in a virtual dom"),
value: f(),
effect_stack: get_effect_stack(),
});
{
get_effect_stack().effects.borrow_mut().pop();
get_effect_stack().effects.write().pop();
}
effect.callback.value.set(Box::new(move || {
+89 -10
View File
@@ -1,5 +1,6 @@
use std::{
cell::RefCell,
mem::MaybeUninit,
ops::{Deref, DerefMut},
rc::Rc,
sync::Arc,
@@ -11,7 +12,7 @@ use dioxus_core::{
};
use generational_box::{GenerationalRef, GenerationalRefMut};
use crate::{CopyValue, Effect};
use crate::{get_effect_stack, CopyValue, Effect, EffectStack};
/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
///
@@ -45,6 +46,7 @@ use crate::{CopyValue, Effect};
/// }
/// ```
#[track_caller]
#[must_use]
pub fn use_signal<T: 'static>(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal<T> {
#[cfg(debug_assertions)]
let caller = std::panic::Location::caller();
@@ -91,6 +93,7 @@ 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,
pub(crate) value: T,
}
@@ -154,6 +157,7 @@ impl<T: 'static> Signal<T> {
effect_subscribers: Default::default(),
update_any: schedule_update_any().expect("in a virtual dom"),
value,
effect_stack: get_effect_stack(),
}),
}
}
@@ -170,6 +174,7 @@ impl<T: 'static> Signal<T> {
effect_subscribers: Default::default(),
update_any: schedule_update_any().expect("in a virtual dom"),
value,
effect_stack: get_effect_stack(),
},
#[cfg(debug_assertions)]
caller,
@@ -186,6 +191,7 @@ impl<T: 'static> Signal<T> {
effect_subscribers: Default::default(),
update_any: schedule_update_any().expect("in a virtual dom"),
value,
effect_stack: get_effect_stack(),
},
owner,
),
@@ -202,7 +208,7 @@ impl<T: 'static> Signal<T> {
#[track_caller]
pub fn read(&self) -> GenerationalRef<T> {
let inner = self.inner.read();
if let Some(effect) = Effect::current() {
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);
@@ -230,7 +236,7 @@ impl<T: 'static> Signal<T> {
/// 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> {
let inner = self.inner.write();
let borrow = GenerationalRefMut::map(inner, |v| &mut v.value);
Write {
@@ -299,12 +305,52 @@ impl<T: Clone + 'static> Signal<T> {
}
}
impl Signal<bool> {
/// 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> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T> Deref for Signal<T> {
type Target = dyn Fn() -> GenerationalRef<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 = 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
}
}
struct SignalSubscriberDrop<T: 'static> {
signal: Signal<T>,
}
@@ -316,14 +362,14 @@ impl<T: 'static> Drop for SignalSubscriberDrop<T> {
}
/// A mutable reference to a signal's value.
pub struct Write<'a, T: 'static, I: 'static = T> {
write: GenerationalRefMut<'a, T>,
pub struct Write<T: 'static, I: 'static = T> {
write: GenerationalRefMut<T>,
signal: SignalSubscriberDrop<I>,
}
impl<'a, T: 'static, I: 'static> Write<'a, T, I> {
impl<T: 'static, I: 'static> Write<T, 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> {
pub fn map<O>(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<O, I> {
let Self { write, signal } = myself;
Write {
write: GenerationalRefMut::map(write, f),
@@ -335,14 +381,14 @@ 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>> {
) -> Option<Write<O, I>> {
let Self { write, signal } = myself;
let write = GenerationalRefMut::filter_map(write, f);
write.map(|write| Write { write, signal })
}
}
impl<'a, T: 'static> Deref for Write<'a, T> {
impl<T: 'static, I: 'static> Deref for Write<T, I> {
type Target = T;
fn deref(&self) -> &Self::Target {
@@ -350,7 +396,7 @@ impl<'a, T: 'static> Deref for Write<'a, T> {
}
}
impl<T> DerefMut for Write<'_, T> {
impl<T, I> DerefMut for Write<T, I> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.write
}
@@ -397,3 +443,36 @@ impl<T: 'static> PartialEq for ReadOnlySignal<T> {
self.inner == other.inner
}
}
impl<T> Deref for ReadOnlySignal<T> {
type Target = dyn Fn() -> GenerationalRef<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 = 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
}
}