maycoon_core/
widget.rs

1use crate::app::context::AppContext;
2use crate::app::info::AppInfo;
3use crate::app::update::Update;
4use crate::layout::{LayoutNode, LayoutStyle, StyleNode};
5use crate::signal::MaybeSignal;
6use crate::vgi::Scene;
7use maycoon_theme::id::WidgetId;
8use maycoon_theme::theme::Theme;
9
10/// A boxed widget.
11pub type BoxedWidget = Box<dyn Widget>;
12
13/// The base trait for all widgets.
14pub trait Widget {
15    /// Render the widget to the canvas.
16    fn render(
17        &mut self,
18        scene: &mut dyn Scene,
19        theme: &mut dyn Theme,
20        layout_node: &LayoutNode,
21        info: &AppInfo,
22        context: AppContext,
23    );
24
25    /// Return the layout style node for layout computation.
26    fn layout_style(&self) -> StyleNode;
27
28    /// Update the widget state with given info and layout. Returns if the app should be updated.
29    fn update(&mut self, layout: &LayoutNode, context: AppContext, info: &AppInfo) -> Update;
30
31    /// Return the widget id.
32    fn widget_id(&self) -> WidgetId;
33}
34
35/// An extension trait for widgets with a single child widget.
36pub trait WidgetChildExt {
37    /// Sets the child widget of the widget.
38    fn set_child(&mut self, child: impl Widget + 'static);
39
40    /// Sets the child widget of the widget and returns self.
41    fn with_child(mut self, child: impl Widget + 'static) -> Self
42    where
43        Self: Sized,
44    {
45        self.set_child(child);
46        self
47    }
48}
49
50/// An extension trait for widgets with multiple child widgets.
51pub trait WidgetChildrenExt {
52    /// Sets the child widgets of the widget.
53    fn set_children(&mut self, children: Vec<BoxedWidget>);
54
55    /// Sets the child widgets of the widget and returns self.
56    fn with_children(mut self, children: Vec<BoxedWidget>) -> Self
57    where
58        Self: Sized,
59    {
60        self.set_children(children);
61        self
62    }
63
64    /// Adds a child widget to the widget.
65    fn add_child(&mut self, child: impl Widget + 'static);
66
67    /// Adds a child widget to the widget and returns self.
68    fn with_child(mut self, child: impl Widget + 'static) -> Self
69    where
70        Self: Sized,
71    {
72        self.add_child(child);
73        self
74    }
75}
76
77/// An extension trait for widgets with a layout style.
78pub trait WidgetLayoutExt {
79    /// Sets the layout style of the widget.
80    fn set_layout_style(&mut self, layout_style: impl Into<MaybeSignal<LayoutStyle>>);
81
82    /// Sets the layout style of the widget and returns self.
83    fn with_layout_style(mut self, layout_style: impl Into<MaybeSignal<LayoutStyle>>) -> Self
84    where
85        Self: Sized,
86    {
87        self.set_layout_style(layout_style);
88        self
89    }
90}