Skip to main content

mitsuami_widgets/
containers.rs

1//! Layout containers: flexbox, grid and titled groups.
2
3use std::rc::Rc;
4
5use std::path::PathBuf;
6
7use mitsuami_core::services::Shortcut;
8use mitsuami_core::{
9    Align, Children, Display, Element, ElementBuilder, FileDrop, FlexDirection, Justify, Length, NodeId, Prop, Track,
10    Tweak, Ui, UiEvent, View, WidgetKind,
11};
12use mitsuami_reactive::{IntoValue, Value};
13
14/// A layout host: flexbox (column by default) or grid.
15pub struct Container(pub(crate) Element);
16widget!(Container);
17
18impl Default for Container {
19    fn default() -> Container {
20        Container::new()
21    }
22}
23
24impl Container {
25    pub fn new() -> Container {
26        Container(Element::new(WidgetKind::Container))
27    }
28
29    pub fn children(mut self, children: impl Children) -> Container {
30        self.0.add_children(children);
31        self
32    }
33
34    pub fn child(self, child: impl View) -> Container {
35        self.children(child)
36    }
37
38    /// Takes the files and folders `drop` says when they're dropped on it
39    /// from the platform's file manager, and gives them to `on_drop`. The
40    /// platform shows it'll copy them while they're over it; `on_drop_hover`
41    /// says when, for the app's own highlight. Dragging isn't reachable
42    /// from the keyboard or assistive technology: offer another way (an
43    /// open dialog) too.
44    pub fn file_drop(mut self, drop: impl IntoValue<FileDrop>) -> Container {
45        let drop = match drop.into_value() {
46            Value::Static(d) => Value::Static(Some(d)),
47            dynamic => Value::Dynamic(Rc::new(move || Some(dynamic.get()))),
48        };
49        self.0.prop(drop, Prop::FileDrop);
50        self
51    }
52
53    /// The files and folders dropped on it that it takes (`file_drop`).
54    pub fn on_drop(mut self, handler: impl Fn(Vec<PathBuf>) + 'static) -> Container {
55        self.0.on(move |event| {
56            if let UiEvent::FilesDropped(paths) = event {
57                handler(paths.clone());
58            }
59        });
60        self
61    }
62
63    /// Whether files it takes are over it (`file_drop`).
64    pub fn on_drop_hover(mut self, handler: impl Fn(bool) + 'static) -> Container {
65        self.0.on(move |event| {
66            if let UiEvent::DropHover(over) = event {
67                handler(*over);
68            }
69        });
70        self
71    }
72
73    /// Called with `true` when the pointer comes over it, or over anything
74    /// inside it, and `false` when it leaves, as the platform tracks it:
75    /// to show a row's buttons while it's hovered. Keyboards and
76    /// assistive technology never hover, so whatever it shows must be
77    /// reachable another way too (a context menu, a selected row's
78    /// toolbar).
79    pub fn on_hover(mut self, handler: impl Fn(bool) + 'static) -> Container {
80        self.0.on_hover(handler);
81        self
82    }
83
84    /// Called when it's double-clicked, or anything inside it that isn't
85    /// a control, as the platform counts a double click: to rename what a
86    /// row shows in place. Keyboards and assistive technology don't
87    /// double-click, so what it does must be reachable another way too (a
88    /// context menu, a button).
89    pub fn on_double_click(mut self, handler: impl Fn() + 'static) -> Container {
90        self.0.on_double_click(handler);
91        self
92    }
93
94    /// Runs `handler` when `key` is pressed while it, or a control
95    /// inside it, has keyboard focus, and the focused control doesn't use
96    /// the key itself: Space for a preview, Delete for Move to Trash.
97    /// A key goes to the nearest node around the focused control that
98    /// takes it. Nothing shows keys taken this way, so give the command a
99    /// menu item or a button too, and pick the keys the platform's own apps
100    /// use (`platform!`).
101    ///
102    /// ```ignore
103    /// Column::new().on_key(Shortcut::primary(Key::Backspace), trash)
104    /// ```
105    pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Container {
106        self.0.on_key(key.into(), handler);
107        self
108    }
109
110    pub fn flex_direction(mut self, direction: impl IntoValue<FlexDirection>) -> Container {
111        self.0.style_prop(direction.into_value(), |s, v| s.flex_direction = v);
112        self
113    }
114
115    /// Gap between rows and columns.
116    pub fn gap(mut self, gap: impl IntoValue<Length>) -> Container {
117        self.0.style_prop(gap.into_value(), |s, v| {
118            s.row_gap = v;
119            s.column_gap = v;
120        });
121        self
122    }
123
124    pub fn row_gap(mut self, gap: impl IntoValue<Length>) -> Container {
125        self.0.style_prop(gap.into_value(), |s, v| s.row_gap = v);
126        self
127    }
128
129    pub fn column_gap(mut self, gap: impl IntoValue<Length>) -> Container {
130        self.0.style_prop(gap.into_value(), |s, v| s.column_gap = v);
131        self
132    }
133
134    /// Cross-axis alignment of children (`align-items`).
135    pub fn align(mut self, align: impl IntoValue<Align>) -> Container {
136        self.0.style_prop(align.into_value(), |s, v| s.align_items = Some(v));
137        self
138    }
139
140    /// Main-axis distribution of children (`justify-content`).
141    pub fn justify(mut self, justify: impl IntoValue<Justify>) -> Container {
142        self.0.style_prop(justify.into_value(), |s, v| s.justify_content = Some(v));
143        self
144    }
145
146    pub fn wrap(self) -> Container {
147        self.style(|s| s.flex_wrap = true)
148    }
149
150    /// Switches to grid layout with these column tracks.
151    pub fn columns<T: Into<Track>>(self, tracks: impl IntoIterator<Item = T>) -> Container {
152        let tracks: Vec<Track> = tracks.into_iter().map(Into::into).collect();
153        self.style(|s| {
154            s.display = Display::Grid;
155            s.grid_template_columns = tracks;
156        })
157    }
158
159    /// Switches to grid layout with these row tracks.
160    pub fn rows<T: Into<Track>>(self, tracks: impl IntoIterator<Item = T>) -> Container {
161        let tracks: Vec<Track> = tracks.into_iter().map(Into::into).collect();
162        self.style(|s| {
163            s.display = Display::Grid;
164            s.grid_template_rows = tracks;
165        })
166    }
167}
168
169/// Vertical flex container. `new()` returns a [`Container`]: chain its
170/// methods, and the style setters of [`ElementBuilder`].
171pub struct Column;
172
173impl Column {
174    #[allow(clippy::new_ret_no_self)]
175    pub fn new() -> Container {
176        Container::new().flex_direction(FlexDirection::Column)
177    }
178}
179
180/// Horizontal flex container. `new()` returns a [`Container`]: chain its
181/// methods, and the style setters of [`ElementBuilder`].
182pub struct Row;
183
184impl Row {
185    #[allow(clippy::new_ret_no_self)]
186    pub fn new() -> Container {
187        Container::new().flex_direction(FlexDirection::Row)
188    }
189}
190
191/// Grid container. `new()` returns a [`Container`]: chain its methods
192/// (`columns`, `rows`), and the style setters of [`ElementBuilder`].
193pub struct Grid;
194
195impl Grid {
196    #[allow(clippy::new_ret_no_self)]
197    pub fn new() -> Container {
198        Container::new().style(|s| s.display = Display::Grid)
199    }
200}
201
202/// A box around related content, as the platform groups it: an `NSBox`
203/// (its heading inside, at the top), libadwaita's card under a heading,
204/// a Fluent card under a heading on Windows, a `QQC2.GroupBox`. The
205/// heading is optional; it names the group to assistive technology.
206///
207/// Its children are laid out as a column's (`gap`, and any style), inside
208/// the platform's border and margins; `padding` adds to those. Put a `Row`
209/// or `Grid` in it for other layouts.
210///
211/// ```ignore
212/// Group::new().title("CD drive").child(
213///     Row::new().gap(Spacing::Md).children((Icon::new(disc), Text::new(title), eject)),
214/// )
215/// ```
216pub struct Group(Element);
217widget!(Group);
218
219impl Default for Group {
220    fn default() -> Group {
221        Group::new()
222    }
223}
224
225impl Group {
226    pub fn new() -> Group {
227        Group(Element::new(WidgetKind::Group)).style(|s| {
228            s.display = Display::Flex;
229            s.flex_direction = FlexDirection::Column;
230        })
231    }
232
233    /// Its heading; empty: none.
234    pub fn title(mut self, title: impl IntoValue<String>) -> Group {
235        self.0.prop(title.into_value(), Prop::Title);
236        self
237    }
238
239    pub fn children(mut self, children: impl Children) -> Group {
240        self.0.add_children(children);
241        self
242    }
243
244    pub fn child(self, child: impl View) -> Group {
245        self.children(child)
246    }
247
248    /// Takes the files and folders `drop` says when they're dropped on it
249    /// from the platform's file manager, and gives them to `on_drop`. The
250    /// platform shows it'll copy them while they're over it; `on_drop_hover`
251    /// says when, for the app's own highlight. Dragging isn't reachable
252    /// from the keyboard or assistive technology: offer another way (an
253    /// open dialog) too.
254    pub fn file_drop(mut self, drop: impl IntoValue<FileDrop>) -> Group {
255        let drop = match drop.into_value() {
256            Value::Static(d) => Value::Static(Some(d)),
257            dynamic => Value::Dynamic(Rc::new(move || Some(dynamic.get()))),
258        };
259        self.0.prop(drop, Prop::FileDrop);
260        self
261    }
262
263    /// The files and folders dropped on it that it takes (`file_drop`).
264    pub fn on_drop(mut self, handler: impl Fn(Vec<PathBuf>) + 'static) -> Group {
265        self.0.on(move |event| {
266            if let UiEvent::FilesDropped(paths) = event {
267                handler(paths.clone());
268            }
269        });
270        self
271    }
272
273    /// Whether files it takes are over it (`file_drop`).
274    pub fn on_drop_hover(mut self, handler: impl Fn(bool) + 'static) -> Group {
275        self.0.on(move |event| {
276            if let UiEvent::DropHover(over) = event {
277                handler(*over);
278            }
279        });
280        self
281    }
282
283    /// Called with `true` when the pointer comes over it, or over anything
284    /// inside it, and `false` when it leaves, as the platform tracks it:
285    /// to show a row's buttons while it's hovered. Keyboards and
286    /// assistive technology never hover, so whatever it shows must be
287    /// reachable another way too (a context menu, a selected row's
288    /// toolbar).
289    pub fn on_hover(mut self, handler: impl Fn(bool) + 'static) -> Group {
290        self.0.on_hover(handler);
291        self
292    }
293
294    /// Called when it's double-clicked, or anything inside it that isn't
295    /// a control, as the platform counts a double click: to rename what a
296    /// row shows in place. Keyboards and assistive technology don't
297    /// double-click, so what it does must be reachable another way too (a
298    /// context menu, a button).
299    pub fn on_double_click(mut self, handler: impl Fn() + 'static) -> Group {
300        self.0.on_double_click(handler);
301        self
302    }
303
304    /// Runs `handler` when `key` is pressed while it, or a control
305    /// inside it, has keyboard focus, and the focused control doesn't use
306    /// the key itself: Space for a preview, Delete for Move to Trash.
307    /// A key goes to the nearest node around the focused control that
308    /// takes it. Nothing shows keys taken this way, so give the command a
309    /// menu item or a button too, and pick the keys the platform's own apps
310    /// use (`platform!`).
311    ///
312    /// ```ignore
313    /// Group::new().on_key(Shortcut::primary(Key::Backspace), trash)
314    /// ```
315    pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Group {
316        self.0.on_key(key.into(), handler);
317        self
318    }
319
320    /// Space between its children.
321    pub fn gap(mut self, gap: impl IntoValue<Length>) -> Group {
322        self.0.style_prop(gap.into_value(), |s, v| {
323            s.row_gap = v;
324            s.column_gap = v;
325        });
326        self
327    }
328
329    /// Raw platform settings, past the semantic ones: see [`Tweak`].
330    pub fn native(mut self, tweak: Tweak<Group>) -> Group {
331        tweak.apply(&mut self.0);
332        self
333    }
334}
335
336impl Group {
337    /// `<Group title="CD drive">…</Group>`
338    #[doc(hidden)]
339    pub fn __tag() -> Group {
340        Group::new()
341    }
342
343    #[doc(hidden)]
344    pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> Group {
345        self.children(children())
346    }
347}
348
349impl Container {
350    #[doc(hidden)]
351    pub fn __tag() -> Container {
352        Container::new()
353    }
354
355    #[doc(hidden)]
356    pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> Container {
357        self.children(children())
358    }
359}
360
361impl Column {
362    #[doc(hidden)]
363    pub fn __tag() -> Container {
364        Column::new()
365    }
366}
367
368impl Row {
369    #[doc(hidden)]
370    pub fn __tag() -> Container {
371        Row::new()
372    }
373}
374
375impl Grid {
376    #[doc(hidden)]
377    pub fn __tag() -> Container {
378        Grid::new()
379    }
380}