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, install_context_menu_on_open};
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    /// Reports a click on the node (`Prop::Click`), and runs `handler` for
140    /// it. For containers and groups.
141    pub fn on_click(&mut self, handler: impl Fn() + 'static) {
142        self.prop(Value::Static(true), Prop::Click);
143        self.on(move |event| {
144            if *event == UiEvent::Click {
145                handler();
146            }
147        });
148    }
149
150    /// Runs `f` right after the node is created, in the building scope.
151    pub fn after_build(&mut self, f: impl FnOnce(&Ui, NodeId) + 'static) {
152        self.binders.push(Box::new(f));
153    }
154
155    pub fn add_children(&mut self, children: impl Children) {
156        children.into_views(&mut self.children);
157    }
158}
159
160impl View for Element {
161    fn build(self, ui: &Ui) -> NodeId {
162        let id = ui.create(self.kind, self.static_props);
163        ui.set_style(id, self.style);
164        if !self.a11y.is_empty() {
165            ui.set_a11y(id, self.a11y);
166        }
167        if let Some(test_id) = self.test_id {
168            ui.set_test_id(id, test_id);
169        }
170        if self.tab_index.is_some() {
171            ui.set_tab_index(id, self.tab_index);
172        }
173        for handler in self.handlers {
174            ui.on_event(id, move |e| handler(e));
175        }
176        for binder in self.binders {
177            binder(ui, id);
178        }
179        for child in self.children {
180            let child = child.build(ui);
181            ui.append_child(id, child);
182        }
183        id
184    }
185}
186
187/// Defines style setters that take static or reactive values:
188/// `.width(200)`, `.width(width_signal)`, `.width(move || …)`.
189macro_rules! style_setters {
190    ($( $(#[$doc:meta])* fn $name:ident($ty:ty) => |$s:ident, $v:ident| $body:expr; )*) => {$(
191        $(#[$doc])*
192        fn $name(mut self, value: impl IntoValue<$ty>) -> Self {
193            self.element().style_prop(value.into_value(), |$s: &mut Style, $v: $ty| $body);
194            self
195        }
196    )*};
197}
198
199/// Style, semantics and test hooks shared by every widget builder.
200///
201/// Every style setter accepts a literal, a signal or a closure; reactive
202/// values update the layout whenever they change.
203pub trait ElementBuilder: Sized {
204    fn element(&mut self) -> &mut Element;
205
206    /// Escape hatch: edit the style directly (static).
207    fn style(mut self, f: impl FnOnce(&mut Style)) -> Self {
208        f(&mut self.element().style);
209        self
210    }
211
212    /// Escape hatch: edit the style reactively. `f` re-runs whenever the
213    /// signals it reads change, and must set every field it cares about.
214    fn style_with(mut self, f: impl Fn(&mut Style) + 'static) -> Self {
215        self.element().style_prop(Value::Dynamic(Rc::new(|| ())), move |s, ()| f(s));
216        self
217    }
218
219    style_setters! {
220        fn width(Length) => |s, v| s.width = v;
221        fn height(Length) => |s, v| s.height = v;
222        fn min_width(Length) => |s, v| s.min_width = v;
223        fn min_height(Length) => |s, v| s.min_height = v;
224        fn max_width(Length) => |s, v| s.max_width = v;
225        fn max_height(Length) => |s, v| s.max_height = v;
226        fn aspect_ratio(f32) => |s, v| s.aspect_ratio = Some(v);
227
228        fn padding(Length) => |s, v| s.padding = Edges::all(v);
229        fn padding_x(Length) => |s, v| { s.padding.start = v; s.padding.end = v; };
230        fn padding_y(Length) => |s, v| { s.padding.top = v; s.padding.bottom = v; };
231        fn padding_start(Length) => |s, v| s.padding.start = v;
232        fn padding_end(Length) => |s, v| s.padding.end = v;
233        fn padding_top(Length) => |s, v| s.padding.top = v;
234        fn padding_bottom(Length) => |s, v| s.padding.bottom = v;
235
236        fn margin(Length) => |s, v| s.margin = Edges::all(v);
237        fn margin_x(Length) => |s, v| { s.margin.start = v; s.margin.end = v; };
238        fn margin_y(Length) => |s, v| { s.margin.top = v; s.margin.bottom = v; };
239        fn margin_start(Length) => |s, v| s.margin.start = v;
240        fn margin_end(Length) => |s, v| s.margin.end = v;
241        fn margin_top(Length) => |s, v| s.margin.top = v;
242        fn margin_bottom(Length) => |s, v| s.margin.bottom = v;
243
244        fn grow(f32) => |s, v| s.flex_grow = v;
245        fn shrink(f32) => |s, v| s.flex_shrink = v;
246        fn basis(Length) => |s, v| s.flex_basis = v;
247        fn align_self(Align) => |s, v| s.align_self = Some(v);
248        /// Alignment inside a grid cell along the inline axis.
249        fn justify_self(Align) => |s, v| s.justify_self = Some(v);
250
251        /// Inset from the top of the containing block (with `absolute()`).
252        fn top(Length) => |s, v| s.inset.top = v;
253        fn bottom(Length) => |s, v| s.inset.bottom = v;
254        /// Inset from the inline start (left in LTR, right in RTL).
255        fn start(Length) => |s, v| s.inset.start = v;
256        fn end(Length) => |s, v| s.inset.end = v;
257
258        fn grid_column(GridPlacement) => |s, v| s.grid_column = v;
259        fn grid_row(GridPlacement) => |s, v| s.grid_row = v;
260
261        fn direction(TextDirection) => |s, v| s.direction = v;
262        /// Not laid out, not visible, not focusable, not in the a11y tree.
263        /// Un-hiding restores whatever `display` the node had.
264        fn hidden(bool) => |s, v| s.hidden = v;
265    }
266
267    fn size(self, width: impl IntoValue<Length>, height: impl IntoValue<Length>) -> Self {
268        self.width(width).height(height)
269    }
270
271    /// Takes the node out of flow; position it with `top`/`start`/….
272    fn absolute(self) -> Self {
273        self.style(|s| s.position = Position::Absolute)
274    }
275
276    /// A tooltip: text the platform shows, its own way, when the pointer
277    /// rests on the widget, and assistive technology reads as its
278    /// description. Empty: none.
279    fn tooltip(mut self, text: impl IntoValue<String>) -> Self {
280        self.element().prop(text.into_value(), Prop::Tooltip);
281        self
282    }
283
284    /// A context menu: the platform shows it its own way, on a right-click,
285    /// a long press or the menu key, and over children without one of
286    /// their own. Takes items, separators and submenus, as a [`Menu`]
287    /// does, with the same reactive titles, states and check marks:
288    ///
289    /// ```ignore
290    /// Text::new(name).context_menu((
291    ///     MenuItem::new("Rename").on_select(rename),
292    ///     MenuSeparator,
293    ///     MenuItem::new("Delete").on_select(delete),
294    /// ))
295    /// ```
296    fn context_menu(mut self, entries: impl MenuEntries) -> Self {
297        let menu = Menu::new(String::new()).children(entries);
298        self.element().after_build(move |ui, id| install_context_menu(ui, id, menu));
299        self
300    }
301
302    /// A context menu built by `entries`, and built again whenever what it
303    /// reads changes, as [`Menu::children_with`] builds its entries.
304    fn context_menu_with<E: MenuEntries>(mut self, entries: impl Fn() -> E + 'static) -> Self {
305        let menu = Menu::new(String::new()).children_with(entries);
306        self.element().after_build(move |ui, id| install_context_menu(ui, id, menu));
307        self
308    }
309
310    /// A context menu built by `entries` each time the platform opens it,
311    /// for a menu that depends on what's selected or under the pointer at
312    /// that moment: a table row's menu acting on the selection. What it
313    /// reads is read then, not followed.
314    fn context_menu_on_open<E: MenuEntries>(mut self, entries: impl Fn() -> E + 'static) -> Self {
315        let build: Rc<dyn Fn() -> Menu> = Rc::new(move || Menu::new(String::new()).children(entries()));
316        self.element().after_build(move |ui, id| install_context_menu_on_open(ui, id, build));
317        self
318    }
319
320    fn a11y_label(mut self, label: impl IntoValue<String>) -> Self {
321        self.element().a11y_text(label.into_value(), |a11y, label| a11y.label = Some(label));
322        self
323    }
324    fn a11y_description(mut self, description: impl IntoValue<String>) -> Self {
325        self.element().a11y_text(description.into_value(), |a11y, text| a11y.description = Some(text));
326        self
327    }
328    fn a11y_role(mut self, role: Role) -> Self {
329        self.element().a11y.role = Some(role);
330        self
331    }
332    fn a11y_hidden(mut self) -> Self {
333        self.element().a11y.hidden = true;
334        self
335    }
336    /// Called when this control gains keyboard focus.
337    fn on_focus(mut self, handler: impl Fn() + 'static) -> Self {
338        self.element().on(move |event| {
339            if *event == UiEvent::FocusIn {
340                handler();
341            }
342        });
343        self
344    }
345
346    /// Called when this control loses keyboard focus.
347    fn on_blur(mut self, handler: impl Fn() + 'static) -> Self {
348        self.element().on(move |event| {
349            if *event == UiEvent::FocusOut {
350                handler();
351            }
352        });
353        self
354    }
355
356    /// Moves this control ahead in the Tab order. Controls with a tab index
357    /// come first (lowest first); the rest follow in reading order. Prefer
358    /// arranging the tree in the order users should visit it.
359    fn tab_index(mut self, index: u32) -> Self {
360        self.element().tab_index = Some(index);
361        self
362    }
363
364    /// Points `node` at this widget's node, for [`use_size`](crate::use_size)
365    /// and to focus it from code ([`NodeRef::focus`]).
366    fn node_ref(mut self, node: NodeRef) -> Self {
367        self.element().after_build(move |ui, id| node.attach(ui, id));
368        self
369    }
370
371    /// Last-resort handle for tests; prefer finding nodes by role and name.
372    fn test_id(mut self, id: impl Into<String>) -> Self {
373        self.element().test_id = Some(id.into());
374        self
375    }
376}
377
378impl ElementBuilder for Element {
379    fn element(&mut self) -> &mut Element {
380        self
381    }
382}