use crate::component::ComponentRc;
pub trait EventHandler<D: ?Sized> {
type UpdateContext;
fn set_handler_fn(
dest: &mut Self,
handler_fn: Box<dyn 'static + Fn(&mut D)>,
ctx: &mut Self::UpdateContext,
);
}
pub struct Event<D: ?Sized> {
handler: Option<Box<dyn 'static + Fn(&mut D)>>,
}
impl<D> Default for Event<D> {
fn default() -> Self {
Self::new()
}
}
impl<D> Event<D> {
pub fn new() -> Self {
Self { handler: None }
}
pub fn trigger(&self, detail: &mut D) {
if let Some(f) = &self.handler {
f(detail)
}
}
}
impl<D: ?Sized> EventHandler<D> for Event<D> {
type UpdateContext = bool;
fn set_handler_fn(
dest: &mut Self,
handler_fn: Box<dyn 'static + Fn(&mut D)>,
_ctx: &mut Self::UpdateContext,
) {
dest.handler = Some(handler_fn);
}
}
pub struct ComponentEvent<'d, C: 'static, D> {
rc: ComponentRc<C>,
detail: &'d mut D,
}
impl<'d, C: 'static, D> std::ops::Deref for ComponentEvent<'d, C, D> {
type Target = ComponentRc<C>;
fn deref(&self) -> &Self::Target {
&self.rc
}
}
impl<'d, C: 'static, D> ComponentEvent<'d, C, D> {
pub fn new(rc: ComponentRc<C>, detail: &'d mut D) -> Self {
Self { rc, detail }
}
pub fn rc(&self) -> ComponentRc<C> {
self.rc.clone()
}
pub fn clone_detail(&self) -> D
where
D: Clone,
{
self.detail.clone()
}
pub fn detail(&self) -> &D {
&self.detail
}
pub fn detail_mut(&mut self) -> &mut D {
&mut self.detail
}
}