use crate::{global_context::current_scope_id, Runtime, ScopeId}; use generational_box::GenerationalBox; use std::{ cell::{Cell, RefCell}, rc::Rc, }; /// A wrapper around some generic data that handles the event's state /// /// /// Prevent this event from continuing to bubble up the tree to parent elements. /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: Event| { /// evt.stop_propagation(); /// } /// } /// }; /// ``` pub struct Event { /// The data associated with this event pub data: Rc, pub(crate) propagates: Rc>, } impl Event { pub(crate) fn new(data: Rc, bubbles: bool) -> Self { Self { data, propagates: Rc::new(Cell::new(bubbles)), } } } impl Event { /// Map the event data to a new type /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: MouseEvent| { /// let data = evt.map(|data| data.client_coordinates()); /// println!("{:?}", data.data()); /// } /// } /// }; /// ``` pub fn map U>(&self, f: F) -> Event { Event { data: Rc::new(f(&self.data)), propagates: self.propagates.clone(), } } /// Prevent this event from continuing to bubble up the tree to parent elements. /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: Event| { /// # #[allow(deprecated)] /// evt.cancel_bubble(); /// } /// } /// }; /// ``` #[deprecated = "use stop_propagation instead"] pub fn cancel_bubble(&self) { self.propagates.set(false); } /// Prevent this event from continuing to bubble up the tree to parent elements. /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: Event| { /// evt.stop_propagation(); /// } /// } /// }; /// ``` pub fn stop_propagation(&self) { self.propagates.set(false); } /// Get a reference to the inner data from this event /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: Event| { /// let data = evt.data(); /// async move { /// println!("{:?}", data); /// } /// } /// } /// }; /// ``` pub fn data(&self) -> Rc { self.data.clone() } } impl Clone for Event { fn clone(&self) -> Self { Self { propagates: self.propagates.clone(), data: self.data.clone(), } } } impl std::ops::Deref for Event { type Target = Rc; fn deref(&self) -> &Self::Target { &self.data } } impl std::fmt::Debug for Event { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("UiEvent") .field("bubble_state", &self.propagates) .field("data", &self.data) .finish() } } /// The callback type generated by the `rsx!` macro when an `on` field is specified for components. /// /// This makes it possible to pass `move |evt| {}` style closures into components as property fields. /// /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx!{ /// MyComponent { onclick: move |evt| tracing::debug!("clicked") } /// }; /// /// #[derive(Props, Clone, PartialEq)] /// struct MyProps { /// onclick: EventHandler, /// } /// /// fn MyComponent(cx: MyProps) -> Element { /// rsx!{ /// button { /// onclick: move |evt| cx.onclick.call(evt), /// } /// } /// } /// ``` pub struct EventHandler { pub(crate) origin: ScopeId, /// During diffing components with EventHandler, we move the EventHandler over in place instead of rerunning the child component. /// /// ```rust /// # use dioxus::prelude::*; /// #[component] /// fn Child(onclick: EventHandler) -> Element { /// rsx!{ /// button { /// // 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 /// onclick: move |evt| onclick(evt), /// } /// } /// } /// ``` /// /// This is both more efficient and allows us to avoid out of date EventHandlers. /// /// We double box here because we want the data to be copy (GenerationalBox) and still update in place (ExternalListenerCallback) /// This isn't an ideal solution for performance, but it is non-breaking and fixes the issues described in pub(super) callback: GenerationalBox>>, } impl std::fmt::Debug for EventHandler { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("EventHandler") .field("origin", &self.origin) .field("callback", &self.callback) .finish() } } impl Default for EventHandler { fn default() -> Self { EventHandler::new(|_| {}) } } impl From for EventHandler { fn from(f: F) -> Self { EventHandler::new(f) } } impl Copy for EventHandler {} impl Clone for EventHandler { fn clone(&self) -> Self { *self } } impl PartialEq for EventHandler { fn eq(&self, _: &Self) -> bool { true } } type ExternalListenerCallback = Rc>; impl EventHandler { /// Create a new [`EventHandler`] from an [`FnMut`]. The callback is owned by the current scope and will be dropped when the scope is dropped. /// This should not be called directly in the body of a component because it will not be dropped until the component is dropped. #[track_caller] pub fn new(mut f: impl FnMut(T) + 'static) -> EventHandler { let owner = crate::innerlude::current_owner::(); let callback = owner.insert(Some(Rc::new(RefCell::new(move |event: T| { f(event); })) as Rc>)); EventHandler { callback, origin: current_scope_id().expect("to be in a dioxus runtime"), } } /// Leak a new [`EventHandler`] that will not be dropped unless it is manually dropped. #[track_caller] pub fn leak(mut f: impl FnMut(T) + 'static) -> EventHandler { let callback = GenerationalBox::leak(Some(Rc::new(RefCell::new(move |event: T| { f(event); })) as Rc>)); EventHandler { callback, origin: current_scope_id().expect("to be in a dioxus runtime"), } } /// Call this event handler with the appropriate event type /// /// This borrows the event using a RefCell. Recursively calling a listener will cause a panic. pub fn call(&self, event: T) { if let Some(callback) = self.callback.read().as_ref() { Runtime::with(|rt| rt.scope_stack.borrow_mut().push(self.origin)); { let mut callback = callback.borrow_mut(); callback(event); } Runtime::with(|rt| rt.scope_stack.borrow_mut().pop()); } } /// Forcibly drop the internal handler callback, releasing memory /// /// This will force any future calls to "call" to not doing anything pub fn release(&self) { self.callback.set(None); } #[doc(hidden)] /// This should only be used by the `rsx!` macro. pub fn __set(&mut self, value: ExternalListenerCallback) { self.callback.set(Some(value)); } #[doc(hidden)] /// This should only be used by the `rsx!` macro. pub fn __take(&self) -> ExternalListenerCallback { self.callback .read() .clone() .expect("EventHandler was manually dropped") } } impl std::ops::Deref for EventHandler { type Target = dyn Fn(T) + 'static; fn deref(&self) -> &Self::Target { // 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). let uninit_callable = std::mem::MaybeUninit::::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 |t| Self::call(unsafe { &*uninit_callable.as_ptr() }, t); // 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::()); // 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 }, // 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 &_ } }