Skip to main content

mitsuami_widgets/
toolbar.rs

1//! The window's toolbar.
2
3use mitsuami_core::{AnyView, Children, CurrentWindow, NodeId, Ui, View, WidgetKind};
4use mitsuami_reactive::{inject, on_cleanup};
5
6/// Items for the toolbar of the window it's declared in: the bar across
7/// the top that shows the window's title (the unified toolbar on macOS,
8/// GTK's header bar, a command bar on WinUI, the page toolbar on KDE).
9/// Declare it anywhere in the window's content; its items stay while it
10/// does.
11///
12/// Each child is one item, at the bar's trailing end, in order. The
13/// platform places them, spaces them and draws the bar; each item is as
14/// big as its content. An item with nothing in it (a `Show` that shows
15/// nothing) is hidden.
16///
17/// ```ignore
18/// Column::new().children((
19///     Toolbar::new().children((
20///         Show::new(move || busy.get(), || Row::new().children((Spinner::new("Downloading"), "Downloading"))),
21///         Text::new(move || status.get()),
22///     )),
23///     machine_list(),
24/// ))
25/// ```
26#[derive(Default)]
27pub struct Toolbar {
28    items: Vec<AnyView>,
29}
30
31impl Toolbar {
32    pub fn new() -> Toolbar {
33        Toolbar::default()
34    }
35
36    /// The items, one per child.
37    pub fn children(mut self, children: impl Children) -> Toolbar {
38        children.into_views(&mut self.items);
39        self
40    }
41
42    pub fn child(self, child: impl View) -> Toolbar {
43        self.children(child)
44    }
45}
46
47impl View for Toolbar {
48    /// A placeholder in the tree, which takes no room; the items are the
49    /// window's.
50    fn build(self, ui: &Ui) -> NodeId {
51        let placeholder = ui.create(WidgetKind::Fragment, Vec::new());
52        let Some(CurrentWindow(window)) = inject::<CurrentWindow>() else {
53            panic!("a Toolbar goes in a window's content");
54        };
55        let items: Vec<NodeId> = self
56            .items
57            .into_iter()
58            .map(|view| {
59                let item = ui.create(WidgetKind::ToolbarItem, Vec::new());
60                let content = view.build(ui);
61                ui.append_child(item, content);
62                ui.append_child(window, item);
63                item
64            })
65            .collect();
66        let ui = ui.clone();
67        on_cleanup(move || {
68            for item in items {
69                ui.destroy(item);
70            }
71        });
72        placeholder
73    }
74}
75
76impl Toolbar {
77    #[doc(hidden)]
78    pub fn __tag() -> Toolbar {
79        Toolbar::new()
80    }
81
82    #[doc(hidden)]
83    pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> Toolbar {
84        self.children(children())
85    }
86}