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::measure::NodeRef;
10use crate::services::{Menu, MenuEntries, Shortcut, install_context_menu};
11use crate::style::{Align, Edges, GridPlacement, Position, Style, TextDirection};
12use crate::ui::{Handler, Ui};
13use crate::units::Length;
14use crate::view::{AnyView, Children, View};
15use crate::widget::{NodeId, Prop, WidgetKind};
16
17type Binder = Box<dyn FnOnce(&Ui, NodeId)>;
18
19/// A node description: kind, style, props (static or reactive), handlers,
20/// semantics and children. Widgets wrap an `Element` and add typed methods.
21pub struct Element {
22    pub kind: WidgetKind,
23    pub style: Style,
24    pub a11y: A11yProps,
25    pub test_id: Option<String>,
26    pub tab_index: Option<u32>,
27    static_props: Vec<Prop>,
28    binders: Vec<Binder>,
29    handlers: Vec<Handler>,
30    children: Vec<AnyView>,
31}
32
33impl Element {
34    pub fn new(kind: WidgetKind) -> Element {
35        Element {
36            kind,
37            style: Style::default(),
38            a11y: A11yProps::default(),
39            test_id: None,
40            tab_index: None,
41            static_props: Vec::new(),
42            binders: Vec::new(),
43            handlers: Vec::new(),
44            children: Vec::new(),
45        }
46    }
47
48    /// Sets a prop from a static or reactive value. Reactive values get an
49    /// effect that updates the native widget whenever they change.
50    pub fn prop<T: Clone + 'static>(&mut self, value: Value<T>, to_prop: impl Fn(T) -> Prop + 'static) {
51        match value {
52            Value::Static(v) => {
53                let prop = to_prop(v);
54                self.static_props.retain(|p| p.key() != prop.key());
55                self.static_props.push(prop);
56            }
57            Value::Dynamic(f) => self.binders.push(Box::new(move |ui, id| {
58                let ui = ui.clone();
59                effect(move || ui.set_prop(id, to_prop(f())));
60            })),
61        }
62    }
63
64    /// Sets a text of the node's semantics (its label, its description)
65    /// from a static or reactive value: a message follows the language.
66    pub fn a11y_text(&mut self, value: Value<String>, apply: impl Fn(&mut A11yProps, String) + 'static) {
67        match value {
68            Value::Static(text) => apply(&mut self.a11y, text),
69            Value::Dynamic(f) => self.binders.push(Box::new(move |ui, id| {
70                let ui = ui.clone();
71                effect(move || {
72                    let text = f();
73                    ui.update_a11y(id, |a11y| apply(a11y, text));
74                });
75            })),
76        }
77    }
78
79    /// Sets part of the style from a static or reactive value.
80    pub fn style_prop<T: Clone + 'static>(&mut self, value: Value<T>, apply: impl Fn(&mut Style, T) + 'static) {
81        match value {
82            Value::Static(v) => apply(&mut self.style, v),
83            Value::Dynamic(f) => self.binders.push(Box::new(move |ui, id| {
84                let ui = ui.clone();
85                effect(move || {
86                    let v = f();
87                    ui.update_style(id, |s| apply(s, v));
88                });
89            })),
90        }
91    }
92
93    pub fn on(&mut self, handler: impl Fn(&UiEvent) + 'static) {
94        self.handlers.push(Rc::new(handler));
95    }
96
97    /// Takes `shortcut` while the node, or a control inside it, has
98    /// keyboard focus (`Prop::Keys`), and runs `handler` when it's pressed.
99    /// For containers, groups, lists and tables.
100    pub fn on_key(&mut self, shortcut: Shortcut, handler: impl Fn() + 'static) {
101        let keys = self.static_props.iter_mut().find_map(|p| match p {
102            Prop::Keys(keys) => Some(keys),
103            _ => None,
104        });
105        match keys {
106            Some(keys) if keys.contains(&shortcut) => {}
107            Some(keys) => keys.push(shortcut),
108            None => self.static_props.push(Prop::Keys(vec![shortcut])),
109        }
110        self.on(move |event| {
111            if *event == UiEvent::Key(shortcut) {
112                handler();
113            }
114        });
115    }
116
117    /// Reports the pointer coming over the node (`Prop::Hover`), and runs
118    /// `handler` with whether it's over it. For containers and groups.
119    pub fn on_hover(&mut self, handler: impl Fn(bool) + 'static) {
120        self.prop(Value::Static(true), Prop::Hover);
121        self.on(move |event| {
122            if let UiEvent::Hover(over) = event {
123                handler(*over);
124            }
125        });
126    }
127
128    /// Reports a double click on the node (`Prop::DoubleClick`), and runs
129    /// `handler` for it. For containers and groups.
130    pub fn on_double_click(&mut self, handler: impl Fn() + 'static) {
131        self.prop(Value::Static(true), Prop::DoubleClick);
132        self.on(move |event| {
133            if *event == UiEvent::DoubleClick {
134                handler();
135            }
136        });
137    }
138
139    /// Runs `f` right after the node is created, in the building scope.
140    pub fn after_build(&mut self, f: impl FnOnce(&Ui, NodeId) + 'static) {
141        self.binders.push(Box::new(f));
142    }
143
144    pub fn add_children(&mut self, children: impl Children) {
145        children.into_views(&mut self.children);
146    }
147}
148
149impl View for Element {
150    fn build(self, ui: &Ui) -> NodeId {
151        let id = ui.create(self.kind, self.static_props);
152        ui.set_style(id, self.style);
153        if !self.a11y.is_empty() {
154            ui.set_a11y(id, self.a11y);
155        }
156        if let Some(test_id) = self.test_id {
157            ui.set_test_id(id, test_id);
158        }
159        if self.tab_index.is_some() {
160            ui.set_tab_index(id, self.tab_index);
161        }
162        for handler in self.handlers {
163            ui.on_event(id, move |e| handler(e));
164        }
165        for binder in self.binders {
166            binder(ui, id);
167        }
168        for child in self.children {
169            let child = child.build(ui);
170            ui.append_child(id, child);
171        }
172        id
173    }
174}
175
176/// Defines style setters that take static or reactive values:
177/// `.width(200)`, `.width(width_signal)`, `.width(move || …)`.
178macro_rules! style_setters {
179    ($( $(#[$doc:meta])* fn $name:ident($ty:ty) => |$s:ident, $v:ident| $body:expr; )*) => {$(
180        $(#[$doc])*
181        fn $name(mut self, value: impl IntoValue<$ty>) -> Self {
182            self.element().style_prop(value.into_value(), |$s: &mut Style, $v: $ty| $body);
183            self
184        }
185    )*};
186}
187
188/// Style, semantics and test hooks shared by every widget builder.
189///
190/// Every style setter accepts a literal, a signal or a closure; reactive
191/// values update the layout whenever they change.
192pub trait ElementBuilder: Sized {
193    fn element(&mut self) -> &mut Element;
194
195    /// Escape hatch: edit the style directly (static).
196    fn style(mut self, f: impl FnOnce(&mut Style)) -> Self {
197        f(&mut self.element().style);
198        self
199    }
200
201    /// Escape hatch: edit the style reactively. `f` re-runs whenever the
202    /// signals it reads change, and must set every field it cares about.
203    fn style_with(mut self, f: impl Fn(&mut Style) + 'static) -> Self {
204        self.element().style_prop(Value::Dynamic(Rc::new(|| ())), move |s, ()| f(s));
205        self
206    }
207
208    style_setters! {
209        fn width(Length) => |s, v| s.width = v;
210        fn height(Length) => |s, v| s.height = v;
211        fn min_width(Length) => |s, v| s.min_width = v;
212        fn min_height(Length) => |s, v| s.min_height = v;
213        fn max_width(Length) => |s, v| s.max_width = v;
214        fn max_height(Length) => |s, v| s.max_height = v;
215        fn aspect_ratio(f32) => |s, v| s.aspect_ratio = Some(v);
216
217        fn padding(Length) => |s, v| s.padding = Edges::all(v);
218        fn padding_x(Length) => |s, v| { s.padding.start = v; s.padding.end = v; };
219        fn padding_y(Length) => |s, v| { s.padding.top = v; s.padding.bottom = v; };
220        fn padding_start(Length) => |s, v| s.padding.start = v;
221        fn padding_end(Length) => |s, v| s.padding.end = v;
222        fn padding_top(Length) => |s, v| s.padding.top = v;
223        fn padding_bottom(Length) => |s, v| s.padding.bottom = v;
224
225        fn margin(Length) => |s, v| s.margin = Edges::all(v);
226        fn margin_x(Length) => |s, v| { s.margin.start = v; s.margin.end = v; };
227        fn margin_y(Length) => |s, v| { s.margin.top = v; s.margin.bottom = v; };
228        fn margin_start(Length) => |s, v| s.margin.start = v;
229        fn margin_end(Length) => |s, v| s.margin.end = v;
230        fn margin_top(Length) => |s, v| s.margin.top = v;
231        fn margin_bottom(Length) => |s, v| s.margin.bottom = v;
232
233        fn grow(f32) => |s, v| s.flex_grow = v;
234        fn shrink(f32) => |s, v| s.flex_shrink = v;
235        fn basis(Length) => |s, v| s.flex_basis = v;
236        fn align_self(Align) => |s, v| s.align_self = Some(v);
237        /// Alignment inside a grid cell along the inline axis.
238        fn justify_self(Align) => |s, v| s.justify_self = Some(v);
239
240        /// Inset from the top of the containing block (with `absolute()`).
241        fn top(Length) => |s, v| s.inset.top = v;
242        fn bottom(Length) => |s, v| s.inset.bottom = v;
243        /// Inset from the inline start (left in LTR, right in RTL).
244        fn start(Length) => |s, v| s.inset.start = v;
245        fn end(Length) => |s, v| s.inset.end = v;
246
247        fn grid_column(GridPlacement) => |s, v| s.grid_column = v;
248        fn grid_row(GridPlacement) => |s, v| s.grid_row = v;
249
250        fn direction(TextDirection) => |s, v| s.direction = v;
251        /// Not laid out, not visible, not focusable, not in the a11y tree.
252        /// Un-hiding restores whatever `display` the node had.
253        fn hidden(bool) => |s, v| s.hidden = v;
254    }
255
256    fn size(self, width: impl IntoValue<Length>, height: impl IntoValue<Length>) -> Self {
257        self.width(width).height(height)
258    }
259
260    /// Takes the node out of flow; position it with `top`/`start`/….
261    fn absolute(self) -> Self {
262        self.style(|s| s.position = Position::Absolute)
263    }
264
265    /// A tooltip: text the platform shows, its own way, when the pointer
266    /// rests on the widget, and assistive technology reads as its
267    /// description. Empty: none.
268    fn tooltip(mut self, text: impl IntoValue<String>) -> Self {
269        self.element().prop(text.into_value(), Prop::Tooltip);
270        self
271    }
272
273    /// A context menu: the platform shows it its own way, on a right-click,
274    /// a long press or the menu key, and over children without one of
275    /// their own. Takes items, separators and submenus, as a [`Menu`]
276    /// does, with the same reactive titles, states and check marks:
277    ///
278    /// ```ignore
279    /// Text::new(name).context_menu((
280    ///     MenuItem::new("Rename").on_select(rename),
281    ///     MenuSeparator,
282    ///     MenuItem::new("Delete").on_select(delete),
283    /// ))
284    /// ```
285    fn context_menu(mut self, entries: impl MenuEntries) -> Self {
286        let menu = Menu::new(String::new()).children(entries);
287        self.element().after_build(move |ui, id| install_context_menu(ui, id, menu));
288        self
289    }
290
291    /// A context menu built by `entries`, and built again whenever what it
292    /// reads changes, as [`Menu::children_with`] builds its entries.
293    fn context_menu_with<E: MenuEntries>(mut self, entries: impl Fn() -> E + 'static) -> Self {
294        let menu = Menu::new(String::new()).children_with(entries);
295        self.element().after_build(move |ui, id| install_context_menu(ui, id, menu));
296        self
297    }
298
299    fn a11y_label(mut self, label: impl IntoValue<String>) -> Self {
300        self.element().a11y_text(label.into_value(), |a11y, label| a11y.label = Some(label));
301        self
302    }
303    fn a11y_description(mut self, description: impl IntoValue<String>) -> Self {
304        self.element().a11y_text(description.into_value(), |a11y, text| a11y.description = Some(text));
305        self
306    }
307    fn a11y_role(mut self, role: Role) -> Self {
308        self.element().a11y.role = Some(role);
309        self
310    }
311    fn a11y_hidden(mut self) -> Self {
312        self.element().a11y.hidden = true;
313        self
314    }
315    /// Called when this control gains keyboard focus.
316    fn on_focus(mut self, handler: impl Fn() + 'static) -> Self {
317        self.element().on(move |event| {
318            if *event == UiEvent::FocusIn {
319                handler();
320            }
321        });
322        self
323    }
324
325    /// Called when this control loses keyboard focus.
326    fn on_blur(mut self, handler: impl Fn() + 'static) -> Self {
327        self.element().on(move |event| {
328            if *event == UiEvent::FocusOut {
329                handler();
330            }
331        });
332        self
333    }
334
335    /// Moves this control ahead in the Tab order. Controls with a tab index
336    /// come first (lowest first); the rest follow in reading order. Prefer
337    /// arranging the tree in the order users should visit it.
338    fn tab_index(mut self, index: u32) -> Self {
339        self.element().tab_index = Some(index);
340        self
341    }
342
343    /// Points `node` at this widget's node, for [`use_size`](crate::use_size)
344    /// and to focus it from code ([`NodeRef::focus`]).
345    fn node_ref(mut self, node: NodeRef) -> Self {
346        self.element().after_build(move |ui, id| node.attach(ui, id));
347        self
348    }
349
350    /// Last-resort handle for tests; prefer finding nodes by role and name.
351    fn test_id(mut self, id: impl Into<String>) -> Self {
352        self.element().test_id = Some(id.into());
353        self
354    }
355}
356
357impl ElementBuilder for Element {
358    fn element(&mut self) -> &mut Element {
359        self
360    }
361}