Skip to main content

mitsuami_widgets/
lib.rs

1//! Built-in widgets. Platform-free: each is an [`Element`] with typed props,
2//! events and accessibility defaults. Backends decide how they look.
3
4use mitsuami_core::{
5    Align, ButtonVariant, Children, Display, Element, ElementBuilder, EventValue, FlexDirection, Justify, Length,
6    NodeId, Point, Prop, ScrollAxes, TextStyle, Track, Ui, UiEvent, View, WidgetKind,
7};
8use mitsuami_reactive::{IntoValue, Signal};
9
10macro_rules! widget {
11    ($t:ty) => {
12        impl ElementBuilder for $t {
13            fn element(&mut self) -> &mut Element {
14                &mut self.0
15            }
16        }
17
18        impl View for $t {
19            fn build(self, ui: &Ui) -> NodeId {
20                self.0.build(ui)
21            }
22        }
23    };
24}
25
26// ------------------------------------------------------------- containers
27
28/// A layout host: flexbox (column by default) or grid.
29pub struct Container(Element);
30widget!(Container);
31
32impl Default for Container {
33    fn default() -> Container {
34        Container::new()
35    }
36}
37
38impl Container {
39    pub fn new() -> Container {
40        Container(Element::new(WidgetKind::Container))
41    }
42
43    pub fn children(mut self, children: impl Children) -> Container {
44        self.0.add_children(children);
45        self
46    }
47
48    pub fn child(self, child: impl View) -> Container {
49        self.children(child)
50    }
51
52    pub fn flex_direction(mut self, direction: impl IntoValue<FlexDirection>) -> Container {
53        self.0.style_prop(direction.into_value(), |s, v| s.flex_direction = v);
54        self
55    }
56
57    /// Gap between rows and columns.
58    pub fn gap(mut self, gap: impl IntoValue<Length>) -> Container {
59        self.0.style_prop(gap.into_value(), |s, v| {
60            s.row_gap = v;
61            s.column_gap = v;
62        });
63        self
64    }
65
66    pub fn row_gap(mut self, gap: impl IntoValue<Length>) -> Container {
67        self.0.style_prop(gap.into_value(), |s, v| s.row_gap = v);
68        self
69    }
70
71    pub fn column_gap(mut self, gap: impl IntoValue<Length>) -> Container {
72        self.0.style_prop(gap.into_value(), |s, v| s.column_gap = v);
73        self
74    }
75
76    /// Cross-axis alignment of children (`align-items`).
77    pub fn align(mut self, align: impl IntoValue<Align>) -> Container {
78        self.0.style_prop(align.into_value(), |s, v| s.align_items = Some(v));
79        self
80    }
81
82    /// Main-axis distribution of children (`justify-content`).
83    pub fn justify(mut self, justify: impl IntoValue<Justify>) -> Container {
84        self.0.style_prop(justify.into_value(), |s, v| s.justify_content = Some(v));
85        self
86    }
87
88    pub fn wrap(self) -> Container {
89        self.style(|s| s.flex_wrap = true)
90    }
91
92    /// Switches to grid layout with these column tracks.
93    pub fn columns<T: Into<Track>>(self, tracks: impl IntoIterator<Item = T>) -> Container {
94        let tracks: Vec<Track> = tracks.into_iter().map(Into::into).collect();
95        self.style(|s| {
96            s.display = Display::Grid;
97            s.grid_template_columns = tracks;
98        })
99    }
100
101    /// Switches to grid layout with these row tracks.
102    pub fn rows<T: Into<Track>>(self, tracks: impl IntoIterator<Item = T>) -> Container {
103        let tracks: Vec<Track> = tracks.into_iter().map(Into::into).collect();
104        self.style(|s| {
105            s.display = Display::Grid;
106            s.grid_template_rows = tracks;
107        })
108    }
109}
110
111/// Vertical flex container.
112pub struct Column;
113
114impl Column {
115    #[allow(clippy::new_ret_no_self)]
116    pub fn new() -> Container {
117        Container::new().flex_direction(FlexDirection::Column)
118    }
119}
120
121/// Horizontal flex container.
122pub struct Row;
123
124impl Row {
125    #[allow(clippy::new_ret_no_self)]
126    pub fn new() -> Container {
127        Container::new().flex_direction(FlexDirection::Row)
128    }
129}
130
131/// Grid container.
132pub struct Grid;
133
134impl Grid {
135    #[allow(clippy::new_ret_no_self)]
136    pub fn new() -> Container {
137        Container::new().style(|s| s.display = Display::Grid)
138    }
139}
140
141/// A native scroll container. Its children go into a content box that
142/// keeps its natural size, so it can be larger than the scroll view.
143///
144/// Give the scroll view a bounded size (a fixed height, or `grow` inside a
145/// sized parent); otherwise it grows with its content and never scrolls.
146/// As in CSS, its natural size is its content's, so in a flex container its
147/// siblings shrink along with it unless they have `.shrink(0.0)`.
148pub struct ScrollView {
149    outer: Element,
150    content: Container,
151}
152
153impl ElementBuilder for ScrollView {
154    fn element(&mut self) -> &mut Element {
155        &mut self.outer
156    }
157}
158
159impl View for ScrollView {
160    fn build(mut self, ui: &Ui) -> NodeId {
161        self.outer.add_children(self.content);
162        self.outer.build(ui)
163    }
164}
165
166impl Default for ScrollView {
167    fn default() -> ScrollView {
168        ScrollView::new()
169    }
170}
171
172impl ScrollView {
173    /// Scrolls vertically.
174    pub fn new() -> ScrollView {
175        ScrollView::with_axes(ScrollAxes::Vertical)
176    }
177
178    pub fn horizontal() -> ScrollView {
179        ScrollView::with_axes(ScrollAxes::Horizontal)
180    }
181
182    pub fn both() -> ScrollView {
183        ScrollView::with_axes(ScrollAxes::Both)
184    }
185
186    fn with_axes(axes: ScrollAxes) -> ScrollView {
187        let mut outer = Element::new(WidgetKind::ScrollView);
188        outer.prop(axes.into_value(), Prop::ScrollAxes);
189        outer.style.scroll_x = axes.horizontal();
190        outer.style.scroll_y = axes.vertical();
191        // The content stretches across the non-scrolling axis and keeps its
192        // natural size along the scrolling ones.
193        outer.style.flex_direction =
194            if axes == ScrollAxes::Horizontal { FlexDirection::Row } else { FlexDirection::Column };
195        // Horizontal content flows in a row; the other kinds in a column.
196        let mut content = Container::new().shrink(0.0);
197        if axes == ScrollAxes::Horizontal {
198            content = content.flex_direction(FlexDirection::Row);
199        }
200        if axes == ScrollAxes::Both {
201            content = content.align_self(Align::Start);
202        }
203        ScrollView { outer, content }
204    }
205
206    pub fn children(mut self, children: impl Children) -> ScrollView {
207        self.content = self.content.children(children);
208        self
209    }
210
211    pub fn child(self, child: impl View) -> ScrollView {
212        self.children(child)
213    }
214
215    /// Called with the new offset whenever the content scrolls.
216    pub fn on_scroll(mut self, handler: impl Fn(Point) + 'static) -> ScrollView {
217        self.outer.on(move |event| {
218            if let UiEvent::Scrolled(offset) = event {
219                handler(*offset);
220            }
221        });
222        self
223    }
224}
225
226// ----------------------------------------------------------------- leaves
227
228/// Static or reactive text.
229pub struct Text(Element);
230widget!(Text);
231
232impl Text {
233    pub fn new(text: impl IntoValue<String>) -> Text {
234        let mut element = Element::new(WidgetKind::Text);
235        element.prop(text.into_value(), Prop::Text);
236        Text(element)
237    }
238
239    pub fn text_style(mut self, style: impl IntoValue<TextStyle>) -> Text {
240        self.0.prop(style.into_value(), Prop::TextStyle);
241        self
242    }
243}
244
245pub struct Button(Element);
246widget!(Button);
247
248impl Button {
249    pub fn new(label: impl IntoValue<String>) -> Button {
250        let mut element = Element::new(WidgetKind::Button);
251        element.prop(label.into_value(), Prop::Label);
252        Button(element)
253    }
254
255    pub fn variant(mut self, variant: impl IntoValue<ButtonVariant>) -> Button {
256        self.0.prop(variant.into_value(), Prop::Variant);
257        self
258    }
259
260    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> Button {
261        self.0.prop(enabled.into_value(), Prop::Enabled);
262        self
263    }
264
265    pub fn on_click(mut self, handler: impl Fn() + 'static) -> Button {
266        self.0.on(move |event| {
267            if *event == UiEvent::Click {
268                handler();
269            }
270        });
271        self
272    }
273}
274
275/// Single-line text entry.
276pub struct TextInput(Element);
277widget!(TextInput);
278
279impl Default for TextInput {
280    fn default() -> TextInput {
281        TextInput::new()
282    }
283}
284
285impl TextInput {
286    pub fn new() -> TextInput {
287        TextInput(Element::new(WidgetKind::TextInput))
288    }
289
290    pub fn value(mut self, value: impl IntoValue<String>) -> TextInput {
291        self.0.prop(value.into_value(), Prop::Value);
292        self
293    }
294
295    /// Two-way binding, Vue's `v-model`.
296    pub fn bind(self, signal: Signal<String>) -> TextInput {
297        self.value(signal).on_input(move |text| signal.set(text))
298    }
299
300    pub fn placeholder(mut self, placeholder: impl IntoValue<String>) -> TextInput {
301        self.0.prop(placeholder.into_value(), Prop::Placeholder);
302        self
303    }
304
305    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> TextInput {
306        self.0.prop(enabled.into_value(), Prop::Enabled);
307        self
308    }
309
310    /// Called on every edit with the new text.
311    pub fn on_input(mut self, handler: impl Fn(String) + 'static) -> TextInput {
312        self.0.on(move |event| {
313            if let UiEvent::Changed(EventValue::Text(text)) = event {
314                handler(text.clone());
315            }
316        });
317        self
318    }
319
320    /// Called when the user confirms (Return / Enter).
321    pub fn on_submit(mut self, handler: impl Fn() + 'static) -> TextInput {
322        self.0.on(move |event| {
323            if *event == UiEvent::Submit {
324                handler();
325            }
326        });
327        self
328    }
329}
330
331macro_rules! toggle {
332    ($t:ident) => {
333        impl $t {
334            pub fn checked(mut self, checked: impl IntoValue<bool>) -> $t {
335                self.0.prop(checked.into_value(), Prop::Checked);
336                self
337            }
338
339            /// Two-way binding, Vue's `v-model`.
340            pub fn bind(self, signal: Signal<bool>) -> $t {
341                self.checked(signal).on_change(move |checked| signal.set(checked))
342            }
343
344            pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> $t {
345                self.0.prop(enabled.into_value(), Prop::Enabled);
346                self
347            }
348
349            pub fn on_change(mut self, handler: impl Fn(bool) + 'static) -> $t {
350                self.0.on(move |event| {
351                    if let UiEvent::Changed(EventValue::Bool(checked)) = event {
352                        handler(*checked);
353                    }
354                });
355                self
356            }
357        }
358    };
359}
360
361pub struct Checkbox(Element);
362widget!(Checkbox);
363toggle!(Checkbox);
364
365impl Checkbox {
366    pub fn new(label: impl IntoValue<String>) -> Checkbox {
367        let mut element = Element::new(WidgetKind::Checkbox);
368        element.prop(label.into_value(), Prop::Label);
369        Checkbox(element)
370    }
371}
372
373/// On/off switch. Most platforms draw no caption; the label is its
374/// accessible name.
375pub struct Switch(Element);
376widget!(Switch);
377toggle!(Switch);
378
379impl Switch {
380    pub fn new(label: impl IntoValue<String>) -> Switch {
381        let mut element = Element::new(WidgetKind::Switch);
382        element.prop(label.into_value(), Prop::Label);
383        Switch(element)
384    }
385}
386
387// ----------------------------------------------------------- view! tags
388//
389// `view!` builds `<Tag …>children</Tag>` as
390// `Tag::__tag().….__children(move || children)`: containers take their
391// children, text and buttons their text.
392
393impl Container {
394    #[doc(hidden)]
395    pub fn __tag() -> Container {
396        Container::new()
397    }
398
399    #[doc(hidden)]
400    pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> Container {
401        self.children(children())
402    }
403}
404
405impl Column {
406    #[doc(hidden)]
407    pub fn __tag() -> Container {
408        Column::new()
409    }
410}
411
412impl Row {
413    #[doc(hidden)]
414    pub fn __tag() -> Container {
415        Row::new()
416    }
417}
418
419impl Grid {
420    #[doc(hidden)]
421    pub fn __tag() -> Container {
422        Grid::new()
423    }
424}
425
426impl ScrollView {
427    #[doc(hidden)]
428    pub fn __tag() -> ScrollView {
429        ScrollView::new()
430    }
431
432    #[doc(hidden)]
433    pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> ScrollView {
434        self.children(children())
435    }
436}
437
438/// Widgets whose one child is their text: `<Text>"Hello"</Text>`.
439macro_rules! text_tag {
440    ($t:ident, $prop:ident) => {
441        impl $t {
442            #[doc(hidden)]
443            pub fn __tag() -> $t {
444                $t(Element::new(WidgetKind::$t))
445            }
446
447            #[doc(hidden)]
448            pub fn __children<S: IntoValue<String>>(mut self, text: impl FnOnce() -> S) -> $t {
449                self.0.prop(text().into_value(), Prop::$prop);
450                self
451            }
452        }
453    };
454}
455
456text_tag!(Text, Text);
457text_tag!(Button, Label);
458text_tag!(Checkbox, Label);
459text_tag!(Switch, Label);
460
461impl TextInput {
462    #[doc(hidden)]
463    pub fn __tag() -> TextInput {
464        TextInput::new()
465    }
466}