Skip to main content

mitsuami_widgets/
document_tabs.rs

1//! Document tabs: a strip of tabs without pages.
2
3use std::cell::Cell;
4use std::rc::Rc;
5
6use mitsuami_core::{
7    DocumentTabsStyle, Element, ElementBuilder, EventValue, NodeId, Prop, Tweak, Ui, UiEvent, View, WidgetKind,
8};
9use mitsuami_reactive::{IntoValue, Signal, Value, effect, signal};
10
11/// Tabs for the documents the app has open, as a browser's or a
12/// terminal's: the platform's own (in the title bar on macOS, as Safari's
13/// and Xcode's, and on Windows; libadwaita's tab bar on GNOME, a tab bar
14/// on KDE). The tabs have no pages: the app shows the chosen document itself,
15/// in one place, as a terminal draws its sessions on one surface.
16///
17/// Its tabs are [`DocumentTab`]s, usually built from the app's list of
18/// documents with `children_with`. `selection` holds the value of the
19/// chosen tab, and choosing another sets it. One is always chosen while
20/// there are tabs, as on every platform: a value no tab has chooses the
21/// first, and when the chosen tab goes, the one now in its place (the
22/// last, if it was last); either sets `selection`.
23///
24/// The user closes tabs, moves them and asks for new ones where the app
25/// lets them: `on_close`, `on_reorder` and `on_new_tab` each turn the
26/// platform's own way on (close buttons, dragging, a new-tab button). A
27/// close only asks: the tab stays until the app takes its document away.
28///
29/// ```ignore
30/// let docs = signal(vec![Doc::new(1, "notes.txt")]);
31/// let current = signal(1);
32/// DocumentTabs::new(current)
33///     .children_with(move || docs.with(|d| d.iter().map(|d| DocumentTab::new(d.name.clone(), d.id)).collect::<Vec<_>>()))
34///     .on_close(move |id| docs.update(|d| d.retain(|d| d.id != id)))
35///     .on_new_tab(move || /* open one, and choose it */)
36/// ```
37///
38/// Where the platform puts its tabs in the window's chrome (macOS,
39/// Windows), they take no room where they're declared; see
40/// [`tabs_style`](Self::tabs_style).
41///
42/// In `view!`: `<DocumentTabs selection=current @close=… @new_tab=…>`,
43/// with `<DocumentTab value=1>"notes.txt"</DocumentTab>`s as children.
44pub struct DocumentTabs<T: 'static> {
45    element: Element,
46    selection: Signal<T>,
47    tabs: Vec<DocumentTab<T>>,
48    /// Built again whenever what it reads changes, after `tabs`.
49    dynamic: Option<Box<dyn Fn() -> Vec<DocumentTab<T>>>>,
50    close: Option<Rc<dyn Fn(T)>>,
51    reorder: Option<Rc<dyn Fn(T, usize)>>,
52    new_tab: Option<Rc<dyn Fn()>>,
53}
54
55impl<T: 'static> ElementBuilder for DocumentTabs<T> {
56    fn element(&mut self) -> &mut Element {
57        &mut self.element
58    }
59}
60
61impl<T: PartialEq + Clone + 'static> DocumentTabs<T> {
62    pub fn new(selection: Signal<T>) -> DocumentTabs<T> {
63        DocumentTabs {
64            element: Element::new(WidgetKind::DocumentTabs),
65            selection,
66            tabs: Vec::new(),
67            dynamic: None,
68            close: None,
69            reorder: None,
70            new_tab: None,
71        }
72    }
73
74    /// Its tabs, in order.
75    pub fn children(mut self, tabs: impl DocumentTabsChildren<T>) -> DocumentTabs<T> {
76        tabs.add_to(&mut self.tabs);
77        self
78    }
79
80    pub fn tab(self, tab: DocumentTab<T>) -> DocumentTabs<T> {
81        self.children(tab)
82    }
83
84    /// Tabs built by `tabs`, and built again whenever what it reads changes
85    /// (the app's documents), after any `children`.
86    pub fn children_with<E: DocumentTabsChildren<T>>(mut self, tabs: impl Fn() -> E + 'static) -> DocumentTabs<T> {
87        self.dynamic = Some(Box::new(move || {
88            let mut built = Vec::new();
89            tabs().add_to(&mut built);
90            built
91        }));
92        self
93    }
94
95    /// Called with a tab's value when the user asks to close it: its close
96    /// button, a middle click, the platform's own way. Gives the tabs
97    /// close buttons. The tab stays until the app takes it away, so it can
98    /// ask about unsaved changes first.
99    pub fn on_close(mut self, close: impl Fn(T) + 'static) -> DocumentTabs<T> {
100        self.close = Some(Rc::new(close));
101        self
102    }
103
104    /// Called with a tab's value and its new index when the user moves it
105    /// (drags it, or moves it from the keyboard where the platform can).
106    /// Lets the user move tabs. The tab already shows there: move the
107    /// document in the app's list too.
108    pub fn on_reorder(mut self, reorder: impl Fn(T, usize) + 'static) -> DocumentTabs<T> {
109        self.reorder = Some(Rc::new(reorder));
110        self
111    }
112
113    /// Called when the user asks for a new tab with the platform's new-tab
114    /// button, which this gives the tabs: open a document, and choose it.
115    pub fn on_new_tab(mut self, new_tab: impl Fn() + 'static) -> DocumentTabs<T> {
116        self.new_tab = Some(Rc::new(new_tab));
117        self
118    }
119
120    /// Where it shows its tabs: the platform's own place (the default), a
121    /// strip where it's declared on every platform, the window's own (the
122    /// title bar on macOS and Windows; GNOME and KDE have none, and show a
123    /// strip), or the title's own row (Safari's compact tabs on macOS, the
124    /// header bar's title on GNOME; KDE shows a strip). In `view!`, after
125    /// `selection`.
126    pub fn tabs_style(mut self, style: impl IntoValue<DocumentTabsStyle>) -> DocumentTabs<T> {
127        self.element.prop(style.into_value(), Prop::DocumentTabsStyle);
128        self
129    }
130
131    /// Raw platform settings: see [`Tweak`]. Pinned tabs, tabs dragged out
132    /// to a window of their own, a tab's width: each platform's own.
133    pub fn native(mut self, tweak: Tweak<DocumentTabs<T>>) -> DocumentTabs<T> {
134        tweak.apply(&mut self.element);
135        self
136    }
137}
138
139impl<T: PartialEq + Clone + 'static> View for DocumentTabs<T> {
140    fn build(self, ui: &Ui) -> NodeId {
141        let DocumentTabs { mut element, selection, tabs, dynamic, close, reorder, new_tab } = self;
142        if close.is_some() {
143            element.prop(Value::Static(true), Prop::TabsClosable);
144        }
145        if reorder.is_some() {
146            element.prop(Value::Static(true), Prop::TabsReorderable);
147        }
148        if new_tab.is_some() {
149            element.prop(Value::Static(true), Prop::NewTabButton);
150        }
151        // The tabs' values in order, which an index from the platform
152        // names: they change when `children_with` builds new tabs, and when
153        // the user moves one.
154        let values: Signal<Vec<T>> = signal(Vec::new());
155        let value_at = move |index: usize| values.with_untracked(|v| v.get(index).cloned());
156        element.on(move |event| match event {
157            UiEvent::Changed(EventValue::Index(index)) => {
158                if let Some(value) = value_at(*index) {
159                    selection.set(value);
160                }
161            }
162            UiEvent::TabCloseRequested(index) => {
163                if let (Some(close), Some(value)) = (&close, value_at(*index)) {
164                    close(value);
165                }
166            }
167            // The platform shows it moved, and the core has its titles so:
168            // the values follow, before the app hears.
169            UiEvent::TabMoved { from, to } => {
170                let Some(value) = value_at(*from) else { return };
171                let mut now = values.get_untracked();
172                if *to >= now.len() {
173                    return;
174                }
175                let moved = now.remove(*from);
176                now.insert(*to, moved);
177                values.set(now);
178                if let Some(reorder) = &reorder {
179                    reorder(value, *to);
180                }
181            }
182            UiEvent::NewTabRequested => {
183                if let Some(new_tab) = &new_tab {
184                    new_tab();
185                }
186            }
187            _ => {}
188        });
189        let strip = element.build(ui);
190        // The titles first: the selection is an index into them.
191        let titled = ui.clone();
192        effect(move || {
193            let built = dynamic.as_ref().map(|tabs| tabs()).unwrap_or_default();
194            let all: Vec<&DocumentTab<T>> = tabs.iter().chain(&built).collect();
195            let now: Vec<T> = all.iter().map(|t| t.value.clone()).collect();
196            if values.with_untracked(|v| *v != now) {
197                values.set(now);
198            }
199            titled.set_prop(strip, Prop::TabTitles(all.iter().map(|t| t.title.get()).collect()));
200        });
201        // Where the chosen tab was, for the one that takes its place.
202        let last = Rc::new(Cell::new(0));
203        let chosen = ui.clone();
204        effect(move || {
205            let index = values.with(|v| {
206                if v.is_empty() {
207                    return None;
208                }
209                Some(selection.with(|value| v.iter().position(|v| v == value)).unwrap_or_else(|| {
210                    let index = last.get().min(v.len() - 1);
211                    selection.set(v[index].clone());
212                    index
213                }))
214            });
215            if let Some(index) = index {
216                last.set(index);
217            }
218            chosen.set_prop(strip, Prop::SelectedIndex(index));
219        });
220        strip
221    }
222}
223
224/// A tab of [`DocumentTabs`]: its title, and the value choosing it gives
225/// the tabs' selection.
226///
227/// In `view!`, its text is its title:
228/// `<DocumentTab value=1>"notes.txt"</DocumentTab>`.
229pub struct DocumentTab<T: 'static> {
230    title: Value<String>,
231    value: T,
232}
233
234impl<T: 'static> DocumentTab<T> {
235    pub fn new(title: impl IntoValue<String>, value: T) -> DocumentTab<T> {
236        DocumentTab { title: title.into_value(), value }
237    }
238
239    pub fn title(mut self, title: impl IntoValue<String>) -> DocumentTab<T> {
240        self.title = title.into_value();
241        self
242    }
243
244    /// The value choosing it gives the tabs' selection.
245    pub fn value<U: 'static>(self, value: U) -> DocumentTab<U> {
246        DocumentTab { title: self.title, value }
247    }
248}
249
250/// What [`DocumentTabs`] take as children: [`DocumentTab`]s, and tuples,
251/// `Vec`s and `Option`s of them.
252pub trait DocumentTabsChildren<T: 'static> {
253    fn add_to(self, tabs: &mut Vec<DocumentTab<T>>);
254}
255
256impl<T: 'static> DocumentTabsChildren<T> for DocumentTab<T> {
257    fn add_to(self, tabs: &mut Vec<DocumentTab<T>>) {
258        tabs.push(self);
259    }
260}
261
262impl<T: 'static, C: DocumentTabsChildren<T>> DocumentTabsChildren<T> for Vec<C> {
263    fn add_to(self, tabs: &mut Vec<DocumentTab<T>>) {
264        for tab in self {
265            tab.add_to(tabs);
266        }
267    }
268}
269
270impl<T: 'static, C: DocumentTabsChildren<T>> DocumentTabsChildren<T> for Option<C> {
271    fn add_to(self, tabs: &mut Vec<DocumentTab<T>>) {
272        if let Some(tab) = self {
273            tab.add_to(tabs);
274        }
275    }
276}
277
278impl<T: 'static> DocumentTabsChildren<T> for () {
279    fn add_to(self, _: &mut Vec<DocumentTab<T>>) {}
280}
281
282macro_rules! tuple_document_tabs {
283    ($($name:ident),+) => {
284        impl<T: 'static, $($name: DocumentTabsChildren<T>),+> DocumentTabsChildren<T> for ($($name,)+) {
285            #[allow(non_snake_case)]
286            fn add_to(self, tabs: &mut Vec<DocumentTab<T>>) {
287                let ($($name,)+) = self;
288                $($name.add_to(tabs);)+
289            }
290        }
291    };
292}
293
294tuple_document_tabs!(A);
295tuple_document_tabs!(A, B);
296tuple_document_tabs!(A, B, C);
297tuple_document_tabs!(A, B, C, D);
298tuple_document_tabs!(A, B, C, D, E);
299tuple_document_tabs!(A, B, C, D, E, F);
300tuple_document_tabs!(A, B, C, D, E, F, G);
301tuple_document_tabs!(A, B, C, D, E, F, G, H);
302
303impl DocumentTabs<()> {
304    #[doc(hidden)]
305    pub fn __tag() -> DocumentTabsWithoutSelection {
306        DocumentTabsWithoutSelection
307    }
308}
309
310/// A `<DocumentTabs>` tag before its `selection`.
311#[doc(hidden)]
312pub struct DocumentTabsWithoutSelection;
313
314impl DocumentTabsWithoutSelection {
315    pub fn selection<T: PartialEq + Clone + 'static>(self, selection: Signal<T>) -> DocumentTabs<T> {
316        DocumentTabs::new(selection)
317    }
318}
319
320impl<T: PartialEq + Clone + 'static> DocumentTabs<T> {
321    #[doc(hidden)]
322    pub fn __children<C: DocumentTabsChildren<T>>(self, tabs: impl FnOnce() -> C) -> DocumentTabs<T> {
323        self.children(tabs())
324    }
325}
326
327impl DocumentTab<()> {
328    /// Without a value until `value=` gives it one.
329    #[doc(hidden)]
330    pub fn __tag() -> DocumentTab<()> {
331        DocumentTab::new(String::new(), ())
332    }
333}
334
335impl<T: 'static> DocumentTab<T> {
336    /// `<DocumentTab value=…>"notes.txt"</DocumentTab>`: its text is its
337    /// title.
338    #[doc(hidden)]
339    pub fn __children<S: IntoValue<String>>(mut self, title: impl FnOnce() -> S) -> DocumentTab<T> {
340        self.title = title().into_value();
341        self
342    }
343}