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::{
6    CurrentWindow, Element, EventValue, NodeId, Prop, SidebarItemData, SidebarSectionData, Tweak, Ui, UiEvent, View,
7    WidgetKind,
8};
9use mitsuami_reactive::{IntoValue, Signal, Value, effect, inject, on_cleanup};
10
11/// The sidebar of the window it's declared in: the list down its leading
12/// side that picks what the window shows, as in macOS's System Settings
13/// and GNOME's Settings (a source list on macOS, libadwaita's navigation
14/// split view on GTK, a NavigationView's pane on Windows, a first column
15/// of Kirigami's page row on KDE). Declare it anywhere in the window's
16/// content; it stays while it does.
17///
18/// Its items are [`SidebarItem`]s, in [`SidebarSection`]s or on their own.
19/// `selection` holds the value of the chosen item, and choosing another
20/// sets it; a value no item has chooses none. The window's content is
21/// what's beside the sidebar: show the page for the selection there. The
22/// platform draws the sidebar, sizes it, and collapses it in a narrow
23/// window its own way. The window's size is its content's, and the
24/// sidebar is added to it.
25///
26/// ```ignore
27/// let page = signal(Page::General);
28/// Column::new().children((
29///     Sidebar::new(page).children((
30///         SidebarItem::new("General", Page::General).icon(platform! {
31///             macos => "gearshape",
32///             gtk | kde => "preferences-system-symbolic",
33///             windows => "\u{E713}",
34///         }),
35///         SidebarSection::new("Network").children((
36///             SidebarItem::new("Wi-Fi", Page::WiFi),
37///             SidebarItem::new("Bluetooth", Page::Bluetooth),
38///         )),
39///     )),
40///     Show::new(move || page.get() == Page::General, general),
41/// ))
42/// ```
43///
44/// In `view!`: `<Sidebar selection=page>`, with
45/// `<SidebarItem value=Page::General>"General"</SidebarItem>`s and
46/// `<SidebarSection title="Network">`s as children.
47pub struct Sidebar<T: 'static> {
48    selection: Signal<T>,
49    sections: Vec<SidebarSection<T>>,
50    shown: Option<Signal<bool>>,
51    tweak: Option<Tweak<Sidebar<T>>>,
52}
53
54impl<T: PartialEq + Clone + 'static> Sidebar<T> {
55    pub fn new(selection: Signal<T>) -> Sidebar<T> {
56        Sidebar { selection, sections: Vec::new(), shown: None, tweak: None }
57    }
58
59    /// Shown beside the window's content while `shown` is true, hidden
60    /// otherwise, as the platform shows and hides a sidebar. The user can
61    /// change it too (the platform's toggle, its divider dragged away),
62    /// which sets the signal. Where the platform's sidebar can't be hidden
63    /// in a wide window (GTK), it's the page shown in a narrow one.
64    pub fn shown(mut self, shown: Signal<bool>) -> Sidebar<T> {
65        self.shown = Some(shown);
66        self
67    }
68
69    /// Raw platform settings: see [`Tweak`]. How wide a sidebar is, say,
70    /// is each platform's own.
71    pub fn native(mut self, tweak: Tweak<Sidebar<T>>) -> Sidebar<T> {
72        self.tweak = Some(tweak);
73        self
74    }
75
76    /// Items and sections, in order. Items outside a section next to each
77    /// other are one section without a heading.
78    pub fn children(mut self, children: impl SidebarEntries<T>) -> Sidebar<T> {
79        children.add_to(&mut self.sections);
80        self
81    }
82
83    pub fn item(self, item: SidebarItem<T>) -> Sidebar<T> {
84        self.children(item)
85    }
86
87    pub fn section(self, section: SidebarSection<T>) -> Sidebar<T> {
88        self.children(section)
89    }
90}
91
92impl<T: PartialEq + Clone + 'static> View for Sidebar<T> {
93    /// A placeholder in the tree, which takes no room; the sidebar is the
94    /// window's.
95    fn build(self, ui: &Ui) -> NodeId {
96        let placeholder = ui.create(WidgetKind::Fragment, Vec::new());
97        let Some(CurrentWindow(window)) = inject::<CurrentWindow>() else {
98            panic!("a Sidebar goes in a window's content");
99        };
100        let Sidebar { selection, sections, shown: showing, tweak } = self;
101        let values: Rc<Vec<T>> =
102            Rc::new(sections.iter().flat_map(|s| s.items.iter().map(|i| i.value.clone())).collect());
103        let mut element = Element::new(WidgetKind::Sidebar);
104        if let Some(tweak) = tweak {
105            tweak.apply(&mut element);
106        }
107        let sidebar = element.build(ui);
108        ui.append_child(window, sidebar);
109        // The items first: the selection is an index into them.
110        let shown = ui.clone();
111        effect(move || {
112            let data = sections
113                .iter()
114                .map(|section| SidebarSectionData {
115                    title: section.title.as_ref().map(|t| t.get()),
116                    items: section
117                        .items
118                        .iter()
119                        .map(|item| SidebarItemData { title: item.title.get(), icon: item.icon.clone() })
120                        .collect(),
121                })
122                .collect();
123            shown.set_prop(sidebar, Prop::Sections(data));
124        });
125        let (chosen, index_of) = (ui.clone(), values.clone());
126        effect(move || {
127            let index = selection.with(|value| index_of.iter().position(|v| v == value));
128            chosen.set_prop(sidebar, Prop::SelectedIndex(index));
129        });
130        ui.on_event(sidebar, move |event| {
131            if let UiEvent::Changed(EventValue::Index(index)) = event
132                && let Some(value) = values.get(*index)
133            {
134                selection.set(value.clone());
135            }
136        });
137        if let Some(showing) = showing {
138            let shown = ui.clone();
139            effect(move || shown.set_prop(sidebar, Prop::SidebarShown(showing.get())));
140            ui.on_event(sidebar, move |event| {
141                if let UiEvent::SidebarShownChanged(on) = event {
142                    showing.set(*on);
143                }
144            });
145        }
146        let ui = ui.clone();
147        on_cleanup(move || ui.destroy(sidebar));
148        placeholder
149    }
150}
151
152/// A group of a [`Sidebar`]'s items, under a heading.
153pub struct SidebarSection<T: 'static> {
154    title: Option<Value<String>>,
155    items: Vec<SidebarItem<T>>,
156    /// Made for items outside any section, so the next ones join it.
157    loose: bool,
158}
159
160impl<T: 'static> SidebarSection<T> {
161    pub fn new(title: impl IntoValue<String>) -> SidebarSection<T> {
162        SidebarSection { title: Some(title.into_value()), items: Vec::new(), loose: false }
163    }
164
165    /// Without a heading.
166    pub fn untitled() -> SidebarSection<T> {
167        SidebarSection { title: None, items: Vec::new(), loose: false }
168    }
169
170    pub fn title(mut self, title: impl IntoValue<String>) -> SidebarSection<T> {
171        self.title = Some(title.into_value());
172        self
173    }
174
175    pub fn item(mut self, item: SidebarItem<T>) -> SidebarSection<T> {
176        self.items.push(item);
177        self
178    }
179
180    /// Its items, in order.
181    pub fn children(mut self, items: impl SidebarItems<T>) -> SidebarSection<T> {
182        items.add_to(&mut self.items);
183        self
184    }
185}
186
187/// An item of a [`Sidebar`]: a title, the value choosing it gives the
188/// sidebar's selection, and optionally an icon.
189///
190/// In `view!`, its text is its title:
191/// `<SidebarItem value=Page::General icon="gearshape">"General"</SidebarItem>`.
192pub struct SidebarItem<T: 'static> {
193    title: Value<String>,
194    icon: Option<String>,
195    value: T,
196}
197
198impl<T: 'static> SidebarItem<T> {
199    pub fn new(title: impl IntoValue<String>, value: T) -> SidebarItem<T> {
200        SidebarItem { title: title.into_value(), icon: None, value }
201    }
202
203    /// The value choosing it gives the sidebar's selection.
204    pub fn value<U: 'static>(self, value: U) -> SidebarItem<U> {
205        SidebarItem { title: self.title, icon: self.icon, value }
206    }
207
208    /// The name of its icon in the platform's own set, picked with
209    /// `platform!`: an SF Symbol on macOS (`"gearshape"`), a symbolic icon
210    /// of the theme on GTK and KDE (`"preferences-system-symbolic"`), a
211    /// Segoe Fluent Icons glyph on Windows (`"\u{E713}"`). Empty: none.
212    /// A platform that can't find it shows none.
213    pub fn icon(mut self, name: impl Into<String>) -> SidebarItem<T> {
214        self.icon = Some(name.into()).filter(|n| !n.is_empty());
215        self
216    }
217}
218
219/// What a [`Sidebar`] takes as children: [`SidebarItem`]s,
220/// [`SidebarSection`]s, and tuples, `Vec`s and `Option`s of them.
221pub trait SidebarEntries<T: 'static> {
222    fn add_to(self, sections: &mut Vec<SidebarSection<T>>);
223}
224
225impl<T: 'static> SidebarEntries<T> for SidebarItem<T> {
226    fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
227        match sections.last_mut().filter(|s| s.loose) {
228            Some(section) => section.items.push(self),
229            None => sections.push(SidebarSection { title: None, items: vec![self], loose: true }),
230        }
231    }
232}
233
234impl<T: 'static> SidebarEntries<T> for SidebarSection<T> {
235    fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
236        sections.push(self);
237    }
238}
239
240impl<T: 'static, E: SidebarEntries<T>> SidebarEntries<T> for Vec<E> {
241    fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
242        for entry in self {
243            entry.add_to(sections);
244        }
245    }
246}
247
248impl<T: 'static, E: SidebarEntries<T>> SidebarEntries<T> for Option<E> {
249    fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
250        if let Some(entry) = self {
251            entry.add_to(sections);
252        }
253    }
254}
255
256impl<T: 'static> SidebarEntries<T> for () {
257    fn add_to(self, _: &mut Vec<SidebarSection<T>>) {}
258}
259
260/// What a [`SidebarSection`] takes as children: [`SidebarItem`]s, and
261/// tuples, `Vec`s and `Option`s of them.
262pub trait SidebarItems<T: 'static> {
263    fn add_to(self, items: &mut Vec<SidebarItem<T>>);
264}
265
266impl<T: 'static> SidebarItems<T> for SidebarItem<T> {
267    fn add_to(self, items: &mut Vec<SidebarItem<T>>) {
268        items.push(self);
269    }
270}
271
272impl<T: 'static, I: SidebarItems<T>> SidebarItems<T> for Vec<I> {
273    fn add_to(self, items: &mut Vec<SidebarItem<T>>) {
274        for item in self {
275            item.add_to(items);
276        }
277    }
278}
279
280impl<T: 'static, I: SidebarItems<T>> SidebarItems<T> for Option<I> {
281    fn add_to(self, items: &mut Vec<SidebarItem<T>>) {
282        if let Some(item) = self {
283            item.add_to(items);
284        }
285    }
286}
287
288impl<T: 'static> SidebarItems<T> for () {
289    fn add_to(self, _: &mut Vec<SidebarItem<T>>) {}
290}
291
292macro_rules! tuple_sidebar {
293    ($($name:ident),+) => {
294        impl<T: 'static, $($name: SidebarEntries<T>),+> SidebarEntries<T> for ($($name,)+) {
295            #[allow(non_snake_case)]
296            fn add_to(self, sections: &mut Vec<SidebarSection<T>>) {
297                let ($($name,)+) = self;
298                $($name.add_to(sections);)+
299            }
300        }
301
302        impl<T: 'static, $($name: SidebarItems<T>),+> SidebarItems<T> for ($($name,)+) {
303            #[allow(non_snake_case)]
304            fn add_to(self, items: &mut Vec<SidebarItem<T>>) {
305                let ($($name,)+) = self;
306                $($name.add_to(items);)+
307            }
308        }
309    };
310}
311
312tuple_sidebar!(A);
313tuple_sidebar!(A, B);
314tuple_sidebar!(A, B, C);
315tuple_sidebar!(A, B, C, D);
316tuple_sidebar!(A, B, C, D, E);
317tuple_sidebar!(A, B, C, D, E, F);
318tuple_sidebar!(A, B, C, D, E, F, G);
319tuple_sidebar!(A, B, C, D, E, F, G, H);
320tuple_sidebar!(A, B, C, D, E, F, G, H, I);
321tuple_sidebar!(A, B, C, D, E, F, G, H, I, J);
322tuple_sidebar!(A, B, C, D, E, F, G, H, I, J, K);
323tuple_sidebar!(A, B, C, D, E, F, G, H, I, J, K, L);
324
325impl Sidebar<()> {
326    #[doc(hidden)]
327    pub fn __tag() -> SidebarWithoutSelection {
328        SidebarWithoutSelection
329    }
330}
331
332/// A `<Sidebar>` tag before its `selection`.
333#[doc(hidden)]
334pub struct SidebarWithoutSelection;
335
336impl SidebarWithoutSelection {
337    pub fn selection<T: PartialEq + Clone + 'static>(self, selection: Signal<T>) -> Sidebar<T> {
338        Sidebar::new(selection)
339    }
340}
341
342impl<T: PartialEq + Clone + 'static> Sidebar<T> {
343    #[doc(hidden)]
344    pub fn __children<E: SidebarEntries<T>>(self, children: impl FnOnce() -> E) -> Sidebar<T> {
345        self.children(children())
346    }
347}
348
349impl<T: 'static> SidebarSection<T> {
350    #[doc(hidden)]
351    pub fn __tag() -> SidebarSection<T> {
352        SidebarSection::untitled()
353    }
354
355    #[doc(hidden)]
356    pub fn __children<I: SidebarItems<T>>(self, items: impl FnOnce() -> I) -> SidebarSection<T> {
357        self.children(items())
358    }
359}
360
361impl SidebarItem<()> {
362    /// Without a value until `value=` gives it one.
363    #[doc(hidden)]
364    pub fn __tag() -> SidebarItem<()> {
365        SidebarItem::new(String::new(), ())
366    }
367}
368
369impl<T: 'static> SidebarItem<T> {
370    /// `<SidebarItem value=…>"General"</SidebarItem>`: its text is its title.
371    #[doc(hidden)]
372    pub fn __children<S: IntoValue<String>>(mut self, title: impl FnOnce() -> S) -> SidebarItem<T> {
373        self.title = title().into_value();
374        self
375    }
376}