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    #[inline(always)]
42    fn with_child(mut self, child: impl Widget + 'static) -> Self
43    where
44        Self: Sized,
45    {
46        self.set_child(child);
47        self
48    }
49}
50
51/// An extension trait for widgets with multiple child widgets.
52pub trait WidgetChildrenExt {
53    /// Sets the child widgets of the widget.
54    fn set_children(&mut self, children: Vec<BoxedWidget>);
55
56    /// Sets the child widgets of the widget and returns self.
57    #[inline(always)]
58    fn with_children(mut self, children: Vec<BoxedWidget>) -> Self
59    where
60        Self: Sized,
61    {
62        self.set_children(children);
63        self
64    }
65
66    /// Adds a child widget to the widget.
67    fn add_child(&mut self, child: impl Widget + 'static);
68
69    /// Adds a child widget to the widget and returns self.
70    #[inline(always)]
71    fn with_child(mut self, child: impl Widget + 'static) -> Self
72    where
73        Self: Sized,
74    {
75        self.add_child(child);
76        self
77    }
78}
79
80/// An extension trait for widgets with a layout style.
81pub trait WidgetLayoutExt {
82    /// Sets the layout style of the widget.
83    fn set_layout_style(&mut self, layout_style: impl Into<MaybeSignal<LayoutStyle>>);
84
85    /// Sets the layout style of the widget and returns self.
86    #[inline(always)]
87    fn with_layout_style(mut self, layout_style: impl Into<MaybeSignal<LayoutStyle>>) -> Self
88    where
89        Self: Sized,
90    {
91        self.set_layout_style(layout_style);
92        self
93    }
94}