From 9d55dacde275731df66810edb05849f3f6ff5ae4 Mon Sep 17 00:00:00 2001 From: Leo dev Date: Sat, 24 Jan 2026 17:22:59 +0100 Subject: [PATCH] Context children --- examples/hello_world.rs | 18 ++++++------------ src/component.rs | 28 +++++++++++++++++++++++++++- src/lib.rs | 1 + 3 files changed, 34 insertions(+), 13 deletions(-) diff --git a/examples/hello_world.rs b/examples/hello_world.rs index cd7dcd5..387c314 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -23,20 +23,14 @@ fn main() { } fn app(cx: &Arc) -> View { - let mc_cx = Context::new(my_component); + cx.child(my_component, None); - cx.on_event({ - let mc_cx = mc_cx.clone(); - move |_, &KeyPress| { - mc_cx.emit_event(&KeyPress); + Arc::new({ + let cx = cx.clone(); + + move |ctx| { + cx.draw_children(ctx); } - }); - - mc_cx.refresh(); - - Arc::new(move |ctx| { - let area = ctx.allocate(0, 0, 10, 10); - ctx.draw_view(area, mc_cx.get_view()); }) } diff --git a/src/component.rs b/src/component.rs index 9404930..b9ea6e5 100644 --- a/src/component.rs +++ b/src/component.rs @@ -4,7 +4,7 @@ use std::{ sync::{Arc, Mutex}, }; -use crate::View; +use crate::{render::DrawContext, View, ViewWrapper}; pub trait Event { fn as_any(&self) -> &dyn Any; @@ -23,6 +23,7 @@ pub struct Context { component: Mutex, event_handlers: Mutex>>, view: Mutex, + children: Mutex, Option)>>, } impl Context { @@ -31,6 +32,7 @@ impl Context { component: Mutex::new(Arc::new(component)), event_handlers: Mutex::new(HashMap::new()), view: Mutex::new(Arc::new(|_| {})), + children: Mutex::new(Vec::new()), }) } @@ -108,4 +110,28 @@ impl Context { } } } + + pub fn child) -> View + Send + Sync + 'static>( + self: &Arc, + child: F, + view_wrapper: Option, + ) { + let ctx = Context::new(child); + + ctx.refresh(); + + self.children.lock().unwrap().push((ctx, view_wrapper)); + } + + pub fn draw_children(self: &Arc, ctx: &mut DrawContext) { + for (child, view_wrapper) in self.children.lock().unwrap().iter() { + let view = child.get_view(); + + if let Some(view_wrapper) = view_wrapper { + view_wrapper(ctx, view) + } else { + ctx.draw_view(ctx.allocated.clone(), view); + } + } + } } diff --git a/src/lib.rs b/src/lib.rs index f70bd95..16af55e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,3 +16,4 @@ pub mod prelude { } pub type View = Arc; +pub type ViewWrapper = Arc;