move hooks out of signals crate
This commit is contained in:
13 files changed
+386
-429
No files matched your search
@@ -0,0 +1,67 @@
|
||||
/// A dependency is a trait that can be used to determine if a effect or selector should be re-run.
|
||||
pub trait Dependency: Sized + Clone {
|
||||
/// The output of the dependency
|
||||
type Out: Clone + PartialEq;
|
||||
/// Returns the output of the dependency.
|
||||
fn out(&self) -> Self::Out;
|
||||
/// Returns true if the dependency has changed.
|
||||
fn changed(&self, other: &Self::Out) -> bool {
|
||||
self.out() != *other
|
||||
}
|
||||
}
|
||||
|
||||
impl Dependency for () {
|
||||
type Out = ();
|
||||
fn out(&self) -> Self::Out {}
|
||||
}
|
||||
|
||||
/// A dependency is a trait that can be used to determine if a effect or selector should be re-run.
|
||||
pub trait Dep: 'static + PartialEq + Clone {}
|
||||
impl<T> Dep for T where T: 'static + PartialEq + Clone {}
|
||||
|
||||
impl<A: Dep> Dependency for &A {
|
||||
type Out = A;
|
||||
fn out(&self) -> Self::Out {
|
||||
(*self).clone()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_dep {
|
||||
(
|
||||
$($el:ident=$name:ident $other:ident,)*
|
||||
) => {
|
||||
impl< $($el),* > Dependency for ($(&$el,)*)
|
||||
where
|
||||
$(
|
||||
$el: Dep
|
||||
),*
|
||||
{
|
||||
type Out = ($($el,)*);
|
||||
|
||||
fn out(&self) -> Self::Out {
|
||||
let ($($name,)*) = self;
|
||||
($((*$name).clone(),)*)
|
||||
}
|
||||
|
||||
fn changed(&self, other: &Self::Out) -> bool {
|
||||
let ($($name,)*) = self;
|
||||
let ($($other,)*) = other;
|
||||
$(
|
||||
if *$name != $other {
|
||||
return true;
|
||||
}
|
||||
)*
|
||||
false
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_dep!(A = a1 a2,);
|
||||
impl_dep!(A = a1 a2, B = b1 b2,);
|
||||
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2,);
|
||||
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2,);
|
||||
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2,);
|
||||
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2,);
|
||||
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2, G = g1 g2,);
|
||||
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2, G = g1 g2, H = h1 h2,);
|
||||
@@ -54,6 +54,8 @@ macro_rules! to_owned {
|
||||
$(to_owned![$($rest)*])?
|
||||
};
|
||||
}
|
||||
mod dependency;
|
||||
pub use dependency::*;
|
||||
|
||||
mod use_callback;
|
||||
pub use use_callback::*;
|
||||
@@ -76,6 +78,12 @@ pub use use_sorted::*;
|
||||
mod use_resource;
|
||||
pub use use_resource::*;
|
||||
|
||||
mod use_effect;
|
||||
pub use use_effect::*;
|
||||
|
||||
mod use_memo;
|
||||
pub use use_memo::*;
|
||||
|
||||
// mod use_on_create;
|
||||
// pub use use_on_create::*;
|
||||
|
||||
@@ -84,3 +92,6 @@ pub use use_root_context::*;
|
||||
|
||||
mod use_hook_did_run;
|
||||
pub use use_hook_did_run::*;
|
||||
|
||||
mod use_signal;
|
||||
pub use use_signal::*;
|
||||
@@ -0,0 +1,24 @@
|
||||
use crate::use_hook_did_run;
|
||||
use dioxus_core::prelude::*;
|
||||
use dioxus_signals::{CopyValue, Effect, Writable};
|
||||
|
||||
/// Create a new effect. The effect will be run immediately and whenever any signal it reads changes.
|
||||
/// The signal will be owned by the current component and will be dropped when the component is dropped.
|
||||
///
|
||||
/// If the use_effect call was skipped due to an early return, the effect will no longer activate.
|
||||
pub fn use_effect(mut callback: impl FnMut() + 'static) {
|
||||
let mut run_effect = use_hook(|| CopyValue::new(true));
|
||||
|
||||
use_hook_did_run(move |did_run| match did_run {
|
||||
true => run_effect.set(true),
|
||||
false => run_effect.set(false),
|
||||
});
|
||||
|
||||
use_hook(|| {
|
||||
Effect::new(move || {
|
||||
if run_effect() {
|
||||
callback();
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
+110
-34
@@ -1,47 +1,123 @@
|
||||
use dioxus_core::ScopeState;
|
||||
use dioxus_core::prelude::*;
|
||||
use dioxus_signals::{CopyValue, ReadOnlySignal, Readable, Signal, SignalData};
|
||||
use dioxus_signals::{Storage, Writable};
|
||||
// use generational_box::Storage;
|
||||
|
||||
use crate::UseFutureDep;
|
||||
use crate::{dependency::Dependency, use_hook_did_run};
|
||||
use dioxus_signals::use_signal;
|
||||
// use dioxus_signals::{signal::SignalData, ReadOnlySignal, Signal};
|
||||
|
||||
/// A hook that provides a callback that executes if the dependencies change.
|
||||
/// This is useful to avoid running computation-expensive calculations even when the data doesn't change.
|
||||
/// Creates a new unsync Selector. The selector will be run immediately and whenever any signal it reads changes.
|
||||
///
|
||||
/// - dependencies: a tuple of references to values that are `PartialEq` + `Clone`
|
||||
/// Selectors can be used to efficiently compute derived data from signals.
|
||||
///
|
||||
/// ## Examples
|
||||
/// ```rust
|
||||
/// use dioxus::prelude::*;
|
||||
/// use dioxus_signals::*;
|
||||
///
|
||||
/// ```rust, no_run
|
||||
/// # use dioxus::prelude::*;
|
||||
///
|
||||
/// #[component]
|
||||
/// fn Calculator(number: usize) -> Element {
|
||||
/// let bigger_number = use_memo((number,), |(number,)| {
|
||||
/// // This will only be calculated when `number` has changed.
|
||||
/// number * 100
|
||||
/// });
|
||||
/// rsx!(
|
||||
/// p { "{bigger_number}" }
|
||||
/// )
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// fn App() -> Element {
|
||||
/// rsx!(Calculator { number: 0 })
|
||||
/// let mut count = use_signal(|| 0);
|
||||
/// let double = use_memo(move || count * 2);
|
||||
/// count += 1;
|
||||
/// assert_eq!(double.value(), count * 2);
|
||||
///
|
||||
/// rsx! { "{double}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[must_use = "Consider using `use_effect` to run rerun a callback when dependencies change"]
|
||||
pub fn use_memo<T, D>(, dependencies: D, callback: impl FnOnce(D::Out) -> T) -> &T
|
||||
#[track_caller]
|
||||
pub fn use_memo<R: PartialEq>(f: impl FnMut() -> R + 'static) -> ReadOnlySignal<R> {
|
||||
use_maybe_sync_memo(f)
|
||||
}
|
||||
|
||||
/// Creates a new Selector that may be sync. The selector will be run immediately and whenever any signal it reads changes.
|
||||
///
|
||||
/// Selectors can be used to efficiently compute derived data from signals.
|
||||
///
|
||||
/// ```rust
|
||||
/// use dioxus::prelude::*;
|
||||
/// use dioxus_signals::*;
|
||||
///
|
||||
/// fn App(cx: Scope) -> Element {
|
||||
/// let mut count = use_signal(cx, || 0);
|
||||
/// let double = use_memo(cx, move || count * 2);
|
||||
/// count += 1;
|
||||
/// assert_eq!(double.value(), count * 2);
|
||||
///
|
||||
/// render! { "{double}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
pub fn use_maybe_sync_memo<R: PartialEq, S: Storage<SignalData<R>>>(
|
||||
f: impl FnMut() -> R + 'static,
|
||||
) -> ReadOnlySignal<R, S> {
|
||||
use_hook(|| Signal::maybe_sync_memo(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_memo_with_dependencies(cx, (local_state.get(),), move |(local_state,)| local_state * 2);
|
||||
/// local_state.set(1);
|
||||
///
|
||||
/// render! { "{double}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
pub fn use_memo_with_dependencies<R: PartialEq, D: Dependency>(
|
||||
dependencies: D,
|
||||
f: impl FnMut(D::Out) -> R + 'static,
|
||||
) -> ReadOnlySignal<R>
|
||||
where
|
||||
T: 'static,
|
||||
D: UseFutureDep,
|
||||
D::Out: 'static,
|
||||
{
|
||||
let value = cx.use_hook(|| None);
|
||||
use_maybe_sync_selector_with_dependencies(dependencies, f)
|
||||
}
|
||||
|
||||
let dependancies_vec = cx.use_hook(Vec::new);
|
||||
|
||||
if dependencies.clone().apply(dependancies_vec) || value.is_none() {
|
||||
// Create the new value
|
||||
*value = Some(callback(dependencies.out()));
|
||||
/// 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_memo_with_dependencies(cx, (local_state.get(),), move |(local_state,)| local_state * 2);
|
||||
/// local_state.set(1);
|
||||
///
|
||||
/// render! { "{double}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
pub fn use_maybe_sync_selector_with_dependencies<
|
||||
R: PartialEq,
|
||||
D: Dependency,
|
||||
S: Storage<SignalData<R>>,
|
||||
>(
|
||||
dependencies: D,
|
||||
mut f: impl FnMut(D::Out) -> R + 'static,
|
||||
) -> ReadOnlySignal<R, S>
|
||||
where
|
||||
D::Out: 'static,
|
||||
{
|
||||
let mut dependencies_signal = use_signal(|| dependencies.out());
|
||||
let selector = use_hook(|| {
|
||||
Signal::maybe_sync_memo(move || {
|
||||
let deref = &*dependencies_signal.read();
|
||||
f(deref.clone())
|
||||
})
|
||||
});
|
||||
let changed = { dependencies.changed(&*dependencies_signal.read()) };
|
||||
if changed {
|
||||
dependencies_signal.set(dependencies.out());
|
||||
}
|
||||
|
||||
value.as_ref().unwrap()
|
||||
selector
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use dioxus_core::prelude::*;
|
||||
use dioxus_signals::{Signal, SignalData, Storage, SyncStorage, UnsyncStorage};
|
||||
|
||||
/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
|
||||
///
|
||||
/// ```rust
|
||||
/// use dioxus::prelude::*;
|
||||
/// use dioxus_signals::*;
|
||||
///
|
||||
/// fn App() -> Element {
|
||||
/// let mut count = use_signal(|| 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.
|
||||
/// rsx! { Child { state: count } }
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// fn Child(state: Signal<u32>) -> Element {
|
||||
/// let state = *state;
|
||||
///
|
||||
/// use_future( |()| async move {
|
||||
/// // Because the signal is a Copy type, we can use it in an async block without cloning it.
|
||||
/// *state.write() += 1;
|
||||
/// });
|
||||
///
|
||||
/// rsx! {
|
||||
/// button {
|
||||
/// onclick: move |_| *state.write() += 1,
|
||||
/// "{state}"
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
#[must_use]
|
||||
pub fn use_signal<T: 'static>(f: impl FnOnce() -> T) -> Signal<T, UnsyncStorage> {
|
||||
use_maybe_signal_sync(f)
|
||||
}
|
||||
|
||||
/// 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>(f: impl FnOnce() -> T) -> Signal<T, SyncStorage> {
|
||||
use_maybe_signal_sync(f)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[track_caller]
|
||||
fn use_maybe_signal_sync<T: 'static, U: Storage<SignalData<T>>>(
|
||||
f: impl FnOnce() -> T,
|
||||
) -> Signal<T, U> {
|
||||
#[cfg(debug_assertions)]
|
||||
let caller = std::panic::Location::caller();
|
||||
|
||||
let signal = use_hook(|| {
|
||||
Signal::new_with_caller(
|
||||
f(),
|
||||
#[cfg(debug_assertions)]
|
||||
caller,
|
||||
)
|
||||
});
|
||||
|
||||
// By default, we want to unsubscribe the current component from the signal on every render
|
||||
// any calls to .read() in the body will re-subscribe the component to the signal
|
||||
use_before_render(|| signal.unsubscribe(current_scope_id().unwrap()));
|
||||
|
||||
signal
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::ops::DerefMut;
|
||||
|
||||
use dioxus_signals::{use_memo, ReadOnlySignal, Signal};
|
||||
use crate::use_memo;
|
||||
use dioxus_signals::{ReadOnlySignal, Signal};
|
||||
|
||||
pub fn use_sorted<V: 'static, T: PartialEq>(
|
||||
collection: impl FnMut() -> Signal<V>,
|
||||
|
||||
Reference in new issue
Block a user