1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
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, ignore
/// rsx! {
/// button {
/// onclick: move |evt: Event<MouseData>| {
/// evt.cancel_bubble();
///
/// }
/// }
/// }
/// ```
pub struct Event<T: 'static + ?Sized> {
/// The data associated with this event
pub data: Rc<T>,
pub(crate) propagates: Rc<Cell<bool>>,
}
impl<T: ?Sized + 'static> Event<T> {
pub(crate) fn new(data: Rc<T>, bubbles: bool) -> Self {
Self {
data,
propagates: Rc::new(Cell::new(bubbles)),
}
}
}
impl<T> Event<T> {
/// Map the event data to a new type
///
/// # Example
///
/// ```rust, ignore
/// rsx! {
/// button {
/// onclick: move |evt: Event<FormData>| {
/// let data = evt.map(|data| data.value());
/// assert_eq!(data.inner(), "hello world");
/// }
/// }
/// }
/// ```
pub fn map<U: 'static, F: FnOnce(&T) -> U>(&self, f: F) -> Event<U> {
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, ignore
/// rsx! {
/// button {
/// onclick: move |evt: Event<MouseData>| {
/// 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, ignore
/// rsx! {
/// button {
/// onclick: move |evt: Event<MouseData>| {
/// evt.stop_propagation();
/// }
/// }
/// }
/// ```
pub fn stop_propagation(&self) {
self.propagates.set(false);
}
/// Get a reference to the inner data from this event
///
/// ```rust, ignore
/// rsx! {
/// button {
/// onclick: move |evt: Event<MouseData>| {
/// let data = evt.inner.clone();
/// cx.spawn(async move {
/// println!("{:?}", data);
/// });
/// }
/// }
/// }
/// ```
pub fn data(&self) -> Rc<T> {
self.data.clone()
}
}
impl<T: ?Sized> Clone for Event<T> {
fn clone(&self) -> Self {
Self {
propagates: self.propagates.clone(),
data: self.data.clone(),
}
}
}
impl<T> std::ops::Deref for Event<T> {
type Target = Rc<T>;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> {
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, ignore
/// rsx!{
/// MyComponent { onclick: move |evt| tracing::debug!("clicked") }
/// }
///
/// #[derive(Props)]
/// struct MyProps {
/// onclick: EventHandler<MouseEvent>,
/// }
///
/// fn MyComponent(cx: MyProps) -> Element {
/// rsx!{
/// button {
/// onclick: move |evt| cx.onclick.call(evt),
/// }
/// }
/// }
///
/// ```
pub struct EventHandler<T = ()> {
pub(crate) origin: ScopeId,
// During diffing components with EventHandler, we move the EventHandler over in place instead of rerunning the child component.
// ```rust
// #[component]
// fn Child(onclick: EventHandler<MouseEvent>) -> 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| cx.onclick.call(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 https://github.com/DioxusLabs/dioxus/pull/2298
pub(super) callback: GenerationalBox<Option<ExternalListenerCallback<T>>>,
}
impl<T> std::fmt::Debug for EventHandler<T> {
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<T: 'static> Default for EventHandler<T> {
fn default() -> Self {
EventHandler::new(|_| {})
}
}
impl<F: FnMut(T) + 'static, T: 'static> From<F> for EventHandler<T> {
fn from(f: F) -> Self {
EventHandler::new(f)
}
}
impl<T> Copy for EventHandler<T> {}
impl<T> Clone for EventHandler<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: 'static> PartialEq for EventHandler<T> {
fn eq(&self, _: &Self) -> bool {
true
}
}
type ExternalListenerCallback<T> = Rc<RefCell<dyn FnMut(T)>>;
impl<T: 'static> EventHandler<T> {
/// 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<T> {
let owner = crate::innerlude::current_owner::<generational_box::UnsyncStorage>();
let callback = owner.insert(Some(Rc::new(RefCell::new(move |event: T| {
f(event);
})) as Rc<RefCell<dyn FnMut(T)>>));
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<T> {
let callback = GenerationalBox::leak(Some(Rc::new(RefCell::new(move |event: T| {
f(event);
})) as Rc<RefCell<dyn FnMut(T)>>));
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<T>) {
self.callback.set(Some(value));
}
#[doc(hidden)]
/// This should only be used by the `rsx!` macro.
pub fn __take(&self) -> ExternalListenerCallback<T> {
self.callback
.read()
.clone()
.expect("EventHandler was manually dropped")
}
}
impl<T: 'static> std::ops::Deref for EventHandler<T> {
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<Self>).
let uninit_callable = std::mem::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 |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::<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
},
// 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 &_
}
}