events.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. use crate::{global_context::current_scope_id, Runtime, ScopeId};
  2. use generational_box::GenerationalBox;
  3. use std::{
  4. cell::{Cell, RefCell},
  5. rc::Rc,
  6. };
  7. /// A wrapper around some generic data that handles the event's state
  8. ///
  9. ///
  10. /// Prevent this event from continuing to bubble up the tree to parent elements.
  11. ///
  12. /// # Example
  13. ///
  14. /// ```rust, no_run
  15. /// # use dioxus::prelude::*;
  16. /// rsx! {
  17. /// button {
  18. /// onclick: move |evt: Event<MouseData>| {
  19. /// evt.stop_propagation();
  20. /// }
  21. /// }
  22. /// };
  23. /// ```
  24. pub struct Event<T: 'static + ?Sized> {
  25. /// The data associated with this event
  26. pub data: Rc<T>,
  27. pub(crate) propagates: Rc<Cell<bool>>,
  28. }
  29. impl<T: ?Sized + 'static> Event<T> {
  30. pub(crate) fn new(data: Rc<T>, bubbles: bool) -> Self {
  31. Self {
  32. data,
  33. propagates: Rc::new(Cell::new(bubbles)),
  34. }
  35. }
  36. }
  37. impl<T> Event<T> {
  38. /// Map the event data to a new type
  39. ///
  40. /// # Example
  41. ///
  42. /// ```rust, no_run
  43. /// # use dioxus::prelude::*;
  44. /// rsx! {
  45. /// button {
  46. /// onclick: move |evt: MouseEvent| {
  47. /// let data = evt.map(|data| data.client_coordinates());
  48. /// println!("{:?}", data.data());
  49. /// }
  50. /// }
  51. /// };
  52. /// ```
  53. pub fn map<U: 'static, F: FnOnce(&T) -> U>(&self, f: F) -> Event<U> {
  54. Event {
  55. data: Rc::new(f(&self.data)),
  56. propagates: self.propagates.clone(),
  57. }
  58. }
  59. /// Prevent this event from continuing to bubble up the tree to parent elements.
  60. ///
  61. /// # Example
  62. ///
  63. /// ```rust, no_run
  64. /// # use dioxus::prelude::*;
  65. /// rsx! {
  66. /// button {
  67. /// onclick: move |evt: Event<MouseData>| {
  68. /// # #[allow(deprecated)]
  69. /// evt.cancel_bubble();
  70. /// }
  71. /// }
  72. /// };
  73. /// ```
  74. #[deprecated = "use stop_propagation instead"]
  75. pub fn cancel_bubble(&self) {
  76. self.propagates.set(false);
  77. }
  78. /// Prevent this event from continuing to bubble up the tree to parent elements.
  79. ///
  80. /// # Example
  81. ///
  82. /// ```rust, no_run
  83. /// # use dioxus::prelude::*;
  84. /// rsx! {
  85. /// button {
  86. /// onclick: move |evt: Event<MouseData>| {
  87. /// evt.stop_propagation();
  88. /// }
  89. /// }
  90. /// };
  91. /// ```
  92. pub fn stop_propagation(&self) {
  93. self.propagates.set(false);
  94. }
  95. /// Get a reference to the inner data from this event
  96. ///
  97. /// ```rust, no_run
  98. /// # use dioxus::prelude::*;
  99. /// rsx! {
  100. /// button {
  101. /// onclick: move |evt: Event<MouseData>| {
  102. /// let data = evt.data();
  103. /// async move {
  104. /// println!("{:?}", data);
  105. /// }
  106. /// }
  107. /// }
  108. /// };
  109. /// ```
  110. pub fn data(&self) -> Rc<T> {
  111. self.data.clone()
  112. }
  113. }
  114. impl<T: ?Sized> Clone for Event<T> {
  115. fn clone(&self) -> Self {
  116. Self {
  117. propagates: self.propagates.clone(),
  118. data: self.data.clone(),
  119. }
  120. }
  121. }
  122. impl<T> std::ops::Deref for Event<T> {
  123. type Target = Rc<T>;
  124. fn deref(&self) -> &Self::Target {
  125. &self.data
  126. }
  127. }
  128. impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> {
  129. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  130. f.debug_struct("UiEvent")
  131. .field("bubble_state", &self.propagates)
  132. .field("data", &self.data)
  133. .finish()
  134. }
  135. }
  136. /// The callback type generated by the `rsx!` macro when an `on` field is specified for components.
  137. ///
  138. /// This makes it possible to pass `move |evt| {}` style closures into components as property fields.
  139. ///
  140. ///
  141. /// # Example
  142. ///
  143. /// ```rust, no_run
  144. /// # use dioxus::prelude::*;
  145. /// rsx!{
  146. /// MyComponent { onclick: move |evt| tracing::debug!("clicked") }
  147. /// };
  148. ///
  149. /// #[derive(Props, Clone, PartialEq)]
  150. /// struct MyProps {
  151. /// onclick: EventHandler<MouseEvent>,
  152. /// }
  153. ///
  154. /// fn MyComponent(cx: MyProps) -> Element {
  155. /// rsx!{
  156. /// button {
  157. /// onclick: move |evt| cx.onclick.call(evt),
  158. /// }
  159. /// }
  160. /// }
  161. /// ```
  162. pub struct EventHandler<T = ()> {
  163. pub(crate) origin: ScopeId,
  164. /// During diffing components with EventHandler, we move the EventHandler over in place instead of rerunning the child component.
  165. ///
  166. /// ```rust
  167. /// # use dioxus::prelude::*;
  168. /// #[component]
  169. /// fn Child(onclick: EventHandler<MouseEvent>) -> Element {
  170. /// rsx!{
  171. /// button {
  172. /// // Diffing Child will not rerun this component, it will just update the EventHandler in place so that if this callback is called, it will run the latest version of the callback
  173. /// onclick: move |evt| onclick(evt),
  174. /// }
  175. /// }
  176. /// }
  177. /// ```
  178. ///
  179. /// This is both more efficient and allows us to avoid out of date EventHandlers.
  180. ///
  181. /// We double box here because we want the data to be copy (GenerationalBox) and still update in place (ExternalListenerCallback)
  182. /// This isn't an ideal solution for performance, but it is non-breaking and fixes the issues described in <https://github.com/DioxusLabs/dioxus/pull/2298>
  183. pub(super) callback: GenerationalBox<Option<ExternalListenerCallback<T>>>,
  184. }
  185. impl<T> std::fmt::Debug for EventHandler<T> {
  186. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  187. f.debug_struct("EventHandler")
  188. .field("origin", &self.origin)
  189. .field("callback", &self.callback)
  190. .finish()
  191. }
  192. }
  193. impl<T: 'static> Default for EventHandler<T> {
  194. fn default() -> Self {
  195. EventHandler::new(|_| {})
  196. }
  197. }
  198. impl<F: FnMut(T) + 'static, T: 'static> From<F> for EventHandler<T> {
  199. fn from(f: F) -> Self {
  200. EventHandler::new(f)
  201. }
  202. }
  203. impl<T> Copy for EventHandler<T> {}
  204. impl<T> Clone for EventHandler<T> {
  205. fn clone(&self) -> Self {
  206. *self
  207. }
  208. }
  209. impl<T: 'static> PartialEq for EventHandler<T> {
  210. fn eq(&self, _: &Self) -> bool {
  211. true
  212. }
  213. }
  214. type ExternalListenerCallback<T> = Rc<RefCell<dyn FnMut(T)>>;
  215. impl<T: 'static> EventHandler<T> {
  216. /// Create a new [`EventHandler`] from an [`FnMut`]. The callback is owned by the current scope and will be dropped when the scope is dropped.
  217. /// This should not be called directly in the body of a component because it will not be dropped until the component is dropped.
  218. #[track_caller]
  219. pub fn new(mut f: impl FnMut(T) + 'static) -> EventHandler<T> {
  220. let owner = crate::innerlude::current_owner::<generational_box::UnsyncStorage>();
  221. let callback = owner.insert(Some(Rc::new(RefCell::new(move |event: T| {
  222. f(event);
  223. })) as Rc<RefCell<dyn FnMut(T)>>));
  224. EventHandler {
  225. callback,
  226. origin: current_scope_id().expect("to be in a dioxus runtime"),
  227. }
  228. }
  229. /// Leak a new [`EventHandler`] that will not be dropped unless it is manually dropped.
  230. #[track_caller]
  231. pub fn leak(mut f: impl FnMut(T) + 'static) -> EventHandler<T> {
  232. let callback = GenerationalBox::leak(Some(Rc::new(RefCell::new(move |event: T| {
  233. f(event);
  234. })) as Rc<RefCell<dyn FnMut(T)>>));
  235. EventHandler {
  236. callback,
  237. origin: current_scope_id().expect("to be in a dioxus runtime"),
  238. }
  239. }
  240. /// Call this event handler with the appropriate event type
  241. ///
  242. /// This borrows the event using a RefCell. Recursively calling a listener will cause a panic.
  243. pub fn call(&self, event: T) {
  244. if let Some(callback) = self.callback.read().as_ref() {
  245. Runtime::with(|rt| rt.scope_stack.borrow_mut().push(self.origin));
  246. {
  247. let mut callback = callback.borrow_mut();
  248. callback(event);
  249. }
  250. Runtime::with(|rt| rt.scope_stack.borrow_mut().pop());
  251. }
  252. }
  253. /// Forcibly drop the internal handler callback, releasing memory
  254. ///
  255. /// This will force any future calls to "call" to not doing anything
  256. pub fn release(&self) {
  257. self.callback.set(None);
  258. }
  259. #[doc(hidden)]
  260. /// This should only be used by the `rsx!` macro.
  261. pub fn __set(&mut self, value: ExternalListenerCallback<T>) {
  262. self.callback.set(Some(value));
  263. }
  264. #[doc(hidden)]
  265. /// This should only be used by the `rsx!` macro.
  266. pub fn __take(&self) -> ExternalListenerCallback<T> {
  267. self.callback
  268. .read()
  269. .clone()
  270. .expect("EventHandler was manually dropped")
  271. }
  272. }
  273. impl<T: 'static> std::ops::Deref for EventHandler<T> {
  274. type Target = dyn Fn(T) + 'static;
  275. fn deref(&self) -> &Self::Target {
  276. // https://github.com/dtolnay/case-studies/tree/master/callable-types
  277. // First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
  278. let uninit_callable = std::mem::MaybeUninit::<Self>::uninit();
  279. // Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
  280. let uninit_closure = move |t| Self::call(unsafe { &*uninit_callable.as_ptr() }, t);
  281. // 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.
  282. let size_of_closure = std::mem::size_of_val(&uninit_closure);
  283. assert_eq!(size_of_closure, std::mem::size_of::<Self>());
  284. // Then cast the lifetime of the closure to the lifetime of &self.
  285. fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
  286. b
  287. }
  288. let reference_to_closure = cast_lifetime(
  289. {
  290. // The real closure that we will never use.
  291. &uninit_closure
  292. },
  293. // 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.
  294. unsafe { std::mem::transmute(self) },
  295. );
  296. // Cast the closure to a trait object.
  297. reference_to_closure as &_
  298. }
  299. }