Make use_callback and Callback bring the runtime with them (#2852)

* Move the runtime along with Callback
This commit is contained in:
Evan Almloff authored and GitHub committed 2024-08-20 14:58:53 -07:00
1 parent 5a7a91323a
commit effc0a3b94
6 files changed
+105 -139

No files matched your search

+15 -98
View File
@@ -1,109 +1,26 @@
use dioxus_core::prelude::{current_scope_id, use_hook, Runtime};
use dioxus_signals::CopyValue;
use dioxus_signals::Writable;
use std::cell::RefCell;
use std::rc::Rc;
/// A callback that's always current
///
/// Whenever this hook is called the inner callback will be replaced with the new callback but the handle will remain.
use dioxus_core::prelude::use_hook;
use dioxus_core::prelude::Callback;
/// Create a callback that's always up to date. Whenever this hook is called the inner callback will be replaced with the new callback but the handle will remain.
///
/// There is *currently* no signal tracking on the Callback so anything reading from it will not be updated.
///
/// This API is in flux and might not remain.
#[doc = include_str!("../docs/rules_of_hooks.md")]
pub fn use_callback<T, O>(f: impl FnMut(T) -> O + 'static) -> UseCallback<T, O> {
pub fn use_callback<T: 'static, O: 'static>(f: impl FnMut(T) -> O + 'static) -> Callback<T, O> {
let mut callback = Some(f);
// Create a copyvalue with no contents
// This copyvalue is generic over F so that it can be sized properly
let mut inner = use_hook(|| CopyValue::new(None));
let mut inner = use_hook(|| Callback::new(callback.take().unwrap()));
// Every time this hook is called replace the inner callback with the new callback
inner.set(Some(f));
// And then wrap that callback in a boxed callback so we're blind to the size of the actual callback
use_hook(|| {
let cur_scope = current_scope_id().unwrap();
let rt = Runtime::current().unwrap();
UseCallback {
inner: CopyValue::new(Box::new(move |value| {
// run this callback in the context of the scope it was created in.
let run_callback =
|| inner.with_mut(|f: &mut Option<_>| f.as_mut().unwrap()(value));
rt.on_scope(cur_scope, run_callback)
})),
}
})
}
/// This callback is not generic over a return type so you can hold a bunch of callbacks at once
///
/// If you need a callback that returns a value, you can simply wrap the closure you pass in that sets a value in its scope
pub struct UseCallback<T: 'static, O: 'static + ?Sized> {
inner: CopyValue<Box<dyn FnMut(T) -> O>>,
}
impl<T: 'static, O: 'static + ?Sized> PartialEq for UseCallback<T, O> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T: 'static, O: 'static + ?Sized> std::fmt::Debug for UseCallback<T, O> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UseCallback")
.field("inner", &self.inner.value())
.finish()
}
}
impl<T: 'static, O: 'static + ?Sized> Clone for UseCallback<T, O> {
fn clone(&self) -> Self {
Self { inner: self.inner }
}
}
impl<T: 'static, O: 'static> Copy for UseCallback<T, O> {}
impl<T, O> UseCallback<T, O> {
/// Call the callback
pub fn call(&self, value: T) -> O {
(self.inner.write_unchecked())(value)
}
}
// This makes UseCallback callable like a normal function
impl<T, O> std::ops::Deref for UseCallback<T, O> {
type Target = dyn Fn(T) -> O;
fn deref(&self) -> &Self::Target {
use std::mem::MaybeUninit;
// 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 |value| Self::call(unsafe { &*uninit_callable.as_ptr() }, value);
// 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
},
#[allow(clippy::missing_transmute_annotations)]
// 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 &_
if let Some(callback) = callback.take() {
// Every time this hook is called replace the inner callback with the new callback
inner.__set(Rc::new(RefCell::new(callback)));
}
inner
}
+2 -2
View File
@@ -1,5 +1,5 @@
#![allow(missing_docs)]
use crate::{use_callback, use_hook_did_run, use_signal, UseCallback};
use crate::{use_callback, use_hook_did_run, use_signal};
use dioxus_core::prelude::*;
use dioxus_signals::*;
use std::future::Future;
@@ -82,7 +82,7 @@ where
pub struct UseFuture {
task: CopyValue<Task>,
state: Signal<UseFutureState>,
callback: UseCallback<(), Task>,
callback: Callback<(), Task>,
}
/// A signal that represents the state of a future
+2 -2
View File
@@ -1,6 +1,6 @@
#![allow(missing_docs)]
use crate::{use_callback, use_signal, UseCallback};
use crate::{use_callback, use_signal};
use dioxus_core::prelude::*;
use dioxus_signals::*;
use futures_util::{future, pin_mut, FutureExt, StreamExt};
@@ -110,7 +110,7 @@ pub struct Resource<T: 'static> {
value: Signal<Option<T>>,
task: Signal<Task>,
state: Signal<UseResourceState>,
callback: UseCallback<(), Task>,
callback: Callback<(), Task>,
}
impl<T> PartialEq for Resource<T> {