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, HeaderEdge, Justify, Length, NodeId,
10    Prop, Track, 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    /// Makes it its window's header, which stays while what's under it
111    /// scrolls: put it at the top of the window's content, over the scroll
112    /// view it stays above. On macOS it goes in the title bar, in the
113    /// bar's glass, and the scroll view runs up under it, as Safari's and
114    /// Mail's bars do; elsewhere it stays at the content's top as it is.
115    ///
116    /// ```ignore
117    /// Column::new().children((
118    ///     Row::new().header(true).children((Text::new("Library"), add_button())),
119    ///     ScrollView::new(rows()).grow(1.0),
120    /// ))
121    /// ```
122    pub fn header(mut self, header: impl IntoValue<bool>) -> Container {
123        self.0.prop(header.into_value(), Prop::Header);
124        self
125    }
126
127    /// How its window's header meets what scrolls under it (`header`):
128    /// on macOS 26.1 and later, a soft fade or a hard line. Without, the
129    /// platform's own; elsewhere it has no such edge.
130    pub fn header_edge(mut self, edge: impl IntoValue<HeaderEdge>) -> Container {
131        self.0.prop(edge.into_value(), Prop::HeaderEdge);
132        self
133    }
134
135    pub fn flex_direction(mut self, direction: impl IntoValue<FlexDirection>) -> Container {
136        self.0.style_prop(direction.into_value(), |s, v| s.flex_direction = v);
137        self
138    }
139
140    /// Gap between rows and columns.
141    pub fn gap(mut self, gap: impl IntoValue<Length>) -> Container {
142        self.0.style_prop(gap.into_value(), |s, v| {
143            s.row_gap = v;
144            s.column_gap = v;
145        });
146        self
147    }
148
149    pub fn row_gap(mut self, gap: impl IntoValue<Length>) -> Container {
150        self.0.style_prop(gap.into_value(), |s, v| s.row_gap = v);
151        self
152    }
153
154    pub fn column_gap(mut self, gap: impl IntoValue<Length>) -> Container {
155        self.0.style_prop(gap.into_value(), |s, v| s.column_gap = v);
156        self
157    }
158
159    /// Cross-axis alignment of children (`align-items`).
160    pub fn align(mut self, align: impl IntoValue<Align>) -> Container {
161        self.0.style_prop(align.into_value(), |s, v| s.align_items = Some(v));
162        self
163    }
164
165    /// Main-axis distribution of children (`justify-content`).
166    pub fn justify(mut self, justify: impl IntoValue<Justify>) -> Container {
167        self.0.style_prop(justify.into_value(), |s, v| s.justify_content = Some(v));
168        self
169    }
170
171    pub fn wrap(self) -> Container {
172        self.style(|s| s.flex_wrap = true)
173    }
174
175    /// Switches to grid layout with these column tracks.
176    pub fn columns<T: Into<Track>>(self, tracks: impl IntoIterator<Item = T>) -> Container {
177        let tracks: Vec<Track> = tracks.into_iter().map(Into::into).collect();
178        self.style(|s| {
179            s.display = Display::Grid;
180            s.grid_template_columns = tracks;
181        })
182    }
183
184    /// Switches to grid layout with these row tracks.
185    pub fn rows<T: Into<Track>>(self, tracks: impl IntoIterator<Item = T>) -> Container {
186        let tracks: Vec<Track> = tracks.into_iter().map(Into::into).collect();
187        self.style(|s| {
188            s.display = Display::Grid;
189            s.grid_template_rows = tracks;
190        })
191    }
192}
193
194/// Vertical flex container. `new()` returns a [`Container`]: chain its
195/// methods, and the style setters of [`ElementBuilder`].
196pub struct Column;
197
198impl Column {
199    #[allow(clippy::new_ret_no_self)]
200    pub fn new() -> Container {
201        Container::new().flex_direction(FlexDirection::Column)
202    }
203}
204
205/// Horizontal flex container. `new()` returns a [`Container`]: chain its
206/// methods, and the style setters of [`ElementBuilder`].
207pub struct Row;
208
209impl Row {
210    #[allow(clippy::new_ret_no_self)]
211    pub fn new() -> Container {
212        Container::new().flex_direction(FlexDirection::Row)
213    }
214}
215
216/// Grid container. `new()` returns a [`Container`]: chain its methods
217/// (`columns`, `rows`), and the style setters of [`ElementBuilder`].
218pub struct Grid;
219
220impl Grid {
221    #[allow(clippy::new_ret_no_self)]
222    pub fn new() -> Container {
223        Container::new().style(|s| s.display = Display::Grid)
224    }
225}
226
227/// A box around related content, as the platform groups it: an `NSBox`
228/// (its heading inside, at the top), libadwaita's card under a heading,
229/// a Fluent card under a heading on Windows, a `QQC2.GroupBox`. The
230/// heading is optional; it names the group to assistive technology.
231///
232/// Its children are laid out as a column's (`gap`, and any style), inside
233/// the platform's border and margins; `padding` adds to those. Put a `Row`
234/// or `Grid` in it for other layouts.
235///
236/// ```ignore
237/// Group::new().title("CD drive").child(
238///     Row::new().gap(Spacing::Md).children((Icon::new(disc), Text::new(title), eject)),
239/// )
240/// ```
241pub struct Group(Element);
242widget!(Group);
243
244impl Default for Group {
245    fn default() -> Group {
246        Group::new()
247    }
248}
249
250impl Group {
251    pub fn new() -> Group {
252        Group(Element::new(WidgetKind::Group)).style(|s| {
253            s.display = Display::Flex;
254            s.flex_direction = FlexDirection::Column;
255        })
256    }
257
258    /// Its heading; empty: none.
259    pub fn title(mut self, title: impl IntoValue<String>) -> Group {
260        self.0.prop(title.into_value(), Prop::Title);
261        self
262    }
263
264    pub fn children(mut self, children: impl Children) -> Group {
265        self.0.add_children(children);
266        self
267    }
268
269    pub fn child(self, child: impl View) -> Group {
270        self.children(child)
271    }
272
273    /// Takes the files and folders `drop` says when they're dropped on it
274    /// from the platform's file manager, and gives them to `on_drop`. The
275    /// platform shows it'll copy them while they're over it; `on_drop_hover`
276    /// says when, for the app's own highlight. Dragging isn't reachable
277    /// from the keyboard or assistive technology: offer another way (an
278    /// open dialog) too.
279    pub fn file_drop(mut self, drop: impl IntoValue<FileDrop>) -> Group {
280        let drop = match drop.into_value() {
281            Value::Static(d) => Value::Static(Some(d)),
282            dynamic => Value::Dynamic(Rc::new(move || Some(dynamic.get()))),
283        };
284        self.0.prop(drop, Prop::FileDrop);
285        self
286    }
287
288    /// The files and folders dropped on it that it takes (`file_drop`).
289    pub fn on_drop(mut self, handler: impl Fn(Vec<PathBuf>) + 'static) -> Group {
290        self.0.on(move |event| {
291            if let UiEvent::FilesDropped(paths) = event {
292                handler(paths.clone());
293            }
294        });
295        self
296    }
297
298    /// Whether files it takes are over it (`file_drop`).
299    pub fn on_drop_hover(mut self, handler: impl Fn(bool) + 'static) -> Group {
300        self.0.on(move |event| {
301            if let UiEvent::DropHover(over) = event {
302                handler(*over);
303            }
304        });
305        self
306    }
307
308    /// Called with `true` when the pointer comes over it, or over anything
309    /// inside it, and `false` when it leaves, as the platform tracks it:
310    /// to show a row's buttons while it's hovered. Keyboards and
311    /// assistive technology never hover, so whatever it shows must be
312    /// reachable another way too (a context menu, a selected row's
313    /// toolbar).
314    pub fn on_hover(mut self, handler: impl Fn(bool) + 'static) -> Group {
315        self.0.on_hover(handler);
316        self
317    }
318
319    /// Called when it's double-clicked, or anything inside it that isn't
320    /// a control, as the platform counts a double click: to rename what a
321    /// row shows in place. Keyboards and assistive technology don't
322    /// double-click, so what it does must be reachable another way too (a
323    /// context menu, a button).
324    pub fn on_double_click(mut self, handler: impl Fn() + 'static) -> Group {
325        self.0.on_double_click(handler);
326        self
327    }
328
329    /// Runs `handler` when `key` is pressed while it, or a control
330    /// inside it, has keyboard focus, and the focused control doesn't use
331    /// the key itself: Space for a preview, Delete for Move to Trash.
332    /// A key goes to the nearest node around the focused control that
333    /// takes it. Nothing shows keys taken this way, so give the command a
334    /// menu item or a button too, and pick the keys the platform's own apps
335    /// use (`platform!`).
336    ///
337    /// ```ignore
338    /// Group::new().on_key(Shortcut::primary(Key::Backspace), trash)
339    /// ```
340    pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Group {
341        self.0.on_key(key.into(), handler);
342        self
343    }
344
345    /// Space between its children.
346    pub fn gap(mut self, gap: impl IntoValue<Length>) -> Group {
347        self.0.style_prop(gap.into_value(), |s, v| {
348            s.row_gap = v;
349            s.column_gap = v;
350        });
351        self
352    }
353
354    /// Raw platform settings, past the semantic ones: see [`Tweak`].
355    pub fn native(mut self, tweak: Tweak<Group>) -> Group {
356        tweak.apply(&mut self.0);
357        self
358    }
359}
360
361impl Group {
362    /// `<Group title="CD drive">…</Group>`
363    #[doc(hidden)]
364    pub fn __tag() -> Group {
365        Group::new()
366    }
367
368    #[doc(hidden)]
369    pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> Group {
370        self.children(children())
371    }
372}
373
374impl Container {
375    #[doc(hidden)]
376    pub fn __tag() -> Container {
377        Container::new()
378    }
379
380    #[doc(hidden)]
381    pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> Container {
382        self.children(children())
383    }
384}
385
386impl Column {
387    #[doc(hidden)]
388    pub fn __tag() -> Container {
389        Column::new()
390    }
391}
392
393impl Row {
394    #[doc(hidden)]
395    pub fn __tag() -> Container {
396        Row::new()
397    }
398}
399
400impl Grid {
401    #[doc(hidden)]
402    pub fn __tag() -> Container {
403        Grid::new()
404    }
405}