use_callback.rs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. use dioxus_core::prelude::{current_scope_id, use_hook, Runtime};
  2. use dioxus_signals::CopyValue;
  3. use dioxus_signals::Writable;
  4. /// A callback that's always current
  5. ///
  6. /// Whenever this hook is called the inner callback will be replaced with the new callback but the handle will remain.
  7. ///
  8. /// There is *currently* no signal tracking on the Callback so anything reading from it will not be updated.
  9. ///
  10. /// This API is in flux and might not remain.
  11. #[doc = include_str!("../docs/rules_of_hooks.md")]
  12. pub fn use_callback<O>(f: impl FnMut() -> O + 'static) -> UseCallback<O> {
  13. // Create a copyvalue with no contents
  14. // This copyvalue is generic over F so that it can be sized properly
  15. let mut inner = use_hook(|| CopyValue::new(None));
  16. // Every time this hook is called replace the inner callback with the new callback
  17. inner.set(Some(f));
  18. // And then wrap that callback in a boxed callback so we're blind to the size of the actual callback
  19. use_hook(|| {
  20. let cur_scope = current_scope_id().unwrap();
  21. let rt = Runtime::current().unwrap();
  22. UseCallback {
  23. inner: CopyValue::new(Box::new(move || {
  24. // run this callback in the context of the scope it was created in.
  25. let run_callback = || inner.with_mut(|f: &mut Option<_>| f.as_mut().unwrap()());
  26. rt.on_scope(cur_scope, run_callback)
  27. })),
  28. }
  29. })
  30. }
  31. /// This callback is not generic over a return type so you can hold a bunch of callbacks at once
  32. ///
  33. /// 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
  34. pub struct UseCallback<O: 'static + ?Sized> {
  35. inner: CopyValue<Box<dyn FnMut() -> O>>,
  36. }
  37. impl<O: 'static + ?Sized> PartialEq for UseCallback<O> {
  38. fn eq(&self, other: &Self) -> bool {
  39. self.inner == other.inner
  40. }
  41. }
  42. impl<O: 'static + ?Sized> std::fmt::Debug for UseCallback<O> {
  43. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  44. f.debug_struct("UseCallback")
  45. .field("inner", &self.inner.value())
  46. .finish()
  47. }
  48. }
  49. impl<O: 'static + ?Sized> Clone for UseCallback<O> {
  50. fn clone(&self) -> Self {
  51. Self { inner: self.inner }
  52. }
  53. }
  54. impl<O: 'static> Copy for UseCallback<O> {}
  55. impl<O> UseCallback<O> {
  56. /// Call the callback
  57. pub fn call(&self) -> O {
  58. (self.inner.write_unchecked())()
  59. }
  60. }
  61. // This makes UseCallback callable like a normal function
  62. impl<O> std::ops::Deref for UseCallback<O> {
  63. type Target = dyn Fn() -> O;
  64. fn deref(&self) -> &Self::Target {
  65. use std::mem::MaybeUninit;
  66. // https://github.com/dtolnay/case-studies/tree/master/callable-types
  67. // First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
  68. let uninit_callable = MaybeUninit::<Self>::uninit();
  69. // Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
  70. let uninit_closure = move || Self::call(unsafe { &*uninit_callable.as_ptr() });
  71. // 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.
  72. let size_of_closure = std::mem::size_of_val(&uninit_closure);
  73. assert_eq!(size_of_closure, std::mem::size_of::<Self>());
  74. // Then cast the lifetime of the closure to the lifetime of &self.
  75. fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
  76. b
  77. }
  78. let reference_to_closure = cast_lifetime(
  79. {
  80. // The real closure that we will never use.
  81. &uninit_closure
  82. },
  83. #[allow(clippy::missing_transmute_annotations)]
  84. // 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.
  85. unsafe {
  86. std::mem::transmute(self)
  87. },
  88. );
  89. // Cast the closure to a trait object.
  90. reference_to_closure as &_
  91. }
  92. }