Bring back mroe hooks, remove old hooks, cleanup a number of examples
This commit is contained in:
33 files changed
+179
-643
No files matched your search
@@ -55,42 +55,26 @@ macro_rules! to_owned {
|
||||
};
|
||||
}
|
||||
|
||||
// pub mod computed;
|
||||
|
||||
mod use_on_destroy;
|
||||
pub use use_on_destroy::*;
|
||||
|
||||
// mod use_const;
|
||||
// pub use use_const::*;
|
||||
|
||||
// mod use_context;
|
||||
// pub use use_context::*;
|
||||
|
||||
// mod use_state;
|
||||
// pub use use_state::{use_state, UseState};
|
||||
mod use_coroutine;
|
||||
pub use use_coroutine::*;
|
||||
|
||||
// mod use_ref;
|
||||
// pub use use_ref::*;
|
||||
|
||||
// mod use_shared_state;
|
||||
// pub use use_shared_state::*;
|
||||
|
||||
// mod use_coroutine;
|
||||
// pub use use_coroutine::*;
|
||||
|
||||
// mod use_future;
|
||||
// pub use use_future::*;
|
||||
mod use_future;
|
||||
pub use use_future::*;
|
||||
|
||||
// mod use_effect;
|
||||
// pub use use_effect::*;
|
||||
|
||||
// mod use_callback;
|
||||
// pub use use_callback::*;
|
||||
|
||||
// mod use_memo;
|
||||
// pub use use_memo::*;
|
||||
|
||||
// mod use_on_create;
|
||||
// pub use use_on_create::*;
|
||||
// mod use_root_context;
|
||||
// pub use use_root_context::*;
|
||||
|
||||
mod use_root_context;
|
||||
pub use use_root_context::*;
|
||||
@@ -1,4 +1,6 @@
|
||||
use dioxus_core::{ScopeState, Task};
|
||||
use dioxus_core::prelude::{consume_context, provide_context, push_future, use_hook};
|
||||
use dioxus_core::Task;
|
||||
use dioxus_signals::{CopyValue, Signal};
|
||||
pub use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
|
||||
use std::future::Future;
|
||||
|
||||
@@ -63,102 +65,76 @@ use std::future::Future;
|
||||
/// }
|
||||
/// })
|
||||
/// ```
|
||||
pub fn use_coroutine<M, G, F>(nit: G) -> &Coroutine<M>
|
||||
pub fn use_coroutine<M, G, F>(init: G) -> Coroutine<M>
|
||||
where
|
||||
M: 'static,
|
||||
G: FnOnce(UnboundedReceiver<M>) -> F,
|
||||
F: Future<Output = ()> + 'static,
|
||||
{
|
||||
cx.use_hook(|| {
|
||||
let coroutine = use_hook(|| {
|
||||
provide_context(Coroutine {
|
||||
needs_regen: Signal::new(true),
|
||||
tx: CopyValue::new(None),
|
||||
task: CopyValue::new(None),
|
||||
})
|
||||
});
|
||||
|
||||
// We do this here so we can capture data with FnOnce
|
||||
// this might not be the best API
|
||||
if *coroutine.needs_regen.read() {
|
||||
let (tx, rx) = futures_channel::mpsc::unbounded();
|
||||
let task = cx.push_future(init(rx));
|
||||
cx.provide_context(Coroutine { tx, task })
|
||||
})
|
||||
let task = push_future(init(rx)).unwrap();
|
||||
coroutine.tx.set(Some(tx));
|
||||
coroutine.task.set(Some(task));
|
||||
coroutine.needs_regen.set_untracked(false);
|
||||
}
|
||||
|
||||
coroutine
|
||||
}
|
||||
|
||||
/// Get a handle to a coroutine higher in the tree
|
||||
///
|
||||
/// See the docs for [`use_coroutine`] for more details.
|
||||
#[must_use]
|
||||
pub fn use_coroutine_handle<M: 'static>() -> Option<&Coroutine<M>> {
|
||||
cx.use_hook(|| cx.consume_context::<Coroutine<M>>())
|
||||
.as_ref()
|
||||
pub fn use_coroutine_handle<M: 'static>() -> Option<Coroutine<M>> {
|
||||
use_hook(|| consume_context::<Coroutine<M>>())
|
||||
}
|
||||
|
||||
pub struct Coroutine<T> {
|
||||
tx: UnboundedSender<T>,
|
||||
task: Task,
|
||||
}
|
||||
|
||||
// for use in futures
|
||||
impl<T> Clone for Coroutine<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
tx: self.tx.clone(),
|
||||
task: self.task,
|
||||
}
|
||||
}
|
||||
#[derive(PartialEq)]
|
||||
pub struct Coroutine<T: 'static> {
|
||||
needs_regen: Signal<bool>,
|
||||
tx: CopyValue<Option<UnboundedSender<T>>>,
|
||||
task: CopyValue<Option<Task>>,
|
||||
}
|
||||
|
||||
impl<T> Coroutine<T> {
|
||||
/// Get the ID of this coroutine
|
||||
#[must_use]
|
||||
pub fn task_id(&self) -> Task {
|
||||
self.task
|
||||
/// Get the underlying task handle
|
||||
pub fn task(&self) -> Task {
|
||||
self.task.read().clone().unwrap()
|
||||
}
|
||||
|
||||
/// Send a message to the coroutine
|
||||
pub fn send(&self, msg: T) {
|
||||
let _ = self.tx.unbounded_send(msg);
|
||||
let _ = self.tx.read().as_ref().unwrap().unbounded_send(msg);
|
||||
}
|
||||
|
||||
/// Restart this coroutine
|
||||
///
|
||||
/// Forces the component to re-render, which will re-invoke the coroutine.
|
||||
pub fn restart(&self) {
|
||||
self.needs_regen.set(true);
|
||||
self.task().stop();
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PartialEq for Coroutine<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.task == other.task
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(unused)]
|
||||
|
||||
use super::*;
|
||||
use dioxus_core::prelude::*;
|
||||
use futures_channel::mpsc::unbounded;
|
||||
use futures_util::StreamExt;
|
||||
|
||||
fn app(name: String) -> Element {
|
||||
let task = use_coroutine(|mut rx: UnboundedReceiver<i32>| async move {
|
||||
while let Some(msg) = rx.next().await {
|
||||
println!("got message: {msg}");
|
||||
}
|
||||
});
|
||||
|
||||
let task2 = use_coroutine(view_task);
|
||||
|
||||
let task3 = use_coroutine(|rx| complex_task(rx, 10));
|
||||
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn view_task(mut rx: UnboundedReceiver<i32>) {
|
||||
while let Some(msg) = rx.next().await {
|
||||
println!("got message: {msg}");
|
||||
}
|
||||
}
|
||||
|
||||
enum Actions {
|
||||
CloseAll,
|
||||
OpenAll,
|
||||
}
|
||||
|
||||
async fn complex_task(mut rx: UnboundedReceiver<Actions>, name: i32) {
|
||||
while let Some(msg) = rx.next().await {
|
||||
match msg {
|
||||
Actions::CloseAll => todo!(),
|
||||
Actions::OpenAll => todo!(),
|
||||
}
|
||||
// manual impl since deriving doesn't work with generics
|
||||
impl<T> Copy for Coroutine<T> {}
|
||||
impl<T> Clone for Coroutine<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
tx: self.tx,
|
||||
task: self.task,
|
||||
needs_regen: self.needs_regen,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
#![allow(missing_docs)]
|
||||
use dioxus_core::{ScopeState, Task};
|
||||
use dioxus_signals::{use_effect, use_signal, Signal};
|
||||
use std::{any::Any, cell::Cell, future::Future, rc::Rc, sync::Arc};
|
||||
|
||||
use crate::{use_state, UseState};
|
||||
|
||||
/// A future that resolves to a value.
|
||||
///
|
||||
/// This runs the future only once - though the future may be regenerated
|
||||
@@ -17,70 +16,29 @@ use crate::{use_state, UseState};
|
||||
/// will be canceled before the new one is started.
|
||||
///
|
||||
/// - dependencies: a tuple of references to values that are PartialEq + Clone
|
||||
pub fn use_future<T, F, D>
|
||||
dependencies: D,
|
||||
future: impl FnOnce(D::Out) -> F,
|
||||
) -> &UseFuture<T>
|
||||
pub fn use_future<T, F>(future: impl FnMut() -> F) -> UseFuture<T>
|
||||
where
|
||||
T: 'static,
|
||||
F: Future<Output = T> + 'static,
|
||||
D: UseFutureDep,
|
||||
{
|
||||
let val = use_signal(|| None);
|
||||
let task = use_signal(|| None);
|
||||
|
||||
let state = cx.use_hook(move || UseFuture {
|
||||
update: cx.schedule_update(),
|
||||
needs_regen: Rc::new(Cell::new(true)),
|
||||
state: val.clone(),
|
||||
task: Default::default(),
|
||||
use_effect(|| {
|
||||
// task.set();
|
||||
});
|
||||
//
|
||||
|
||||
let state_dependencies = cx.use_hook(Vec::new);
|
||||
|
||||
if dependencies.clone().apply(state_dependencies) || state.needs_regen.get() {
|
||||
// kill the old one, if it exists
|
||||
if let Some(task) = state.task.take() {
|
||||
cx.remove_future(task);
|
||||
}
|
||||
|
||||
// Create the new future
|
||||
let fut = future(dependencies.out());
|
||||
let val = val.clone();
|
||||
let task = state.task.clone();
|
||||
|
||||
state.task.set(Some(cx.push_future(async move {
|
||||
val.set(Some(fut.await));
|
||||
task.take();
|
||||
})));
|
||||
|
||||
// Mark that we don't need to regenerate
|
||||
state.needs_regen.set(false);
|
||||
UseFuture {
|
||||
value: todo!(),
|
||||
task,
|
||||
state: todo!(),
|
||||
}
|
||||
|
||||
// update the current value
|
||||
state.state.current_val = val.current_val.clone();
|
||||
|
||||
state
|
||||
}
|
||||
|
||||
pub enum FutureState<'a, T> {
|
||||
Pending,
|
||||
Complete(&'a T),
|
||||
Regenerating(&'a T), // the old value
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct UseFuture<T: 'static> {
|
||||
update: Arc<dyn Fn()>,
|
||||
needs_regen: Rc<Cell<bool>>,
|
||||
task: Rc<Cell<Option<Task>>>,
|
||||
state: UseState<Option<T>>,
|
||||
}
|
||||
|
||||
pub enum UseFutureState<'a, T> {
|
||||
Pending,
|
||||
Complete(&'a T),
|
||||
Reloading(&'a T),
|
||||
value: Signal<T>,
|
||||
task: Signal<Option<Task>>,
|
||||
state: Signal<UseFutureState<T>>,
|
||||
}
|
||||
|
||||
impl<T> UseFuture<T> {
|
||||
@@ -89,198 +47,57 @@ impl<T> UseFuture<T> {
|
||||
/// Will not cancel the previous future, but will ignore any values that it
|
||||
/// generates.
|
||||
pub fn restart(&self) {
|
||||
self.needs_regen.set(true);
|
||||
(self.update)();
|
||||
// self.needs_regen.set(true);
|
||||
// (self.update)();
|
||||
}
|
||||
|
||||
/// Forcefully cancel a future
|
||||
pub fn cancel(&self, ) {
|
||||
if let Some(task) = self.task.take() {
|
||||
cx.remove_future(task);
|
||||
}
|
||||
pub fn cancel(&self) {
|
||||
// if let Some(task) = self.task.take() {
|
||||
// cx.remove_future(task);
|
||||
// }
|
||||
}
|
||||
|
||||
// Manually set the value in the future slot without starting the future over
|
||||
pub fn set(&self, new_value: T) {
|
||||
self.state.set(Some(new_value));
|
||||
// self.state.set(Some(new_value));
|
||||
}
|
||||
|
||||
/// Return any value, even old values if the future has not yet resolved.
|
||||
///
|
||||
/// If the future has never completed, the returned value will be `None`.
|
||||
pub fn value(&self) -> Option<&T> {
|
||||
self.state.current_val.as_ref().as_ref()
|
||||
pub fn value(&self) -> Signal<Option<T>> {
|
||||
todo!()
|
||||
// self.state.current_val.as_ref().as_ref()
|
||||
}
|
||||
|
||||
/// Get the ID of the future in Dioxus' internal scheduler
|
||||
pub fn task(&self) -> Option<Task> {
|
||||
self.task.get()
|
||||
todo!()
|
||||
// self.task.get()
|
||||
}
|
||||
|
||||
/// Get the current state of the future.
|
||||
pub fn state(&self) -> UseFutureState<T> {
|
||||
match (&self.task.get(), &self.value()) {
|
||||
// If we have a task and an existing value, we're reloading
|
||||
(Some(_), Some(val)) => UseFutureState::Reloading(val),
|
||||
todo!()
|
||||
// match (&self.task.get(), &self.value()) {
|
||||
// // If we have a task and an existing value, we're reloading
|
||||
// (Some(_), Some(val)) => UseFutureState::Reloading(val),
|
||||
|
||||
// no task, but value - we're done
|
||||
(None, Some(val)) => UseFutureState::Complete(val),
|
||||
// // no task, but value - we're done
|
||||
// (None, Some(val)) => UseFutureState::Complete(val),
|
||||
|
||||
// no task, no value - something's wrong? return pending
|
||||
(None, None) => UseFutureState::Pending,
|
||||
// // no task, no value - something's wrong? return pending
|
||||
// (None, None) => UseFutureState::Pending,
|
||||
|
||||
// Task, no value - we're still pending
|
||||
(Some(_), None) => UseFutureState::Pending,
|
||||
}
|
||||
// // Task, no value - we're still pending
|
||||
// (Some(_), None) => UseFutureState::Pending,
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
pub trait UseFutureDep: Sized + Clone {
|
||||
type Out;
|
||||
fn out(&self) -> Self::Out;
|
||||
fn apply(self, state: &mut Vec<Box<dyn Any>>) -> bool;
|
||||
}
|
||||
|
||||
impl UseFutureDep for () {
|
||||
type Out = ();
|
||||
fn out(&self) -> Self::Out {}
|
||||
fn apply(self, _state: &mut Vec<Box<dyn Any>>) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Dep: 'static + PartialEq + Clone {}
|
||||
impl<T> Dep for T where T: 'static + PartialEq + Clone {}
|
||||
|
||||
impl<A: Dep> UseFutureDep for &A {
|
||||
type Out = A;
|
||||
fn out(&self) -> Self::Out {
|
||||
(*self).clone()
|
||||
}
|
||||
fn apply(self, state: &mut Vec<Box<dyn Any>>) -> bool {
|
||||
match state.get_mut(0).and_then(|f| f.downcast_mut::<A>()) {
|
||||
Some(val) => {
|
||||
if *val != *self {
|
||||
*val = self.clone();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
state.push(Box::new(self.clone()));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_dep {
|
||||
(
|
||||
$($el:ident=$name:ident,)*
|
||||
) => {
|
||||
impl< $($el),* > UseFutureDep for ($(&$el,)*)
|
||||
where
|
||||
$(
|
||||
$el: Dep
|
||||
),*
|
||||
{
|
||||
type Out = ($($el,)*);
|
||||
|
||||
fn out(&self) -> Self::Out {
|
||||
let ($($name,)*) = self;
|
||||
($((*$name).clone(),)*)
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
fn apply(self, state: &mut Vec<Box<dyn Any>>) -> bool {
|
||||
let ($($name,)*) = self;
|
||||
let mut idx = 0;
|
||||
let mut needs_regen = false;
|
||||
|
||||
$(
|
||||
match state.get_mut(idx).map(|f| f.downcast_mut::<$el>()).flatten() {
|
||||
Some(val) => {
|
||||
if *val != *$name {
|
||||
*val = $name.clone();
|
||||
needs_regen = true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
state.push(Box::new($name.clone()));
|
||||
needs_regen = true;
|
||||
}
|
||||
}
|
||||
idx += 1;
|
||||
)*
|
||||
|
||||
needs_regen
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_dep!(A = a,);
|
||||
impl_dep!(A = a, B = b,);
|
||||
impl_dep!(A = a, B = b, C = c,);
|
||||
impl_dep!(A = a, B = b, C = c, D = d,);
|
||||
impl_dep!(A = a, B = b, C = c, D = d, E = e,);
|
||||
impl_dep!(A = a, B = b, C = c, D = d, E = e, F = f,);
|
||||
impl_dep!(A = a, B = b, C = c, D = d, E = e, F = f, G = g,);
|
||||
impl_dep!(A = a, B = b, C = c, D = d, E = e, F = f, G = g, H = h,);
|
||||
|
||||
/// A helper macro that merges uses the closure syntax to elaborate the dependency array
|
||||
#[macro_export]
|
||||
macro_rules! use_future {
|
||||
($cx:ident, || $($rest:tt)*) => { use_future( $cx, (), |_| $($rest)* ) };
|
||||
($cx:ident, | $($args:tt),* | $($rest:tt)*) => {
|
||||
use_future(
|
||||
$cx,
|
||||
($($args),*),
|
||||
|($($args),*)| $($rest)*
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[allow(unused)]
|
||||
#[test]
|
||||
fn test_use_future() {
|
||||
use dioxus_core::prelude::*;
|
||||
|
||||
struct MyProps {
|
||||
a: String,
|
||||
b: i32,
|
||||
c: i32,
|
||||
d: i32,
|
||||
e: i32,
|
||||
}
|
||||
|
||||
async fn app(cx: Scope<'_, MyProps>) -> Element {
|
||||
// should only ever run once
|
||||
let fut = use_future(|_| async move {});
|
||||
|
||||
// runs when a is changed
|
||||
let fut = use_future((&cx.props.a,), |(a,)| async move {});
|
||||
|
||||
// runs when a or b is changed
|
||||
let fut = use_future((&cx.props.a, &cx.props.b), |(a, b)| async move { 123 });
|
||||
|
||||
let a = use_future(|| async move {
|
||||
// do the thing!
|
||||
});
|
||||
|
||||
let b = &123;
|
||||
let c = &123;
|
||||
|
||||
let a = use_future(|b, c| async move {
|
||||
let a = b + c;
|
||||
let blah = "asd";
|
||||
});
|
||||
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
pub enum UseFutureState<T: 'static> {
|
||||
Pending,
|
||||
Complete(Signal<T>),
|
||||
Regenerating(Signal<T>), // the old value
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
use dioxus_core::ScopeState;
|
||||
use dioxus_core::{prelude::consume_context, prelude::provide_root_context, use_hook};
|
||||
|
||||
///
|
||||
pub fn use_root_context<T: 'static + Clone>(, new: impl FnOnce() -> T) -> &T {
|
||||
cx.use_hook(|| {
|
||||
cx.consume_context::<T>()
|
||||
.unwrap_or_else(|| cx.provide_root_context(new()))
|
||||
pub fn use_root_context<T: 'static + Clone>(new: impl FnOnce() -> T) -> T {
|
||||
use_hook(|| {
|
||||
consume_context::<T>()
|
||||
// If no context is provided, create a new one at the root
|
||||
.unwrap_or_else(|| provide_root_context(new()).expect(" A runtime to exist"))
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user