maycoon_core/
widget.rs

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