diff --git a/examples/hello_world.rs b/examples/hello_world.rs index 9eb4fa7..2bed746 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -1,11 +1,16 @@ -use osui::{Context, Node}; +use osui::{Context, Event, Node}; + +pub struct ClickEvent; + +impl Event for ClickEvent { + fn as_any(&self) -> &dyn std::any::Any { + self + } +} fn app(cx: &mut Context) -> Node { // Hooks - // Event handlers - // cx.event(|e: &ClickEvent| { - - // }); + cx.event(|_: &ClickEvent| {}); Box::new(|renderer| { renderer.draw_text("Hello, World!", 0, 0).unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 020ac87..a316c61 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +use std::any::Any; + use crate::renderer::{OsuiRenderer, Renderer}; pub mod error; @@ -8,7 +10,13 @@ pub use error::Result; pub type Node = Box; pub type Component = Box Node>; -pub struct Context {} +pub trait Event { + fn as_any(&self) -> &dyn Any; +} + +pub struct Context { + event_handlers: Vec>, +} pub struct Osui { node: Node, @@ -17,14 +25,18 @@ pub struct Osui { impl Osui { pub fn new(component: Component) -> Self { - let mut cx = Context {}; + let mut cx = Context { + event_handlers: Vec::new(), + }; Osui { node: component(&mut cx), renderer: None, } } pub fn with_renderer(component: Component, renderer: Box) -> Self { - let mut cx = Context {}; + let mut cx = Context { + event_handlers: Vec::new(), + }; Osui { node: component(&mut cx), renderer: Some(renderer), @@ -41,3 +53,21 @@ impl Osui { Ok(()) } } + +impl Context { + pub fn event(&mut self, handler: F) { + self.event_handlers.push(Box::new(move |e| { + if let Some(e) = e.as_any().downcast_ref() { + (handler)(e) + } + })); + } + + pub fn global_event(&mut self, handler: F) { + self.event_handlers.push(Box::new(move |e| { + if let Some(e) = e.as_any().downcast_ref() { + (handler)(e) + } + })); + } +}