Merge branch 'master' into jk/coroutine-coroutineoverhaul
This commit is contained in:
commit
f1af18c60b
213 files changed
+6234
-4644
No files matched your search
+22
-42
@@ -16,45 +16,25 @@ pub use usefuture::*;
|
||||
mod usesuspense;
|
||||
pub use usesuspense::*;
|
||||
|
||||
// #[macro_export]
|
||||
// macro_rules! to_owned {
|
||||
// ($($es:ident),+) => {$(
|
||||
// #[allow(unused_mut)]
|
||||
// let mut $es = $es.to_owned();
|
||||
// )*}
|
||||
// }
|
||||
|
||||
// /// Calls `for_async` on the series of paramters.
|
||||
// ///
|
||||
// /// If the type is Clone, then it will be cloned. However, if the type is not `clone`
|
||||
// /// then it must have a `for_async` method for Rust to lower down into.
|
||||
// ///
|
||||
// /// See: how use_state implements `for_async` but *not* through the trait.
|
||||
// #[macro_export]
|
||||
// macro_rules! for_async {
|
||||
// ($($es:ident),+) => {$(
|
||||
// #[allow(unused_mut)]
|
||||
// let mut $es = $es.for_async();
|
||||
// )*}
|
||||
// }
|
||||
|
||||
// /// This is a marker trait that uses decoherence.
|
||||
// ///
|
||||
// /// It is *not* meant for hooks to actually implement, but rather defer to their
|
||||
// /// underlying implementation if they *don't* implement the trait.
|
||||
// ///
|
||||
// ///
|
||||
// pub trait AsyncHook {
|
||||
// type Output;
|
||||
// fn for_async(self) -> Self::Output;
|
||||
// }
|
||||
|
||||
// impl<T> AsyncHook for T
|
||||
// where
|
||||
// T: ToOwned<Owned = T>,
|
||||
// {
|
||||
// type Output = T;
|
||||
// fn for_async(self) -> Self::Output {
|
||||
// self
|
||||
// }
|
||||
// }
|
||||
#[macro_export]
|
||||
/// A helper macro for using hooks in async environements.
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
///
|
||||
/// ```
|
||||
/// let (data) = use_ref(&cx, || {});
|
||||
///
|
||||
/// let handle_thing = move |_| {
|
||||
/// to_owned![data]
|
||||
/// cx.spawn(async move {
|
||||
/// // do stuff
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
macro_rules! to_owned {
|
||||
($($es:ident),+) => {$(
|
||||
#[allow(unused_mut)]
|
||||
let mut $es = $es.to_owned();
|
||||
)*}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ impl<T> ProvidedStateInner<T> {
|
||||
/// This hook provides some relatively light ergonomics around shared state.
|
||||
///
|
||||
/// It is not a substitute for a proper state management system, but it is capable enough to provide use_state - type
|
||||
/// ergonimics in a pinch, with zero cost.
|
||||
/// ergonomics in a pinch, with zero cost.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
|
||||
+207
-37
@@ -1,57 +1,227 @@
|
||||
use dioxus_core::ScopeState;
|
||||
use std::{
|
||||
cell::{Ref, RefCell, RefMut},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use dioxus_core::ScopeState;
|
||||
|
||||
pub fn use_ref<'a, T: 'static>(cx: &'a ScopeState, f: impl FnOnce() -> T) -> &'a UseRef<T> {
|
||||
/// `use_ref` is a key foundational hook for storing state in Dioxus.
|
||||
///
|
||||
/// It is different that `use_state` in that the value stored is not "immutable".
|
||||
/// Instead, UseRef is designed to store larger values that will be mutated at will.
|
||||
///
|
||||
/// ## Writing Values
|
||||
///
|
||||
/// Generally, `use_ref` is just a wrapper around a RefCell that tracks mutable
|
||||
/// writes through the `write` method. Whenever `write` is called, the component
|
||||
/// that initialized the hook will be marked as "dirty".
|
||||
///
|
||||
/// ```rust
|
||||
/// let val = use_ref(|| HashMap::<u32, String>::new());
|
||||
///
|
||||
/// // using `write` will give us a `RefMut` to the inner value, which we can call methods on
|
||||
/// // This marks the component as "dirty"
|
||||
/// val.write().insert(1, "hello".to_string());
|
||||
/// ```
|
||||
///
|
||||
/// You can avoid this defualt behavior with `write_silent`
|
||||
///
|
||||
/// ```
|
||||
/// // with `write_silent`, the component will not be re-rendered
|
||||
/// val.write_silent().insert(2, "goodbye".to_string());
|
||||
/// ```
|
||||
///
|
||||
/// ## Reading Values
|
||||
///
|
||||
/// To read values out of the refcell, you can use the `read` method which will retrun a `Ref`.
|
||||
///
|
||||
/// ```rust
|
||||
/// let map: Ref<_> = val.read();
|
||||
///
|
||||
/// let item = map.get(&1);
|
||||
/// ```
|
||||
///
|
||||
/// To get an &T out of the RefCell, you need to "reborrow" through the Ref:
|
||||
///
|
||||
/// ```rust
|
||||
/// let read = val.read();
|
||||
/// let map = &*read;
|
||||
/// ```
|
||||
///
|
||||
/// ## Collections and iteration
|
||||
///
|
||||
/// A common usecase for `use_ref` is to store a large amount of data in a component.
|
||||
/// Typically this will be a collection like a HashMap or a Vec. To create new
|
||||
/// elements from the collection, we can use `read()` directly in our rsx!.
|
||||
///
|
||||
/// ```rust
|
||||
/// rsx!{
|
||||
/// val.read().iter().map(|(k, v)| {
|
||||
/// rsx!{ key: "{k}", value: "{v}" }
|
||||
/// })
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If you are generating elements outside of `rsx!` then you might need to call
|
||||
/// "render" inside the iterator. For some cases you might need to collect into
|
||||
/// a temporary Vec.
|
||||
///
|
||||
/// ```rust
|
||||
/// let items = val.read().iter().map(|(k, v)| {
|
||||
/// cx.render(rsx!{ key: "{k}", value: "{v}" })
|
||||
/// });
|
||||
///
|
||||
/// // collect into a Vec
|
||||
///
|
||||
/// let items: Vec<Element> = items.collect();
|
||||
/// ```
|
||||
///
|
||||
/// ## Use in Async
|
||||
///
|
||||
/// To access values from a `UseRef` in an async context, you need to detach it
|
||||
/// from the current scope's lifetime, making it a `'static` value. This is done
|
||||
/// by simply calling `ToOnwed` or `Clone`.
|
||||
///
|
||||
/// ```rust
|
||||
/// let val = use_ref(|| HashMap::<u32, String>::new());
|
||||
///
|
||||
/// cx.spawn({
|
||||
/// let val = val.clone();
|
||||
/// async move {
|
||||
/// some_work().await;
|
||||
/// val.write().insert(1, "hello".to_string());
|
||||
/// }
|
||||
/// })
|
||||
/// ```
|
||||
///
|
||||
/// If you're working with lots of values like UseState and UseRef, you can use the
|
||||
/// `clone!` macro to make it easier to write the above code.
|
||||
///
|
||||
/// ```rust
|
||||
/// let val1 = use_ref(|| HashMap::<u32, String>::new());
|
||||
/// let val2 = use_ref(|| HashMap::<u32, String>::new());
|
||||
/// let val3 = use_ref(|| HashMap::<u32, String>::new());
|
||||
///
|
||||
/// cx.spawn({
|
||||
/// clone![val1, val2, val3];
|
||||
/// async move {
|
||||
/// some_work().await;
|
||||
/// val.write().insert(1, "hello".to_string());
|
||||
/// }
|
||||
/// })
|
||||
/// ```
|
||||
pub fn use_ref<'a, T: 'static>(
|
||||
cx: &'a ScopeState,
|
||||
initialize_refcell: impl FnOnce() -> T,
|
||||
) -> &'a UseRef<T> {
|
||||
cx.use_hook(|_| UseRef {
|
||||
update_callback: cx.schedule_update(),
|
||||
value: Rc::new(RefCell::new(f())),
|
||||
update: cx.schedule_update(),
|
||||
value: Rc::new(RefCell::new(initialize_refcell())),
|
||||
})
|
||||
}
|
||||
|
||||
/// A type created by the [`use_ref`] hook. See its documentation for more details.
|
||||
pub struct UseRef<T> {
|
||||
update_callback: Rc<dyn Fn()>,
|
||||
update: Rc<dyn Fn()>,
|
||||
value: Rc<RefCell<T>>,
|
||||
}
|
||||
|
||||
impl<T> UseRef<T> {
|
||||
pub fn read(&self) -> Ref<'_, T> {
|
||||
self.value.borrow()
|
||||
}
|
||||
|
||||
pub fn set(&self, new: T) {
|
||||
*self.value.borrow_mut() = new;
|
||||
self.needs_update();
|
||||
}
|
||||
|
||||
pub fn read_write(&self) -> (Ref<'_, T>, &Self) {
|
||||
(self.read(), self)
|
||||
}
|
||||
|
||||
/// Calling "write" will force the component to re-render
|
||||
pub fn write(&self) -> RefMut<'_, T> {
|
||||
self.needs_update();
|
||||
self.value.borrow_mut()
|
||||
}
|
||||
|
||||
/// Allows the ability to write the value without forcing a re-render
|
||||
pub fn write_silent(&self) -> RefMut<'_, T> {
|
||||
self.value.borrow_mut()
|
||||
}
|
||||
|
||||
pub fn needs_update(&self) {
|
||||
(self.update_callback)();
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for UseRef<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
update_callback: self.update_callback.clone(),
|
||||
update: self.update.clone(),
|
||||
value: self.value.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> UseRef<T> {
|
||||
/// Read the value in the RefCell into a `Ref`. If this method is called
|
||||
/// while other values are still being `read` or `write`, then your app will crash.
|
||||
///
|
||||
/// Be very careful when working with this method. If you can, consider using
|
||||
/// the `with` and `with_mut` methods instead, choosing to render Elements
|
||||
/// during the read calls.
|
||||
pub fn read(&self) -> Ref<'_, T> {
|
||||
self.value.borrow()
|
||||
}
|
||||
|
||||
/// Set the curernt value to `new_value`. This will mark the component as "dirty"
|
||||
///
|
||||
/// This change will propogate immediately, so any other contexts that are
|
||||
/// using this RefCell will also be affected. If called during an async context,
|
||||
/// the component will not be re-rendered until the next `.await` call.
|
||||
pub fn set(&self, new: T) {
|
||||
*self.value.borrow_mut() = new;
|
||||
self.needs_update();
|
||||
}
|
||||
|
||||
/// Mutably unlock the value in the RefCell. This will mark the component as "dirty"
|
||||
///
|
||||
/// Uses to `write` should be as short as possible.
|
||||
///
|
||||
/// Be very careful when working with this method. If you can, consider using
|
||||
/// the `with` and `with_mut` methods instead, choosing to render Elements
|
||||
/// during the read and write calls.
|
||||
pub fn write(&self) -> RefMut<'_, T> {
|
||||
self.needs_update();
|
||||
self.value.borrow_mut()
|
||||
}
|
||||
|
||||
/// Mutably unlock the value in the RefCell. This will not mark the component as dirty.
|
||||
/// This is useful if you want to do some work without causing the component to re-render.
|
||||
///
|
||||
/// Uses to `write` should be as short as possible.
|
||||
///
|
||||
/// Be very careful when working with this method. If you can, consider using
|
||||
/// the `with` and `with_mut` methods instead, choosing to render Elements
|
||||
pub fn write_silent(&self) -> RefMut<'_, T> {
|
||||
self.value.borrow_mut()
|
||||
}
|
||||
|
||||
/// Take a reference to the inner value termporarily and produce a new value
|
||||
///
|
||||
/// Note: You can always "reborrow" the value through the RefCell.
|
||||
/// This method just does it for you automatically.
|
||||
///
|
||||
/// ```rust
|
||||
/// let val = use_ref(|| HashMap::<u32, String>::new());
|
||||
///
|
||||
///
|
||||
/// // use reborrowing
|
||||
/// let inner = &*val.read();
|
||||
///
|
||||
/// // or, be safer and use `with`
|
||||
/// val.with(|i| println!("{:?}", i));
|
||||
/// ```
|
||||
pub fn with<O>(&self, immutable_callback: impl FnOnce(&T) -> O) -> O {
|
||||
immutable_callback(&*self.read())
|
||||
}
|
||||
|
||||
/// Take a reference to the inner value termporarily and produce a new value,
|
||||
/// modifying the original in place.
|
||||
///
|
||||
/// Note: You can always "reborrow" the value through the RefCell.
|
||||
/// This method just does it for you automatically.
|
||||
///
|
||||
/// ```rust
|
||||
/// let val = use_ref(|| HashMap::<u32, String>::new());
|
||||
///
|
||||
///
|
||||
/// // use reborrowing
|
||||
/// let inner = &mut *val.write();
|
||||
///
|
||||
/// // or, be safer and use `with`
|
||||
/// val.with_mut(|i| i.insert(1, "hi"));
|
||||
/// ```
|
||||
pub fn with_mut<O>(&self, mutable_callback: impl FnOnce(&mut T) -> O) -> O {
|
||||
mutable_callback(&mut *self.write())
|
||||
}
|
||||
|
||||
/// Call the inner callback to mark the originator component as dirty.
|
||||
///
|
||||
/// This will cause the component to be re-rendered after the current scope
|
||||
/// has ended or the current async task has been yielded through await.
|
||||
pub fn needs_update(&self) {
|
||||
(self.update)();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
#![warn(clippy::pedantic)]
|
||||
|
||||
use dioxus_core::prelude::*;
|
||||
use std::{
|
||||
cell::{RefCell, RefMut},
|
||||
fmt::{Debug, Display},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
/// Store state between component renders.
|
||||
///
|
||||
/// ## Dioxus equivalent of useState, designed for Rust
|
||||
///
|
||||
/// The Dioxus version of `useState` for state management inside components. It allows you to ergonomically store and
|
||||
/// modify state between component renders. When the state is updated, the component will re-render.
|
||||
///
|
||||
///
|
||||
/// ```ignore
|
||||
/// const Example: Component = |cx| {
|
||||
/// let (count, set_count) = use_state(&cx, || 0);
|
||||
///
|
||||
/// cx.render(rsx! {
|
||||
/// div {
|
||||
/// h1 { "Count: {count}" }
|
||||
/// button { onclick: move |_| set_count(a - 1), "Increment" }
|
||||
/// button { onclick: move |_| set_count(a + 1), "Decrement" }
|
||||
/// }
|
||||
/// ))
|
||||
/// }
|
||||
/// ```
|
||||
pub fn use_state<'a, T: 'static>(
|
||||
cx: &'a ScopeState,
|
||||
initial_state_fn: impl FnOnce() -> T,
|
||||
) -> (&'a T, &'a UseState<T>) {
|
||||
let hook = cx.use_hook(move |_| {
|
||||
let current_val = Rc::new(initial_state_fn());
|
||||
let update_callback = cx.schedule_update();
|
||||
let slot = Rc::new(RefCell::new(current_val.clone()));
|
||||
let setter = Rc::new({
|
||||
crate::to_owned![update_callback, slot];
|
||||
move |new| {
|
||||
{
|
||||
let mut slot = slot.borrow_mut();
|
||||
|
||||
// if there's only one reference (weak or otherwise), we can just swap the values
|
||||
// Typically happens when the state is set multiple times - we don't want to create a new Rc for each new value
|
||||
if let Some(val) = Rc::get_mut(&mut slot) {
|
||||
*val = new;
|
||||
} else {
|
||||
*slot = Rc::new(new);
|
||||
}
|
||||
}
|
||||
update_callback();
|
||||
}
|
||||
});
|
||||
|
||||
UseState {
|
||||
current_val,
|
||||
update_callback,
|
||||
setter,
|
||||
slot,
|
||||
}
|
||||
});
|
||||
|
||||
hook.current_val = hook.slot.borrow().clone();
|
||||
|
||||
(hook.current_val.as_ref(), hook)
|
||||
}
|
||||
|
||||
pub struct UseState<T: 'static> {
|
||||
pub(crate) current_val: Rc<T>,
|
||||
pub(crate) update_callback: Rc<dyn Fn()>,
|
||||
pub(crate) setter: Rc<dyn Fn(T)>,
|
||||
pub(crate) slot: Rc<RefCell<Rc<T>>>,
|
||||
}
|
||||
|
||||
impl<T: 'static> UseState<T> {
|
||||
/// Get the current value of the state by cloning its container Rc.
|
||||
///
|
||||
/// This is useful when you are dealing with state in async contexts but need
|
||||
/// to know the current value. You are not given a reference to the state.
|
||||
///
|
||||
/// # Examples
|
||||
/// An async context might need to know the current value:
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// fn component(cx: Scope) -> Element {
|
||||
/// let (count, set_count) = use_state(&cx, || 0);
|
||||
/// cx.spawn({
|
||||
/// let set_count = set_count.to_owned();
|
||||
/// async move {
|
||||
/// let current = set_count.current();
|
||||
/// }
|
||||
/// })
|
||||
/// }
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn current(&self) -> Rc<T> {
|
||||
self.slot.borrow().clone()
|
||||
}
|
||||
|
||||
/// Get the `setter` function directly without the `UseState` wrapper.
|
||||
///
|
||||
/// This is useful for passing the setter function to other components.
|
||||
///
|
||||
/// However, for most cases, calling `to_owned` o`UseState`te is the
|
||||
/// preferred way to get "anoth`set_state`tate handle.
|
||||
///
|
||||
///
|
||||
/// # Examples
|
||||
/// A component might require an `Rc<dyn Fn(T)>` as an input to set a value.
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// fn component(cx: Scope) -> Element {
|
||||
/// let (value, set_value) = use_state(&cx, || 0);
|
||||
///
|
||||
/// rsx!{
|
||||
/// Component {
|
||||
/// handler: set_val.setter()
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn setter(&self) -> Rc<dyn Fn(T)> {
|
||||
self.setter.clone()
|
||||
}
|
||||
|
||||
/// Set the state to a new value, using the current state value as a reference.
|
||||
///
|
||||
/// This is similar to passing a closure to React's `set_value` function.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
/// ```rust
|
||||
/// # use dioxus_core::prelude::*;
|
||||
/// # use dioxus_hooks::*;
|
||||
/// fn component(cx: Scope) -> Element {
|
||||
/// let (value, set_value) = use_state(&cx, || 0);
|
||||
///
|
||||
/// // to increment the value
|
||||
/// set_value.modify(|v| v + 1);
|
||||
///
|
||||
/// // usage in async
|
||||
/// cx.spawn({
|
||||
/// let set_value = set_value.to_owned();
|
||||
/// async move {
|
||||
/// set_value.modify(|v| v + 1);
|
||||
/// }
|
||||
/// });
|
||||
///
|
||||
/// # todo!()
|
||||
/// }
|
||||
/// ```
|
||||
pub fn modify(&self, f: impl FnOnce(&T) -> T) {
|
||||
let new_val = {
|
||||
let current = self.slot.borrow();
|
||||
f(current.as_ref())
|
||||
};
|
||||
(self.setter)(new_val);
|
||||
}
|
||||
|
||||
/// Get the value of the state when this handle was created.
|
||||
///
|
||||
/// This method is useful when you want an `Rc` around the data to cheaply
|
||||
/// pass it around your app.
|
||||
///
|
||||
/// ## Warning
|
||||
///
|
||||
/// This will return a stale value if used within async contexts.
|
||||
///
|
||||
/// Try `current` to get the real current value of the state.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// # use dioxus_core::prelude::*;
|
||||
/// # use dioxus_hooks::*;
|
||||
/// fn component(cx: Scope) -> Element {
|
||||
/// let (value, set_value) = use_state(&cx, || 0);
|
||||
///
|
||||
/// let as_rc = set_value.get();
|
||||
/// assert_eq!(as_rc.as_ref(), &0);
|
||||
///
|
||||
/// # todo!()
|
||||
/// }
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn get(&self) -> &Rc<T> {
|
||||
&self.current_val
|
||||
}
|
||||
|
||||
/// Mark the component that create this [`UseState`] as dirty, forcing it to re-render.
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// fn component(cx: Scope) -> Element {
|
||||
/// let (count, set_count) = use_state(&cx, || 0);
|
||||
/// cx.spawn({
|
||||
/// let set_count = set_count.to_owned();
|
||||
/// async move {
|
||||
/// // for the component to re-render
|
||||
/// set_count.needs_update();
|
||||
/// }
|
||||
/// })
|
||||
/// }
|
||||
/// ```
|
||||
pub fn needs_update(&self) {
|
||||
(self.update_callback)();
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> UseState<T> {
|
||||
/// Get a mutable handle to the value by calling `ToOwned::to_owned` on the
|
||||
/// current value.
|
||||
///
|
||||
/// This is essentially cloning the underlying value and then setting it,
|
||||
/// giving you a mutable handle in the process. This method is intended for
|
||||
/// types that are cheaply cloneable.
|
||||
///
|
||||
/// If you are comfortable dealing with `RefMut`, then you can use `make_mut` to get
|
||||
/// the underlying slot. However, be careful with `RefMut` since you might panic
|
||||
/// if the `RefCell` is left open.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// let (val, set_val) = use_state(&cx, || 0);
|
||||
///
|
||||
/// set_val.with_mut(|v| *v = 1);
|
||||
/// ```
|
||||
pub fn with_mut(&self, apply: impl FnOnce(&mut T)) {
|
||||
let mut slot = self.slot.borrow_mut();
|
||||
let mut inner = slot.as_ref().to_owned();
|
||||
|
||||
apply(&mut inner);
|
||||
|
||||
if let Some(new) = Rc::get_mut(&mut slot) {
|
||||
*new = inner;
|
||||
} else {
|
||||
*slot = Rc::new(inner);
|
||||
}
|
||||
|
||||
self.needs_update();
|
||||
}
|
||||
|
||||
/// Get a mutable handle to the value by calling `ToOwned::to_owned` on the
|
||||
/// current value.
|
||||
///
|
||||
/// This is essentially cloning the underlying value and then setting it,
|
||||
/// giving you a mutable handle in the process. This method is intended for
|
||||
/// types that are cheaply cloneable.
|
||||
///
|
||||
/// # Warning
|
||||
/// Be careful with `RefMut` since you might panic if the `RefCell` is left open!
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// let (val, set_val) = use_state(&cx, || 0);
|
||||
///
|
||||
/// set_val.with_mut(|v| *v = 1);
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn make_mut(&self) -> RefMut<T> {
|
||||
let mut slot = self.slot.borrow_mut();
|
||||
|
||||
self.needs_update();
|
||||
|
||||
if Rc::strong_count(&*slot) > 0 {
|
||||
*slot = Rc::new(slot.as_ref().to_owned());
|
||||
}
|
||||
|
||||
RefMut::map(slot, |rc| Rc::get_mut(rc).expect("the hard count to be 0"))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> Clone for UseState<T> {
|
||||
fn clone(&self) -> Self {
|
||||
UseState {
|
||||
current_val: self.current_val.clone(),
|
||||
update_callback: self.update_callback.clone(),
|
||||
setter: self.setter.clone(),
|
||||
slot: self.slot.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: 'static + Display> std::fmt::Display for UseState<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.current_val)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PartialEq<UseState<T>> for UseState<T> {
|
||||
fn eq(&self, other: &UseState<T>) -> bool {
|
||||
// some level of memoization for UseState
|
||||
Rc::ptr_eq(&self.slot, &other.slot)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Debug> Debug for UseState<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:?}", self.current_val)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> std::ops::Deref for UseState<T> {
|
||||
type Target = Rc<dyn Fn(T)>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.setter
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_makes_sense() {
|
||||
#[allow(unused)]
|
||||
fn app(cx: Scope) -> Element {
|
||||
let (val, set_val) = use_state(&cx, || 0);
|
||||
|
||||
set_val(0);
|
||||
set_val.modify(|v| v + 1);
|
||||
let real_current = set_val.current();
|
||||
|
||||
match val {
|
||||
10 => {
|
||||
set_val(20);
|
||||
set_val.modify(|v| v + 1);
|
||||
}
|
||||
20 => {}
|
||||
_ => {
|
||||
println!("{real_current}");
|
||||
}
|
||||
}
|
||||
|
||||
cx.spawn({
|
||||
crate::to_owned![set_val];
|
||||
async move {
|
||||
set_val.modify(|f| f + 1);
|
||||
}
|
||||
});
|
||||
|
||||
cx.render(LazyNodes::new(|f| f.static_text("asd")))
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
use super::owned::UseStateOwned;
|
||||
use std::{
|
||||
cell::{Ref, RefMut},
|
||||
fmt::{Debug, Display},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
pub struct UseState<'a, T: 'static>(pub(crate) &'a UseStateOwned<T>);
|
||||
|
||||
impl<T> Copy for UseState<'_, T> {}
|
||||
|
||||
impl<'a, T: 'static> Clone for UseState<'a, T> {
|
||||
fn clone(&self) -> Self {
|
||||
UseState(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Debug> Debug for UseState<'_, T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:?}", self.0.current_val)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: 'static> UseState<'a, T> {
|
||||
/// Tell the Dioxus Scheduler that we need to be processed
|
||||
pub fn needs_update(&self) {
|
||||
if !self.0.update_scheuled.get() {
|
||||
self.0.update_scheuled.set(true);
|
||||
(self.0.update_callback)();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set(&self, new_val: T) {
|
||||
*self.0.wip.borrow_mut() = Some(new_val);
|
||||
self.needs_update();
|
||||
}
|
||||
|
||||
pub fn get(&self) -> &'a T {
|
||||
&self.0.current_val
|
||||
}
|
||||
|
||||
pub fn get_rc(&self) -> &'a Rc<T> {
|
||||
&self.0.current_val
|
||||
}
|
||||
|
||||
/// Get the current status of the work-in-progress data
|
||||
pub fn get_wip(&self) -> Ref<Option<T>> {
|
||||
self.0.wip.borrow()
|
||||
}
|
||||
|
||||
/// Get the current status of the work-in-progress data
|
||||
pub fn get_wip_mut(&self) -> RefMut<Option<T>> {
|
||||
self.0.wip.borrow_mut()
|
||||
}
|
||||
|
||||
pub fn classic(self) -> (&'a T, Rc<dyn Fn(T)>) {
|
||||
(&self.0.current_val, self.setter())
|
||||
}
|
||||
|
||||
pub fn setter(&self) -> Rc<dyn Fn(T)> {
|
||||
let slot = self.0.wip.clone();
|
||||
let callback = self.0.update_callback.clone();
|
||||
Rc::new(move |new| {
|
||||
callback();
|
||||
*slot.borrow_mut() = Some(new)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn with(&self, f: impl FnOnce(&mut T)) {
|
||||
let mut val = self.0.wip.borrow_mut();
|
||||
|
||||
if let Some(inner) = val.as_mut() {
|
||||
f(inner);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_async(&self) -> UseStateOwned<T> {
|
||||
let UseStateOwned {
|
||||
current_val,
|
||||
wip,
|
||||
update_callback,
|
||||
update_scheuled,
|
||||
} = self.0;
|
||||
|
||||
UseStateOwned {
|
||||
current_val: current_val.clone(),
|
||||
wip: wip.clone(),
|
||||
update_callback: update_callback.clone(),
|
||||
update_scheuled: update_scheuled.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: 'static + ToOwned<Owned = T>> UseState<'a, T> {
|
||||
/// Gain mutable access to the new value via [`RefMut`].
|
||||
///
|
||||
/// If `modify` is called, then the component will re-render.
|
||||
///
|
||||
/// This method is only available when the value is a `ToOwned` type.
|
||||
///
|
||||
/// Mutable access is derived by calling "ToOwned" (IE cloning) on the current value.
|
||||
///
|
||||
/// To get a reference to the current value, use `.get()`
|
||||
pub fn modify(self) -> RefMut<'a, T> {
|
||||
// make sure we get processed
|
||||
self.needs_update();
|
||||
|
||||
// Bring out the new value, cloning if it we need to
|
||||
// "get_mut" is locked behind "ToOwned" to make it explicit that cloning occurs to use this
|
||||
RefMut::map(self.0.wip.borrow_mut(), |slot| {
|
||||
if slot.is_none() {
|
||||
*slot = Some(self.0.current_val.as_ref().to_owned());
|
||||
}
|
||||
slot.as_mut().unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn inner(self) -> T {
|
||||
self.0.current_val.as_ref().to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> std::ops::Deref for UseState<'a, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.get()
|
||||
}
|
||||
}
|
||||
|
||||
// enable displaty for the handle
|
||||
impl<'a, T: 'static + Display> std::fmt::Display for UseState<'a, T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0.current_val)
|
||||
}
|
||||
}
|
||||
impl<'a, V, T: PartialEq<V>> PartialEq<V> for UseState<'a, T> {
|
||||
fn eq(&self, other: &V) -> bool {
|
||||
self.get() == other
|
||||
}
|
||||
}
|
||||
impl<'a, O, T: std::ops::Not<Output = O> + Copy> std::ops::Not for UseState<'a, T> {
|
||||
type Output = O;
|
||||
|
||||
fn not(self) -> Self::Output {
|
||||
!*self.get()
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
Convenience methods for UseState.
|
||||
|
||||
Note!
|
||||
|
||||
This is not comprehensive.
|
||||
This is *just* meant to make common operations easier.
|
||||
*/
|
||||
|
||||
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
|
||||
|
||||
impl<'a, T: Copy + Add<T, Output = T>> Add<T> for UseState<'a, T> {
|
||||
type Output = T;
|
||||
|
||||
fn add(self, rhs: T) -> Self::Output {
|
||||
self.0.current_val.add(rhs)
|
||||
}
|
||||
}
|
||||
impl<'a, T: Copy + Add<T, Output = T>> AddAssign<T> for UseState<'a, T> {
|
||||
fn add_assign(&mut self, rhs: T) {
|
||||
self.set(self.0.current_val.add(rhs));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sub
|
||||
impl<'a, T: Copy + Sub<T, Output = T>> Sub<T> for UseState<'a, T> {
|
||||
type Output = T;
|
||||
|
||||
fn sub(self, rhs: T) -> Self::Output {
|
||||
self.0.current_val.sub(rhs)
|
||||
}
|
||||
}
|
||||
impl<'a, T: Copy + Sub<T, Output = T>> SubAssign<T> for UseState<'a, T> {
|
||||
fn sub_assign(&mut self, rhs: T) {
|
||||
self.set(self.0.current_val.sub(rhs));
|
||||
}
|
||||
}
|
||||
|
||||
/// MUL
|
||||
impl<'a, T: Copy + Mul<T, Output = T>> Mul<T> for UseState<'a, T> {
|
||||
type Output = T;
|
||||
|
||||
fn mul(self, rhs: T) -> Self::Output {
|
||||
self.0.current_val.mul(rhs)
|
||||
}
|
||||
}
|
||||
impl<'a, T: Copy + Mul<T, Output = T>> MulAssign<T> for UseState<'a, T> {
|
||||
fn mul_assign(&mut self, rhs: T) {
|
||||
self.set(self.0.current_val.mul(rhs));
|
||||
}
|
||||
}
|
||||
|
||||
/// DIV
|
||||
impl<'a, T: Copy + Div<T, Output = T>> Div<T> for UseState<'a, T> {
|
||||
type Output = T;
|
||||
|
||||
fn div(self, rhs: T) -> Self::Output {
|
||||
self.0.current_val.div(rhs)
|
||||
}
|
||||
}
|
||||
impl<'a, T: Copy + Div<T, Output = T>> DivAssign<T> for UseState<'a, T> {
|
||||
fn div_assign(&mut self, rhs: T) {
|
||||
self.set(self.0.current_val.div(rhs));
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
mod handle;
|
||||
mod owned;
|
||||
pub use handle::*;
|
||||
pub use owned::*;
|
||||
|
||||
use dioxus_core::prelude::*;
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
/// Store state between component renders!
|
||||
///
|
||||
/// ## Dioxus equivalent of useState, designed for Rust
|
||||
///
|
||||
/// The Dioxus version of `useState` for state management inside components. It allows you to ergonomically store and
|
||||
/// modify state between component renders. When the state is updated, the component will re-render.
|
||||
///
|
||||
/// Dioxus' use_state basically wraps a RefCell with helper methods and integrates it with the VirtualDOM update system.
|
||||
///
|
||||
/// [`use_state`] exposes a few helper methods to modify the underlying state:
|
||||
/// - `.set(new)` allows you to override the "work in progress" value with a new value
|
||||
/// - `.get_mut()` allows you to modify the WIP value
|
||||
/// - `.get_wip()` allows you to access the WIP value
|
||||
/// - `.deref()` provides the previous value (often done implicitly, though a manual dereference with `*` might be required)
|
||||
///
|
||||
/// Additionally, a ton of std::ops traits are implemented for the `UseState` wrapper, meaning any mutative type operations
|
||||
/// will automatically be called on the WIP value.
|
||||
///
|
||||
/// ## Combinators
|
||||
///
|
||||
/// On top of the methods to set/get state, `use_state` also supports fancy combinators to extend its functionality:
|
||||
/// - `.classic()` and `.split()` convert the hook into the classic React-style hook
|
||||
/// ```rust
|
||||
/// let (state, set_state) = use_state(&cx, || 10).split()
|
||||
/// ```
|
||||
///
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```ignore
|
||||
/// const Example: Component = |cx| {
|
||||
/// let counter = use_state(&cx, || 0);
|
||||
///
|
||||
/// cx.render(rsx! {
|
||||
/// div {
|
||||
/// h1 { "Counter: {counter}" }
|
||||
/// button { onclick: move |_| counter += 1, "Increment" }
|
||||
/// button { onclick: move |_| counter -= 1, "Decrement" }
|
||||
/// }
|
||||
/// ))
|
||||
/// }
|
||||
/// ```
|
||||
pub fn use_state<'a, T: 'static>(
|
||||
cx: &'a ScopeState,
|
||||
initial_state_fn: impl FnOnce() -> T,
|
||||
) -> UseState<'a, T> {
|
||||
let hook = cx.use_hook(move |_| UseStateOwned {
|
||||
current_val: Rc::new(initial_state_fn()),
|
||||
update_callback: cx.schedule_update(),
|
||||
wip: Rc::new(RefCell::new(None)),
|
||||
update_scheuled: Cell::new(false),
|
||||
});
|
||||
|
||||
hook.update_scheuled.set(false);
|
||||
let mut new_val = hook.wip.borrow_mut();
|
||||
|
||||
if new_val.is_some() {
|
||||
// if there's only one reference (weak or otherwise), we can just swap the values
|
||||
if let Some(val) = Rc::get_mut(&mut hook.current_val) {
|
||||
*val = new_val.take().unwrap();
|
||||
} else {
|
||||
hook.current_val = Rc::new(new_val.take().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
UseState(hook)
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
use std::{
|
||||
cell::{Cell, Ref, RefCell, RefMut},
|
||||
fmt::{Debug, Display},
|
||||
rc::Rc,
|
||||
};
|
||||
pub struct UseStateOwned<T: 'static> {
|
||||
// this will always be outdated
|
||||
pub(crate) current_val: Rc<T>,
|
||||
pub(crate) wip: Rc<RefCell<Option<T>>>,
|
||||
pub(crate) update_callback: Rc<dyn Fn()>,
|
||||
pub(crate) update_scheuled: Cell<bool>,
|
||||
}
|
||||
|
||||
impl<T> UseStateOwned<T> {
|
||||
pub fn get(&self) -> Ref<Option<T>> {
|
||||
self.wip.borrow()
|
||||
}
|
||||
|
||||
pub fn set(&self, new_val: T) {
|
||||
*self.wip.borrow_mut() = Some(new_val);
|
||||
(self.update_callback)();
|
||||
}
|
||||
|
||||
pub fn modify(&self) -> RefMut<Option<T>> {
|
||||
(self.update_callback)();
|
||||
self.wip.borrow_mut()
|
||||
}
|
||||
}
|
||||
|
||||
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
|
||||
|
||||
impl<T: Debug> Debug for UseStateOwned<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:?}", self.current_val)
|
||||
}
|
||||
}
|
||||
|
||||
// enable displaty for the handle
|
||||
impl<'a, T: 'static + Display> std::fmt::Display for UseStateOwned<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.current_val)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Copy + Add<T, Output = T>> Add<T> for UseStateOwned<T> {
|
||||
type Output = T;
|
||||
|
||||
fn add(self, rhs: T) -> Self::Output {
|
||||
self.current_val.add(rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Copy + Add<T, Output = T>> AddAssign<T> for UseStateOwned<T> {
|
||||
fn add_assign(&mut self, rhs: T) {
|
||||
self.set(self.current_val.add(rhs));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sub
|
||||
impl<'a, T: Copy + Sub<T, Output = T>> Sub<T> for UseStateOwned<T> {
|
||||
type Output = T;
|
||||
|
||||
fn sub(self, rhs: T) -> Self::Output {
|
||||
self.current_val.sub(rhs)
|
||||
}
|
||||
}
|
||||
impl<'a, T: Copy + Sub<T, Output = T>> SubAssign<T> for UseStateOwned<T> {
|
||||
fn sub_assign(&mut self, rhs: T) {
|
||||
self.set(self.current_val.sub(rhs));
|
||||
}
|
||||
}
|
||||
|
||||
/// MUL
|
||||
impl<'a, T: Copy + Mul<T, Output = T>> Mul<T> for UseStateOwned<T> {
|
||||
type Output = T;
|
||||
|
||||
fn mul(self, rhs: T) -> Self::Output {
|
||||
self.current_val.mul(rhs)
|
||||
}
|
||||
}
|
||||
impl<'a, T: Copy + Mul<T, Output = T>> MulAssign<T> for UseStateOwned<T> {
|
||||
fn mul_assign(&mut self, rhs: T) {
|
||||
self.set(self.current_val.mul(rhs));
|
||||
}
|
||||
}
|
||||
|
||||
/// DIV
|
||||
impl<'a, T: Copy + Div<T, Output = T>> Div<T> for UseStateOwned<T> {
|
||||
type Output = T;
|
||||
|
||||
fn div(self, rhs: T) -> Self::Output {
|
||||
self.current_val.div(rhs)
|
||||
}
|
||||
}
|
||||
impl<'a, T: Copy + Div<T, Output = T>> DivAssign<T> for UseStateOwned<T> {
|
||||
fn div_assign(&mut self, rhs: T) {
|
||||
self.set(self.current_val.div(rhs));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user