use std::{
cell::{Cell, RefCell},
rc::Rc,
};
pub struct Event<T: 'static + ?Sized> {
pub data: Rc<T>,
pub(crate) propagates: Rc<Cell<bool>>,
}
impl<T> Event<T> {
#[deprecated = "use stop_propagation instead"]
pub fn cancel_bubble(&self) {
self.propagates.set(false);
}
pub fn stop_propagation(&self) {
self.propagates.set(false);
}
pub fn inner(&self) -> &Rc<T> {
&self.data
}
}
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()
}
}
#[doc(hidden)]
pub struct EventHandler<'bump, T = ()> {
pub(super) callback: RefCell<Option<ExternalListenerCallback<'bump, T>>>,
}
impl<T> Default for EventHandler<'_, T> {
fn default() -> Self {
Self {
callback: Default::default(),
}
}
}
type ExternalListenerCallback<'bump, T> = bumpalo::boxed::Box<'bump, dyn FnMut(T) + 'bump>;
impl<T> EventHandler<'_, T> {
pub fn call(&self, event: T) {
if let Some(callback) = self.callback.borrow_mut().as_mut() {
callback(event);
}
}
pub fn release(&self) {
self.callback.replace(None);
}
}