Testing new structure

This commit is contained in:
2025-11-20 17:10:12 +01:00
parent e4110976cd
commit ff351caee0
2 changed files with 43 additions and 8 deletions
+10 -5
View File
@@ -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 { fn app(cx: &mut Context) -> Node {
// Hooks // Hooks
// Event handlers cx.event(|_: &ClickEvent| {});
// cx.event(|e: &ClickEvent| {
// });
Box::new(|renderer| { Box::new(|renderer| {
renderer.draw_text("Hello, World!", 0, 0).unwrap(); renderer.draw_text("Hello, World!", 0, 0).unwrap();
+33 -3
View File
@@ -1,3 +1,5 @@
use std::any::Any;
use crate::renderer::{OsuiRenderer, Renderer}; use crate::renderer::{OsuiRenderer, Renderer};
pub mod error; pub mod error;
@@ -8,7 +10,13 @@ pub use error::Result;
pub type Node = Box<dyn Fn(&mut dyn Renderer)>; pub type Node = Box<dyn Fn(&mut dyn Renderer)>;
pub type Component = Box<dyn Fn(&mut Context) -> Node>; pub type Component = Box<dyn Fn(&mut Context) -> Node>;
pub struct Context {} pub trait Event {
fn as_any(&self) -> &dyn Any;
}
pub struct Context {
event_handlers: Vec<Box<dyn Fn(&dyn Event)>>,
}
pub struct Osui { pub struct Osui {
node: Node, node: Node,
@@ -17,14 +25,18 @@ pub struct Osui {
impl Osui { impl Osui {
pub fn new(component: Component) -> Self { pub fn new(component: Component) -> Self {
let mut cx = Context {}; let mut cx = Context {
event_handlers: Vec::new(),
};
Osui { Osui {
node: component(&mut cx), node: component(&mut cx),
renderer: None, renderer: None,
} }
} }
pub fn with_renderer(component: Component, renderer: Box<dyn Renderer>) -> Self { pub fn with_renderer(component: Component, renderer: Box<dyn Renderer>) -> Self {
let mut cx = Context {}; let mut cx = Context {
event_handlers: Vec::new(),
};
Osui { Osui {
node: component(&mut cx), node: component(&mut cx),
renderer: Some(renderer), renderer: Some(renderer),
@@ -41,3 +53,21 @@ impl Osui {
Ok(()) Ok(())
} }
} }
impl Context {
pub fn event<E: Event + 'static, F: Fn(&E) + 'static>(&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<E: Event + 'static, F: Fn(&E) + 'static>(&mut self, handler: F) {
self.event_handlers.push(Box::new(move |e| {
if let Some(e) = e.as_any().downcast_ref() {
(handler)(e)
}
}));
}
}