Skip to main content

mitsuami_widgets/
sidebar.rs

1//! The window's sidebar, its sections and items.
2
3use std::rc::Rc;
4
5use mitsuami_core::services::{ItemMenus, Menu, MenuEntries};
6use mitsuami_core::{
7    CurrentWindow, Element, EventValue, NodeId, Prop, SidebarItemData, SidebarSectionData, Tweak, Ui, UiEvent, View,
8    WidgetKind,
9};
10use mitsuami_reactive::{IntoValue, Signal, Value, effect, inject, on_cleanup, signal};
11
12/// The sidebar of the window it's declared in: the list down its leading
13/// side that picks what the window shows, as in macOS's System Settings
14/// and GNOME's Settings (a source list on macOS, libadwaita's navigation
15/// split view on GTK, a NavigationView's pane on Windows, a first column
16/// of Kirigami's page row on KDE). Declare it anywhere in the window's
17/// content; it stays while it does.
18///
19/// Its items are [`SidebarItem`]s, in [`SidebarSection`]s or on their own.
20/// `selection` holds the value of the chosen item, and choosing another
21/// sets it; a value no item has chooses none. The window's content is
22/// what's beside the sidebar: show the page for the selection there. The
23/// platform draws the sidebar, sizes it, and collapses it in a narrow
24/// window its own way. The window's size is its content's, and the
25/// sidebar is added to it.
26///
27/// ```ignore
28/// let page = signal(Page::General);
29/// Column::new().children((
30///     Sidebar::new(page).children((
31///         SidebarItem::new("General", Page::General).icon(platform! {
32///             macos => "gearshape",
33///             gtk | kde => "preferences-system-symbolic",
34///             windows => "\u{E713}",
35///         }),
36///         SidebarSection::new("Network").children((
37///             SidebarItem::new("Wi-Fi", Page::WiFi),
38///             SidebarItem::new("Bluetooth", Page::Bluetooth),
39///         )),
40///     )),
41///     Show::new(move || page.get() == Page::General, general),
42/// ))
43/// ```
44///
45/// Items can be what the window is about rather than its pages, as
46/// Mail's mailboxes or a VM manager's machines are: a `subtitle` under
47/// the title, a `context_menu` each, `on_activate` for a double-click or
48/// Enter, and `children_with` for items that come and go.
49///
50/// In `view!`: `<Sidebar selection=page>`, with
51/// `<SidebarItem value=Page::General>"General"</SidebarItem>`s and
52/// `<SidebarSection title="Network">`s as children.
53pub struct Sidebar<T: 'static> {
54    selection: Signal<T>,
55    sections: Vec<SidebarSection<T>>,
56    /// Built again whenever what it reads changes, after `sections`.
57    dynamic: Option<Box<dyn Fn() -> Vec<SidebarSection<T>>>>,
58    shown: Option<Signal<bool>>,
59    activate: Option<Rc<dyn Fn(T)>>,
60    tweak: Option<Tweak<Sidebar<T>>>,
61}
62
63impl<T: PartialEq + Clone + 'static> Sidebar<T> {
64    pub fn new(selection: Signal<T>) -> Sidebar<T> {
65        Sidebar { selection, sections: Vec::new(), dynamic: None, shown: None, activate: None, tweak: None }
66    }
67
68    /// Items and sections built by `entries`, and built again whenever what
69    /// it reads changes (a list of documents, of machines), after any
70    /// `children`. An item whose value is gone stops being chosen, and the
71    /// selection is left as it is.
72    pub fn children_with<E: SidebarEntries<T>>(mut self, entries: impl Fn() -> E + 'static) -> Sidebar<T> {
73        self.dynamic = Some(Box::new(move || {
74            let mut sections = Vec::new();
75            entries().add_to(&mut sections);
76            sections
77        }));
78        self
79    }
80
81    /// Called with an item's value when it's activated, where the
82    /// platform's sidebar has that, as a list's row is: double-clicked or
83    /// Enter pressed on it (AppKit, GTK, Kirigami; WinUI's double-tap).
84    /// The item is chosen first.
85    pub fn on_activate(mut self, activate: impl Fn(T) + 'static) -> Sidebar<T> {
86        self.activate = Some(Rc::new(activate));
87        self
88    }
89
90    /// Shown beside the window's content while `shown` is true, hidden
91    /// otherwise, as the platform shows and hides a sidebar. The user can
92    /// change it too (the platform's toggle, its divider dragged away),
93    /// which sets the signal. Where the platform's sidebar can't be hidden
94    /// in a wide window (GTK), it's the page shown in a narrow one.
95    pub fn shown(mut self, shown: Signal<bool>) -> Sidebar<T> {
96        self.shown = Some(shown);
97        self
98    }
99
100    /// Raw platform settings: see [`Tweak`]. How wide a sidebar is, say,
101    /// is each platform's own.
102    pub fn native(mut self, tweak: Tweak<Sidebar<T>>) -> Sidebar<T> {
103        self.tweak = Some(tweak);
104        self
105    }
106
107    /// Items and sections, in order. Items outside a section next to each
108    /// other are one section without a heading.
109    pub fn children(mut self, children: impl SidebarEntries<T>) -> Sidebar<T> {
110        children.add_to(&mut self.sections);
111        self
112    }
113
114    pub fn item(self, item: SidebarItem<T>) -> Sidebar<T> {
115        self.children(item)
116    }
117
118    pub fn section(self, section: SidebarSection<T>) -> Sidebar<T> {
119        self.children(section)
120    }
121}
122
123impl<T: PartialEq + Clone + 'static> View for Sidebar<T> {
124    /// A placeholder in the tree, which takes no room; the sidebar is the
125    /// window's.
126    fn build(self, ui: &Ui) -> NodeId {
127        let placeholder = ui.create(WidgetKind::Fragment, Vec::new());
128        let Some(CurrentWindow(window)) = inject::<CurrentWindow>() else {
129            panic!("a Sidebar goes in a window's content");
130        };
131        let Sidebar { selection, sections, dynamic, shown: showing, activate, tweak } = self;
132        // The items' values in order, which an index from the platform
133        // names: they change when `children_with` builds new items.
134        let values: Signal<Vec<T>> = signal(Vec::new());
135        let menus = ItemMenus::new();
136        let mut element = Element::new(WidgetKind::Sidebar);
137        if let Some(tweak) = tweak {
138            tweak.apply(&mut element);
139        }
140        let sidebar = element.build(ui);
141        ui.append_child(window, sidebar);
142        // The items first: the selection is an index into them.
143        let (shown, item_menus) = (ui.clone(), menus.clone());
144        effect(move || {
145            let built = dynamic.as_ref().map(|entries| entries()).unwrap_or_default();
146            let all: Vec<&SidebarSection<T>> = sections.iter().chain(&built).collect();
147            let items = all.iter().flat_map(|s| &s.items);
148            let mut entries =
149                item_menus.collect(&items.clone().map(|i| i.menu.as_ref()).collect::<Vec<_>>()).into_iter();
150            let data = all
151                .iter()
152                .map(|section| SidebarSectionData {
153                    title: section.title.as_ref().map(|t| t.get()),
154                    items: section
155                        .items
156                        .iter()
157                        .map(|item| SidebarItemData {
158                            title: item.title.get(),
159                            icon: item.icon.clone(),
160                            subtitle: item.subtitle.as_ref().map(|s| s.get()),
161                            menu: entries.next().unwrap_or_default(),
162                        })
163                        .collect(),
164                })
165                .collect();
166            let now: Vec<T> = items.map(|i| i.value.clone()).collect();
167            if values.with_untracked(|v| *v != now) {
168                values.set(now);
169            }
170            shown.set_prop(sidebar, Prop::Sections(data));
171        });
172        let chosen = ui.clone();
173        effect(move || {
174            let index = selection.with(|value| values.with(|v| v.iter().position(|v| v == value)));
175            chosen.set_prop(sidebar, Prop::SelectedIndex(index));
176        });
177        let value_at = move |index: usize| values.with_untracked(|v| v.get(index).cloned());
178        ui.on_event(sidebar, move |event| match event {
179            UiEvent::Changed(EventValue::Index(index)) => {
180                if let Some(value) = value_at(*index) {
181                    selection.set(value);
182                }
183            }
184            UiEvent::SidebarItemActivated(index) => {
185                if let (Some(activate), Some(value)) = (&activate, value_at(*index)) {
186                    activate(value);
187                }
188            }
189            UiEvent::ContextMenuItem(_) => menus.handle(event),
190            _ => {}
191        });
192        if let Some(showing) = showing {
193            let shown = ui.clone();
194            effect(move || shown.set_prop(sidebar, Prop::SidebarShown(showing.get())));
195            ui.on_event(sidebar, move |event| {
196                if let UiEvent::SidebarShownChanged(on) = event {
197                    showing.set(*on);
198                }
199            });
200        }
201        let ui = ui.clone();
202        on_cleanup(move || ui.destroy(sidebar));
203        placeholder
204    }
205}
206
207/// A group of a [`Sidebar`]'s items, under a heading.
208pub struct SidebarSection<T: 'static> {
209    title: Option<Value<String>>,
210    items: Vec<SidebarItem<T>>,
211    /// Made for items outside any section, so the next ones join it.
212    loose: bool,
213}
214
215impl<T: 'static> SidebarSection<T> {
216    pub fn new(title: impl IntoValue<String>) -> SidebarSection<T> {
217        SidebarSection { title: Some(title.into_value()), items: Vec::new(), loose: false }
218    }
219
220    /// Without a heading.
221    pub fn untitled() -> SidebarSection<T> {
222        SidebarSection { title: None, items: Vec::new(), loose: false }
223    }
224
225    pub fn title(mut self, title: impl IntoValue<String>) -> SidebarSection<T> {
226        self.title = Some(title.into_value());
227        self
228    }
229
230    pub fn item(mut self, item: SidebarItem<T>) -> SidebarSection<T> {
231        self.items.push(item);
232        self
233    }
234
235    /// Its items, in order.
236    pub fn children(mut self, items: impl SidebarItems<T>) -> SidebarSection<T> {
237        items.add_to(&mut self.items);
238        self
239    }
240}
241
242/// An item of a [`Sidebar`]: a title, the value choosing it gives the
243/// sidebar's selection, and optionally an icon, a subtitle and a context
244/// menu.
245///
246/// In `view!`, its text is its title:
247/// `<SidebarItem value=Page::General icon="gearshape">"General"</SidebarItem>`.
248pub struct SidebarItem<T: 'static> {
249    title: Value<String>,
250    icon: Option<String>,
251    subtitle: Option<Value<String>>,
252    menu: Option<Menu>,
253    value: T,
254}
255
256impl<T: 'static> SidebarItem<T> {
257    pub fn new(title: impl IntoValue<String>, value: T) -> SidebarItem<T> {
258        SidebarItem { title: title.into_value(), icon: None, subtitle: None, menu: None, value }
259    }
260
261    /// The value choosing it gives the sidebar's selection.
262    pub fn value<U: 'static>(self, value: U) -> SidebarItem<U> {
263        SidebarItem { title: self.title, icon: self.icon, subtitle: self.subtitle, menu: self.menu, value }
264    }
265
266    /// A second line under the title, in the platform's secondary style
267    /// (a machine's system and state, a mailbox's account). The row is as
268    /// tall as the two lines need.
269    pub fn subtitle(mut self, subtitle: impl IntoValue<String>) -> SidebarItem<T> {
270        self.subtitle = Some(subtitle.into_value());
271        self
272    }
273
274    /// Its context menu, which the platform shows its own way on the item
275    /// (a right-click, a long press, the menu key). Takes what
276    /// [`ElementBuilder::context_menu`](mitsuami_core::ElementBuilder::context_menu)
277    /// takes, with the same reactive titles and states.
278    pub fn context_menu(mut self, entries: impl MenuEntries) -> SidebarItem<T> {
279        self.menu = Some(Menu::new(String::new()).children(entries));
280        self
281    }
282
283    /// The name of its icon in the platform's own set, picked with
284    /// `platform!`: an SF Symbol on macOS (`"gearshape"`), a symbolic icon
285    /// of the theme on GTK and KDE (`"preferences-system-symbolic"`), a
286    /// Segoe Fluent Icons glyph on Windows (`"\u{E713}"`). Empty: none.
287    /// A platform that can't find it shows none.
288    pub fn icon(mut self, name: impl Into<String>) -> SidebarItem<T> {
289        self.icon = Some(name.into()).filter(|n| !n.is_empty());
290        self
291    }
292}
293
294/// What a [`Sidebar`] takes as children: [`SidebarItem`]s,
295/// [`SidebarSection`]s, and tuples, `Vec`s and `Option`s of them.
296pub trait SidebarEntries<T: 'static> {
297    fn add_to(self, sections: &mut Vec<SidebarSection<T>>);
298}
299
300impl<T: 'static> SidebarEntries<T> for SidebarItem<T> {
301    fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
302        match sections.last_mut().filter(|s| s.loose) {
303            Some(section) => section.items.push(self),
304            None => sections.push(SidebarSection { title: None, items: vec![self], loose: true }),
305        }
306    }
307}
308
309impl<T: 'static> SidebarEntries<T> for SidebarSection<T> {
310    fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
311        sections.push(self);
312    }
313}
314
315impl<T: 'static, E: SidebarEntries<T>> SidebarEntries<T> for Vec<E> {
316    fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
317        for entry in self {
318            entry.add_to(sections);
319        }
320    }
321}
322
323impl<T: 'static, E: SidebarEntries<T>> SidebarEntries<T> for Option<E> {
324    fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
325        if let Some(entry) = self {
326            entry.add_to(sections);
327        }
328    }
329}
330
331impl<T: 'static> SidebarEntries<T> for () {
332    fn add_to(self, _: &mut Vec<SidebarSection<T>>) {}
333}
334
335/// What a [`SidebarSection`] takes as children: [`SidebarItem`]s, and
336/// tuples, `Vec`s and `Option`s of them.
337pub trait SidebarItems<T: 'static> {
338    fn add_to(self, items: &mut Vec<SidebarItem<T>>);
339}
340
341impl<T: 'static> SidebarItems<T> for SidebarItem<T> {
342    fn add_to(self, items: &mut Vec<SidebarItem<T>>) {
343        items.push(self);
344    }
345}
346
347impl<T: 'static, I: SidebarItems<T>> SidebarItems<T> for Vec<I> {
348    fn add_to(self, items: &mut Vec<SidebarItem<T>>) {
349        for item in self {
350            item.add_to(items);
351        }
352    }
353}
354
355impl<T: 'static, I: SidebarItems<T>> SidebarItems<T> for Option<I> {
356    fn add_to(self, items: &mut Vec<SidebarItem<T>>) {
357        if let Some(item) = self {
358            item.add_to(items);
359        }
360    }
361}
362
363impl<T: 'static> SidebarItems<T> for () {
364    fn add_to(self, _: &mut Vec<SidebarItem<T>>) {}
365}
366
367macro_rules! tuple_sidebar {
368    ($($name:ident),+) => {
369        impl<T: 'static, $($name: SidebarEntries<T>),+> SidebarEntries<T> for ($($name,)+) {
370            #[allow(non_snake_case)]
371            fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
372                let ($($name,)+) = self;
373                $($name.add_to(sections);)+
374            }
375        }
376
377        impl<T: 'static, $($name: SidebarItems<T>),+> SidebarItems<T> for ($($name,)+) {
378            #[allow(non_snake_case)]
379            fn add_to(self, items: &mut Vec<SidebarItem<T>>) {
380                let ($($name,)+) = self;
381                $($name.add_to(items);)+
382            }
383        }
384    };
385}
386
387tuple_sidebar!(A);
388tuple_sidebar!(A, B);
389tuple_sidebar!(A, B, C);
390tuple_sidebar!(A, B, C, D);
391tuple_sidebar!(A, B, C, D, E);
392tuple_sidebar!(A, B, C, D, E, F);
393tuple_sidebar!(A, B, C, D, E, F, G);
394tuple_sidebar!(A, B, C, D, E, F, G, H);
395tuple_sidebar!(A, B, C, D, E, F, G, H, I);
396tuple_sidebar!(A, B, C, D, E, F, G, H, I, J);
397tuple_sidebar!(A, B, C, D, E, F, G, H, I, J, K);
398tuple_sidebar!(A, B, C, D, E, F, G, H, I, J, K, L);
399
400impl Sidebar<()> {
401    #[doc(hidden)]
402    pub fn __tag() -> SidebarWithoutSelection {
403        SidebarWithoutSelection
404    }
405}
406
407/// A `<Sidebar>` tag before its `selection`.
408#[doc(hidden)]
409pub struct SidebarWithoutSelection;
410
411impl SidebarWithoutSelection {
412    pub fn selection<T: PartialEq + Clone + 'static>(self, selection: Signal<T>) -> Sidebar<T> {
413        Sidebar::new(selection)
414    }
415}
416
417impl<T: PartialEq + Clone + 'static> Sidebar<T> {
418    #[doc(hidden)]
419    pub fn __children<E: SidebarEntries<T>>(self, children: impl FnOnce() -> E) -> Sidebar<T> {
420        self.children(children())
421    }
422}
423
424impl<T: 'static> SidebarSection<T> {
425    #[doc(hidden)]
426    pub fn __tag() -> SidebarSection<T> {
427        SidebarSection::untitled()
428    }
429
430    #[doc(hidden)]
431    pub fn __children<I: SidebarItems<T>>(self, items: impl FnOnce() -> I) -> SidebarSection<T> {
432        self.children(items())
433    }
434}
435
436impl SidebarItem<()> {
437    /// Without a value until `value=` gives it one.
438    #[doc(hidden)]
439    pub fn __tag() -> SidebarItem<()> {
440        SidebarItem::new(String::new(), ())
441    }
442}
443
444impl<T: 'static> SidebarItem<T> {
445    /// `<SidebarItem value=…>"General"</SidebarItem>`: its text is its title.
446    #[doc(hidden)]
447    pub fn __children<S: IntoValue<String>>(mut self, title: impl FnOnce() -> S) -> SidebarItem<T> {
448        self.title = title().into_value();
449        self
450    }
451}