Skip to main content

mitsuami_core/
element.rs

1//! The generic builder every widget is made of.
2
3use std::rc::Rc;
4
5use mitsuami_reactive::{IntoValue, Value, effect};
6
7use crate::a11y::{A11yProps, Role};
8use crate::command::UiEvent;
9use crate::style::{Align, Edges, GridPlacement, Position, Style, TextDirection};
10use crate::ui::{Handler, Ui};
11use crate::units::Length;
12use crate::view::{AnyView, Children, View};
13use crate::widget::{NodeId, Prop, WidgetKind};
14
15type Binder = Box<dyn FnOnce(&Ui, NodeId)>;
16
17/// A node description: kind, style, props (static or reactive), handlers,
18/// semantics and children. Widgets wrap an `Element` and add typed methods.
19pub struct Element {
20    pub kind: WidgetKind,
21    pub style: Style,
22    pub a11y: A11yProps,
23    pub test_id: Option<String>,
24    pub tab_index: Option<u32>,
25    static_props: Vec<Prop>,
26    binders: Vec<Binder>,
27    handlers: Vec<Handler>,
28    children: Vec<AnyView>,
29}
30
31impl Element {
32    pub fn new(kind: WidgetKind) -> Element {
33        Element {
34            kind,
35            style: Style::default(),
36            a11y: A11yProps::default(),
37            test_id: None,
38            tab_index: None,
39            static_props: Vec::new(),
40            binders: Vec::new(),
41            handlers: Vec::new(),
42            children: Vec::new(),
43        }
44    }
45
46    /// Sets a prop from a static or reactive value. Reactive values get an
47    /// effect that updates the native widget whenever they change.
48    pub fn prop<T: Clone + 'static>(&mut self, value: Value<T>, to_prop: impl Fn(T) -> Prop + 'static) {
49        match value {
50            Value::Static(v) => {
51                let prop = to_prop(v);
52                self.static_props.retain(|p| p.key() != prop.key());
53                self.static_props.push(prop);
54            }
55            Value::Dynamic(f) => self.binders.push(Box::new(move |ui, id| {
56                let ui = ui.clone();
57                effect(move || ui.set_prop(id, to_prop(f())));
58            })),
59        }
60    }
61
62    /// Sets part of the style from a static or reactive value.
63    pub fn style_prop<T: Clone + 'static>(&mut self, value: Value<T>, apply: impl Fn(&mut Style, T) + 'static) {
64        match value {
65            Value::Static(v) => apply(&mut self.style, v),
66            Value::Dynamic(f) => self.binders.push(Box::new(move |ui, id| {
67                let ui = ui.clone();
68                effect(move || {
69                    let v = f();
70                    ui.update_style(id, |s| apply(s, v));
71                });
72            })),
73        }
74    }
75
76    pub fn on(&mut self, handler: impl Fn(&UiEvent) + 'static) {
77        self.handlers.push(Rc::new(handler));
78    }
79
80    /// Runs `f` right after the node is created, in the building scope.
81    pub fn after_build(&mut self, f: impl FnOnce(&Ui, NodeId) + 'static) {
82        self.binders.push(Box::new(f));
83    }
84
85    pub fn add_children(&mut self, children: impl Children) {
86        children.into_views(&mut self.children);
87    }
88}
89
90impl View for Element {
91    fn build(self, ui: &Ui) -> NodeId {
92        let id = ui.create(self.kind, self.static_props);
93        ui.set_style(id, self.style);
94        if !self.a11y.is_empty() {
95            ui.set_a11y(id, self.a11y);
96        }
97        if let Some(test_id) = self.test_id {
98            ui.set_test_id(id, test_id);
99        }
100        if self.tab_index.is_some() {
101            ui.set_tab_index(id, self.tab_index);
102        }
103        for handler in self.handlers {
104            ui.on_event(id, move |e| handler(e));
105        }
106        for binder in self.binders {
107            binder(ui, id);
108        }
109        for child in self.children {
110            let child = child.build(ui);
111            ui.append_child(id, child);
112        }
113        id
114    }
115}
116
117/// Defines style setters that take static or reactive values:
118/// `.width(200)`, `.width(width_signal)`, `.width(move || …)`.
119macro_rules! style_setters {
120    ($( $(#[$doc:meta])* fn $name:ident($ty:ty) => |$s:ident, $v:ident| $body:expr; )*) => {$(
121        $(#[$doc])*
122        fn $name(mut self, value: impl IntoValue<$ty>) -> Self {
123            self.element().style_prop(value.into_value(), |$s: &mut Style, $v: $ty| $body);
124            self
125        }
126    )*};
127}
128
129/// Style, semantics and test hooks shared by every widget builder.
130///
131/// Every style setter accepts a literal, a signal or a closure; reactive
132/// values update the layout whenever they change.
133pub trait ElementBuilder: Sized {
134    fn element(&mut self) -> &mut Element;
135
136    /// Escape hatch: edit the style directly (static).
137    fn style(mut self, f: impl FnOnce(&mut Style)) -> Self {
138        f(&mut self.element().style);
139        self
140    }
141
142    /// Escape hatch: edit the style reactively. `f` re-runs whenever the
143    /// signals it reads change, and must set every field it cares about.
144    fn style_with(mut self, f: impl Fn(&mut Style) + 'static) -> Self {
145        self.element().style_prop(Value::Dynamic(Rc::new(|| ())), move |s, ()| f(s));
146        self
147    }
148
149    style_setters! {
150        fn width(Length) => |s, v| s.width = v;
151        fn height(Length) => |s, v| s.height = v;
152        fn min_width(Length) => |s, v| s.min_width = v;
153        fn min_height(Length) => |s, v| s.min_height = v;
154        fn max_width(Length) => |s, v| s.max_width = v;
155        fn max_height(Length) => |s, v| s.max_height = v;
156        fn aspect_ratio(f32) => |s, v| s.aspect_ratio = Some(v);
157
158        fn padding(Length) => |s, v| s.padding = Edges::all(v);
159        fn padding_x(Length) => |s, v| { s.padding.start = v; s.padding.end = v; };
160        fn padding_y(Length) => |s, v| { s.padding.top = v; s.padding.bottom = v; };
161        fn padding_start(Length) => |s, v| s.padding.start = v;
162        fn padding_end(Length) => |s, v| s.padding.end = v;
163        fn padding_top(Length) => |s, v| s.padding.top = v;
164        fn padding_bottom(Length) => |s, v| s.padding.bottom = v;
165
166        fn margin(Length) => |s, v| s.margin = Edges::all(v);
167        fn margin_x(Length) => |s, v| { s.margin.start = v; s.margin.end = v; };
168        fn margin_y(Length) => |s, v| { s.margin.top = v; s.margin.bottom = v; };
169        fn margin_start(Length) => |s, v| s.margin.start = v;
170        fn margin_end(Length) => |s, v| s.margin.end = v;
171        fn margin_top(Length) => |s, v| s.margin.top = v;
172        fn margin_bottom(Length) => |s, v| s.margin.bottom = v;
173
174        fn grow(f32) => |s, v| s.flex_grow = v;
175        fn shrink(f32) => |s, v| s.flex_shrink = v;
176        fn basis(Length) => |s, v| s.flex_basis = v;
177        fn align_self(Align) => |s, v| s.align_self = Some(v);
178        /// Alignment inside a grid cell along the inline axis.
179        fn justify_self(Align) => |s, v| s.justify_self = Some(v);
180
181        /// Inset from the top of the containing block (with `absolute()`).
182        fn top(Length) => |s, v| s.inset.top = v;
183        fn bottom(Length) => |s, v| s.inset.bottom = v;
184        /// Inset from the inline start (left in LTR, right in RTL).
185        fn start(Length) => |s, v| s.inset.start = v;
186        fn end(Length) => |s, v| s.inset.end = v;
187
188        fn grid_column(GridPlacement) => |s, v| s.grid_column = v;
189        fn grid_row(GridPlacement) => |s, v| s.grid_row = v;
190
191        fn direction(TextDirection) => |s, v| s.direction = v;
192        /// Not laid out, not visible, not focusable, not in the a11y tree.
193        /// Un-hiding restores whatever `display` the node had.
194        fn hidden(bool) => |s, v| s.hidden = v;
195    }
196
197    fn size(self, width: impl IntoValue<Length>, height: impl IntoValue<Length>) -> Self {
198        self.width(width).height(height)
199    }
200
201    /// Takes the node out of flow; position it with `top`/`start`/….
202    fn absolute(self) -> Self {
203        self.style(|s| s.position = Position::Absolute)
204    }
205
206    fn a11y_label(mut self, label: impl Into<String>) -> Self {
207        self.element().a11y.label = Some(label.into());
208        self
209    }
210    fn a11y_description(mut self, description: impl Into<String>) -> Self {
211        self.element().a11y.description = Some(description.into());
212        self
213    }
214    fn a11y_role(mut self, role: Role) -> Self {
215        self.element().a11y.role = Some(role);
216        self
217    }
218    fn a11y_hidden(mut self) -> Self {
219        self.element().a11y.hidden = true;
220        self
221    }
222    /// Called when this control gains keyboard focus.
223    fn on_focus(mut self, handler: impl Fn() + 'static) -> Self {
224        self.element().on(move |event| {
225            if *event == UiEvent::FocusIn {
226                handler();
227            }
228        });
229        self
230    }
231
232    /// Called when this control loses keyboard focus.
233    fn on_blur(mut self, handler: impl Fn() + 'static) -> Self {
234        self.element().on(move |event| {
235            if *event == UiEvent::FocusOut {
236                handler();
237            }
238        });
239        self
240    }
241
242    /// Moves this control ahead in the Tab order. Controls with a tab index
243    /// come first (lowest first); the rest follow in reading order. Prefer
244    /// arranging the tree in the order users should visit it.
245    fn tab_index(mut self, index: u32) -> Self {
246        self.element().tab_index = Some(index);
247        self
248    }
249
250    /// Last-resort handle for tests; prefer finding nodes by role and name.
251    fn test_id(mut self, id: impl Into<String>) -> Self {
252        self.element().test_id = Some(id.into());
253        self
254    }
255}
256
257impl ElementBuilder for Element {
258    fn element(&mut self) -> &mut Element {
259        self
260    }
261}