Skip to main content

mitsuami_widgets/
tabs.rs

1//! Tab views and their pages.
2
3use std::rc::Rc;
4
5use crate::{Column, Container};
6use mitsuami_core::{
7    Children, Element, ElementBuilder, EventValue, Length, NodeId, Prop, TabsStyle, Ui, UiEvent, View, WidgetKind,
8};
9use mitsuami_reactive::{IntoValue, Signal, Value};
10
11/// Pages, one shown at a time, with a tab for each to pick it: the
12/// platform's own tab view (an NSTabView on macOS, a notebook on GTK, a
13/// selector bar over its pages on Windows, a tab bar on KDE). It's for a
14/// fixed set of views, as in a settings window, not documents the user
15/// opens and closes.
16///
17/// Its pages are [`Tab`]s. `selection` holds the value of the page shown,
18/// and picking a tab sets it; a value no tab has shows the first, as every
19/// platform's tab view shows one. Every page stays built while it's
20/// hidden, so what's in it (a half-typed field, a scroll position) is
21/// still there when it's picked again. The view is as big as its biggest
22/// page, and the platform's tab strip and border are added to it; put
23/// padding on the pages.
24///
25/// ```ignore
26/// let page = signal(Page::General);
27/// Tabs::new(page).children((
28///     Tab::new("General", Page::General).padding(16).children((/* … */)),
29///     Tab::new("Advanced", Page::Advanced).padding(16).children((/* … */)),
30/// ))
31/// ```
32///
33/// In `view!`: `<Tabs selection=page>`, with
34/// `<Tab title="General" value=Page::General>…</Tab>`s as children.
35pub struct Tabs<T: 'static> {
36    element: Element,
37    selection: Signal<T>,
38    tabs: Vec<Tab<T>>,
39}
40
41impl<T: 'static> ElementBuilder for Tabs<T> {
42    fn element(&mut self) -> &mut Element {
43        &mut self.element
44    }
45}
46
47impl<T: PartialEq + Clone + 'static> Tabs<T> {
48    pub fn new(selection: Signal<T>) -> Tabs<T> {
49        Tabs { element: Element::new(WidgetKind::Tabs), selection, tabs: Vec::new() }
50    }
51
52    /// Its pages, in order.
53    pub fn children(mut self, tabs: impl TabsChildren<T>) -> Tabs<T> {
54        tabs.add_to(&mut self.tabs);
55        self
56    }
57
58    pub fn tab(self, tab: Tab<T>) -> Tabs<T> {
59        self.children(tab)
60    }
61
62    /// How it shows its tabs, where the platform has more than one way:
63    /// navigation tabs (the default: libadwaita's view switcher,
64    /// Kirigami's navigation bar) or a tab bar (GTK's notebook, Qt's tab
65    /// bar) on GNOME and KDE. The others show theirs. In `view!`, after
66    /// `selection`.
67    pub fn tabs_style(mut self, style: impl IntoValue<TabsStyle>) -> Tabs<T> {
68        self.element.prop(style.into_value(), Prop::TabsStyle);
69        self
70    }
71}
72
73impl<T: PartialEq + Clone + 'static> View for Tabs<T> {
74    fn build(self, ui: &Ui) -> NodeId {
75        let Tabs { mut element, selection, tabs } = self;
76        let titles: Vec<Value<String>> = tabs.iter().map(|t| t.title.clone()).collect();
77        let values: Rc<Vec<T>> = Rc::new(tabs.iter().map(|t| t.value.clone()).collect());
78        // The titles first: the selection is an index into them.
79        element.prop(Value::Dynamic(Rc::new(move || titles.iter().map(|t| t.get()).collect())), Prop::TabTitles);
80        if tabs.iter().any(|t| t.icon.is_some()) {
81            let icons: Vec<Option<Value<String>>> = tabs.iter().map(|t| t.icon.clone()).collect();
82            element.prop(
83                Value::Dynamic(Rc::new(move || {
84                    icons.iter().map(|i| i.as_ref().map(|i| i.get()).unwrap_or_default()).collect()
85                })),
86                Prop::TabIcons,
87            );
88        }
89        let shown = values.clone();
90        element.prop(
91            Value::Dynamic(Rc::new(move || {
92                let index = selection.with(|value| shown.iter().position(|v| v == value));
93                (!shown.is_empty()).then(|| index.unwrap_or(0))
94            })),
95            Prop::SelectedIndex,
96        );
97        element.on(move |event| {
98            if let UiEvent::Changed(EventValue::Index(index)) = event
99                && let Some(value) = values.get(*index)
100            {
101                selection.set(value.clone());
102            }
103        });
104        for tab in tabs {
105            element.add_children(tab.page);
106        }
107        element.build(ui)
108    }
109}
110
111/// A page of [`Tabs`]: its title, the value picking it gives the tabs'
112/// selection, and what it shows, in a column.
113///
114/// In `view!`, its children are its content:
115/// `<Tab title="General" value=Page::General>…</Tab>`.
116pub struct Tab<T: 'static> {
117    title: Value<String>,
118    icon: Option<Value<String>>,
119    value: T,
120    page: Container,
121}
122
123impl<T: 'static> ElementBuilder for Tab<T> {
124    fn element(&mut self) -> &mut Element {
125        self.page.element()
126    }
127}
128
129impl<T: 'static> Tab<T> {
130    pub fn new(title: impl IntoValue<String>, value: T) -> Tab<T> {
131        Tab { title: title.into_value(), icon: None, value, page: Column::new() }
132    }
133
134    pub fn title(mut self, title: impl IntoValue<String>) -> Tab<T> {
135        self.title = title.into_value();
136        self
137    }
138
139    /// An icon on its tab, named in the platform's own set as for
140    /// [`Icon`](crate::Icon); empty: none. Shown where the platform's tabs
141    /// show one (libadwaita's view switcher, WinUI's selector bar, Qt's tabs);
142    /// AppKit's tab view shows titles only.
143    pub fn icon(mut self, name: impl IntoValue<String>) -> Tab<T> {
144        self.icon = Some(name.into_value());
145        self
146    }
147
148    /// The value picking it gives the tabs' selection.
149    pub fn value<U: 'static>(self, value: U) -> Tab<U> {
150        Tab { title: self.title, icon: self.icon, value, page: self.page }
151    }
152
153    /// What it shows, in a column.
154    pub fn children(mut self, children: impl Children) -> Tab<T> {
155        self.page = self.page.children(children);
156        self
157    }
158
159    pub fn child(self, child: impl View) -> Tab<T> {
160        self.children(child)
161    }
162
163    /// Gap between its children.
164    pub fn gap(mut self, gap: impl IntoValue<Length>) -> Tab<T> {
165        self.page = self.page.gap(gap);
166        self
167    }
168}
169
170/// What [`Tabs`] take as children: [`Tab`]s, and tuples, `Vec`s and
171/// `Option`s of them.
172pub trait TabsChildren<T: 'static> {
173    fn add_to(self, tabs: &mut Vec<Tab<T>>);
174}
175
176impl<T: 'static> TabsChildren<T> for Tab<T> {
177    fn add_to(self, tabs: &mut Vec<Tab<T>>) {
178        tabs.push(self);
179    }
180}
181
182impl<T: 'static, C: TabsChildren<T>> TabsChildren<T> for Vec<C> {
183    fn add_to(self, tabs: &mut Vec<Tab<T>>) {
184        for tab in self {
185            tab.add_to(tabs);
186        }
187    }
188}
189
190impl<T: 'static, C: TabsChildren<T>> TabsChildren<T> for Option<C> {
191    fn add_to(self, tabs: &mut Vec<Tab<T>>) {
192        if let Some(tab) = self {
193            tab.add_to(tabs);
194        }
195    }
196}
197
198impl<T: 'static> TabsChildren<T> for () {
199    fn add_to(self, _: &mut Vec<Tab<T>>) {}
200}
201
202macro_rules! tuple_tabs {
203    ($($name:ident),+) => {
204        impl<T: 'static, $($name: TabsChildren<T>),+> TabsChildren<T> for ($($name,)+) {
205            #[allow(non_snake_case)]
206            fn add_to(self, tabs: &mut Vec<Tab<T>>) {
207                let ($($name,)+) = self;
208                $($name.add_to(tabs);)+
209            }
210        }
211    };
212}
213
214tuple_tabs!(A);
215tuple_tabs!(A, B);
216tuple_tabs!(A, B, C);
217tuple_tabs!(A, B, C, D);
218tuple_tabs!(A, B, C, D, E);
219tuple_tabs!(A, B, C, D, E, F);
220tuple_tabs!(A, B, C, D, E, F, G);
221tuple_tabs!(A, B, C, D, E, F, G, H);
222tuple_tabs!(A, B, C, D, E, F, G, H, I);
223tuple_tabs!(A, B, C, D, E, F, G, H, I, J);
224tuple_tabs!(A, B, C, D, E, F, G, H, I, J, K);
225tuple_tabs!(A, B, C, D, E, F, G, H, I, J, K, L);
226
227impl Tabs<()> {
228    #[doc(hidden)]
229    pub fn __tag() -> TabsWithoutSelection {
230        TabsWithoutSelection
231    }
232}
233
234/// A `<Tabs>` tag before its `selection`.
235#[doc(hidden)]
236pub struct TabsWithoutSelection;
237
238impl TabsWithoutSelection {
239    pub fn selection<T: PartialEq + Clone + 'static>(self, selection: Signal<T>) -> Tabs<T> {
240        Tabs::new(selection)
241    }
242}
243
244impl<T: PartialEq + Clone + 'static> Tabs<T> {
245    #[doc(hidden)]
246    pub fn __children<C: TabsChildren<T>>(self, children: impl FnOnce() -> C) -> Tabs<T> {
247        self.children(children())
248    }
249}
250
251impl Tab<()> {
252    /// Without a value until `value=` gives it one.
253    #[doc(hidden)]
254    pub fn __tag() -> Tab<()> {
255        Tab::new(String::new(), ())
256    }
257}
258
259impl<T: 'static> Tab<T> {
260    #[doc(hidden)]
261    pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> Tab<T> {
262        self.children(children())
263    }
264}