Skip to main content

mitsuami_core/
tree.rs

1//! `Tree`: the platform's tree control, rows that nest, with rows built by
2//! the core.
3//!
4//! A tree is a [`List`](crate::List) whose rows have children, shown while
5//! the row is open: its data, selection, activation and scrolling work the
6//! same way, and the platform realises its rows the same way. The core
7//! sends the rows that show, each with its place in the tree
8//! (`Prop::TreeRows`); the platform draws the disclosures, indents the
9//! levels and reports the user opening and closing rows (`RowExpanded`),
10//! which the open set follows.
11
12use std::cell::{Cell, RefCell};
13use std::collections::{HashMap, HashSet};
14use std::hash::Hash;
15use std::path::PathBuf;
16use std::rc::Rc;
17use std::time::Duration;
18
19use mitsuami_reactive::{IntoValue, Signal, Value, signal};
20
21use crate::element::{Element, ElementBuilder};
22use crate::list::{FileFn, KeyFn, ListHandle, Mount, MoveFn, RowParts, RowRender, Shape, TreeParts, build_rows};
23use crate::services::Shortcut;
24use crate::tweak::Tweak;
25use crate::ui::Ui;
26use crate::units::Length;
27use crate::view::{AnyView, View};
28use crate::widget::{ListStyle, NodeId, Prop, RowDrop, RowMoves, SelectionMode, WidgetKind};
29
30/// An item's children: `None` for a row that never opens, `Some` for one
31/// that does, empty or not.
32type ChildrenFn<T> = Rc<dyn Fn(&T) -> Option<Vec<T>>>;
33
34/// Whether an item's children are being read.
35type LoadingFn<T> = Rc<dyn Fn(&T) -> bool>;
36
37/// A virtualised tree of rows, shown by the platform's own tree control,
38/// which draws the disclosures and indents the levels.
39///
40/// ```ignore
41/// Tree::new(move || folders.get(), |f| f.path.clone(), |f| f.children(), |f| FolderRow(f))
42///     .expanded(open)                // Signal<Vec<K>>: the open rows' keys
43///     .selected(selected)            // Signal<Vec<K>>: the selected keys
44///     .on_activate(|path| open(path))
45///     .grow(1.0)
46/// ```
47///
48/// `children` is `None` for a row that never opens (a file) and `Some` for
49/// one that does (a folder, empty or not yet read). It's called for each
50/// row that shows, so keep it cheap; signals it reads are tracked, so
51/// children that load later show when they come. Rows are keyed as a
52/// `List`'s, and everything a `List` has works the same way.
53///
54/// Rows are read by screen readers (and found by tests) as tree items
55/// named by their text, with their level and whether they're open.
56///
57/// The type's defaults make `Tree` alone name the widget, for
58/// [`Tweak<Tree>`](Tweak).
59pub struct Tree<T: 'static = (), K: 'static = (), R = RowRender<T>> {
60    element: Element,
61    roots: Value<Vec<T>>,
62    key: KeyFn<T, K>,
63    children: ChildrenFn<T>,
64    render: R,
65    expanded: Option<Signal<Vec<K>>>,
66    mode: Option<Value<SelectionMode>>,
67    style: Option<ListStyle>,
68    selected: Option<Signal<Vec<K>>>,
69    on_activate: Option<Rc<dyn Fn(K)>>,
70    estimate: Option<f32>,
71    handle: Option<ListHandle<K>>,
72    files: Option<FileFn<T>>,
73    moves: Option<(RowMoves, MoveFn<K>)>,
74    loading: Option<LoadingFn<T>>,
75}
76
77impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> Tree<T, K> {
78    pub fn new<V: View>(
79        roots: impl IntoValue<Vec<T>>,
80        key: impl Fn(&T) -> K + 'static,
81        children: impl Fn(&T) -> Option<Vec<T>> + 'static,
82        render: impl Fn(T) -> V + 'static,
83    ) -> Tree<T, K> {
84        Tree::with_element(
85            Element::new(WidgetKind::Tree),
86            roots.into_value(),
87            Rc::new(key),
88            Rc::new(children),
89            RowRender::new(move |item| AnyView::new(render(item))),
90        )
91    }
92}
93
94impl<T: 'static, K: 'static, R> Tree<T, K, R> {
95    fn with_element(
96        element: Element,
97        roots: Value<Vec<T>>,
98        key: KeyFn<T, K>,
99        children: ChildrenFn<T>,
100        render: R,
101    ) -> Tree<T, K, R> {
102        Tree {
103            element,
104            roots,
105            key,
106            children,
107            render,
108            expanded: None,
109            mode: None,
110            style: None,
111            selected: None,
112            on_activate: None,
113            estimate: None,
114            handle: None,
115            files: None,
116            moves: None,
117            loading: None,
118        }
119    }
120
121    /// Rows can be dragged within the tree, with the platform's own row
122    /// drag (the selection, when a selected row is dragged), and dropped
123    /// where `moves` says, as a `List`'s [`on_move`](crate::List::on_move):
124    /// onto a row (into a folder), before one (at its place among its
125    /// folder's rows), or at the end (after the top rows). A folder can't
126    /// be dropped inside itself. `handler` gets the rows, in the tree's
127    /// order, and where; the tree shows nothing moved until the app moves
128    /// its data. Offer another way too (a Move command): dragging isn't
129    /// reachable from the keyboard or assistive technology.
130    pub fn on_move(mut self, moves: RowMoves, handler: impl Fn(Vec<K>, RowDrop<K>) + 'static) -> Self {
131        self.moves = Some((moves, Rc::new(handler)));
132        self
133    }
134
135    /// Which rows' children are being read: a folder whose files take a
136    /// moment to come, as on a network share. Once `loading` has said so
137    /// for half a second, the platform's spinner shows where the row's
138    /// disclosure is, as Finder shows one in place of a folder's triangle;
139    /// a folder read quicker opens without one flashing. Signals it reads
140    /// are tracked, as `children`'s are. The tree doesn't read children
141    /// itself: the app says when they're read, and `children` gives them.
142    pub fn loading(mut self, loading: impl Fn(&T) -> bool + 'static) -> Self {
143        self.loading = Some(Rc::new(loading));
144        self
145    }
146
147    /// Binds which rows are open, as their keys, both ways: the user opens
148    /// and closes rows (the disclosure, the platform's keys, assistive
149    /// technology), and the app can too. A key stays while its row is in a
150    /// closed folder, so reopening the folder shows the row open again.
151    /// Without it, the tree keeps its own, every row closed at first.
152    pub fn expanded(mut self, expanded: Signal<Vec<K>>) -> Self {
153        self.expanded = Some(expanded);
154        self
155    }
156
157    /// Rows can be dragged out of the app, carrying the files their items
158    /// stand for, as a `List`'s [`drag_files`](crate::List::drag_files).
159    pub fn drag_files(mut self, file: impl Fn(&T) -> Option<PathBuf> + 'static) -> Self {
160        self.files = Some(Rc::new(file));
161        self
162    }
163
164    /// Binds the selection, as the selected rows' keys, both ways. Trees
165    /// with a selection bound select one row at a time unless
166    /// [`selection_mode`](Tree::selection_mode) says otherwise. Closing a
167    /// folder deselects its rows.
168    pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
169        self.selected = Some(selected);
170        self
171    }
172
173    /// How many rows can be selected, as a `List`'s
174    /// [`selection_mode`](crate::List::selection_mode).
175    pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
176        self.mode = Some(mode.into_value());
177        self
178    }
179
180    /// How the tree sits in its surroundings, as a `List`'s
181    /// [`list_style`](crate::List::list_style).
182    pub fn list_style(mut self, style: ListStyle) -> Self {
183        self.style = Some(style);
184        self
185    }
186
187    /// Called with a row's key when it's activated: double-clicked, or Enter
188    /// pressed on it. It opens nothing: what a folder's activation does is
189    /// the app's.
190    pub fn on_activate(mut self, handler: impl Fn(K) + 'static) -> Self {
191        self.on_activate = Some(Rc::new(handler));
192        self
193    }
194
195    /// Runs `handler` when `key` is pressed while the tree, or a control
196    /// inside it, has keyboard focus, and the focused control doesn't use
197    /// the key itself (the arrows, the keys that open and close rows, and
198    /// what else the platform's tree takes), as a `List`'s
199    /// [`on_key`](crate::List::on_key).
200    pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Self {
201        self.element.on_key(key.into(), handler);
202        self
203    }
204
205    /// How high rows are likely to be, for platforms that size rows before
206    /// they're shown (AppKit). By default, the rows shown so far tell.
207    pub fn estimated_row_height(mut self, height: impl Into<Length>) -> Self {
208        self.estimate = match height.into() {
209            Length::Px(px) => Some(px),
210            _ => None,
211        };
212        self
213    }
214
215    /// Connects a [`ListHandle`], to scroll the tree from code. A row in a
216    /// closed folder doesn't show, so it's scrolled to once its folders are
217    /// open ([`expanded`](Tree::expanded)).
218    pub fn handle(mut self, handle: ListHandle<K>) -> Self {
219        self.handle = Some(handle);
220        self
221    }
222
223    /// Raw platform settings: see [`Tweak`]. They run on the tree view, not
224    /// the scroll view around it.
225    pub fn native(mut self, tweak: Tweak<Tree>) -> Self {
226        tweak.apply(&mut self.element);
227        self
228    }
229}
230
231impl<T: 'static, K: 'static, R> ElementBuilder for Tree<T, K, R> {
232    fn element(&mut self) -> &mut Element {
233        &mut self.element
234    }
235}
236
237/// How long a row loads before its spinner shows: a folder read quicker
238/// opens without one flashing, as Nautilus waits before showing its own.
239const SPINNER_DELAY: Duration = Duration::from_millis(500);
240
241/// The app's `loading`, held back for `SPINNER_DELAY`: when each row that
242/// shows began loading, on the `Ui`'s clock, and a signal a timer bumps
243/// when a row's time is up. A row that stops loading, or isn't walked (in
244/// a closed folder), starts again.
245struct Delayed<T: 'static, K: 'static> {
246    ui: Ui,
247    key: KeyFn<T, K>,
248    loading: LoadingFn<T>,
249    since: RefCell<HashMap<K, (Duration, u64)>>,
250    walk: Cell<u64>,
251    due: Signal<u64>,
252}
253
254impl<T, K: Eq + Hash + Clone> Delayed<T, K> {
255    /// Whether the item's spinner shows. It's asked of each row walked.
256    fn shows(&self, item: &T) -> bool {
257        if !(self.loading)(item) {
258            return false;
259        }
260        // Walked again when a timer is due.
261        self.due.get();
262        let now = self.ui.executor().now();
263        let mut since = self.since.borrow_mut();
264        let walk = self.walk.get();
265        let entry = since.entry((self.key)(item)).or_insert_with(|| {
266            let (ui, due) = (self.ui.clone(), self.due);
267            self.ui.spawn_local(async move {
268                ui.sleep(SPINNER_DELAY).await;
269                if due.is_alive() {
270                    due.update(|n| *n += 1);
271                }
272            });
273            (now, walk)
274        });
275        entry.1 = walk;
276        now.saturating_sub(entry.0) >= SPINNER_DELAY
277    }
278
279    /// Walks the rows, forgetting those not loading in it.
280    fn walk<R>(&self, f: impl FnOnce() -> R) -> R {
281        let walk = self.walk.get() + 1;
282        self.walk.set(walk);
283        let out = f();
284        self.since.borrow_mut().retain(|_, (_, seen)| *seen == walk);
285        out
286    }
287}
288
289/// A row that shows: its item and its place in the tree.
290#[derive(Clone)]
291struct Flat<T> {
292    item: T,
293    shape: Shape,
294}
295
296/// The rows that show, in order: each root, then, while it's open, its
297/// children's rows, and so on down. A row whose key is one of its own
298/// folders' doesn't open, so a cycle in the app's data ends there.
299fn flatten<T: Clone, K: Eq + Hash>(
300    roots: Vec<T>,
301    key: &dyn Fn(&T) -> K,
302    children: &dyn Fn(&T) -> Option<Vec<T>>,
303    loading: Option<&dyn Fn(&T) -> bool>,
304    open: &HashSet<K>,
305) -> Vec<Flat<T>> {
306    struct Walk<'a, T, K> {
307        key: &'a dyn Fn(&T) -> K,
308        children: &'a dyn Fn(&T) -> Option<Vec<T>>,
309        loading: Option<&'a dyn Fn(&T) -> bool>,
310        open: &'a HashSet<K>,
311        /// The open rows above the one being walked.
312        folders: Vec<K>,
313        out: Vec<Flat<T>>,
314    }
315
316    impl<T: Clone, K: Eq + Hash> Walk<'_, T, K> {
317        fn visit(&mut self, items: Vec<T>, parent: Option<usize>, depth: u32) {
318            for item in items {
319                let k = (self.key)(&item);
320                let kids = (self.children)(&item);
321                let expandable = kids.is_some();
322                let expanded = expandable && self.open.contains(&k) && !self.folders.contains(&k);
323                let loading = self.loading.is_some_and(|loading| loading(&item));
324                let index = self.out.len();
325                self.out.push(Flat { item, shape: Shape { parent, depth, expandable, expanded, loading } });
326                if let (true, Some(kids)) = (expanded, kids) {
327                    self.folders.push(k);
328                    self.visit(kids, Some(index), depth + 1);
329                    self.folders.pop();
330                }
331            }
332        }
333    }
334
335    let mut walk = Walk { key, children, loading, open, folders: Vec::new(), out: Vec::new() };
336    walk.visit(roots, None, 0);
337    walk.out
338}
339
340impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> View for Tree<T, K> {
341    fn build(self, ui: &Ui) -> NodeId {
342        let Tree {
343            element,
344            roots,
345            key,
346            children,
347            render,
348            expanded,
349            mode,
350            style,
351            selected,
352            on_activate,
353            estimate,
354            handle,
355            files,
356            moves,
357            loading,
358        } = self;
359        let expanded = expanded.unwrap_or_else(|| signal(Vec::new()));
360        let loads = loading.is_some();
361        let delayed = loading.map(|loading| Delayed {
362            ui: ui.clone(),
363            key: key.clone(),
364            loading,
365            since: RefCell::default(),
366            walk: Cell::new(0),
367            due: signal(0),
368        });
369        let each = {
370            let (key, children) = (key.clone(), children.clone());
371            Value::Dynamic(Rc::new(move || {
372                let open: HashSet<K> = expanded.get().into_iter().collect();
373                match &delayed {
374                    Some(delayed) => {
375                        let shows = |item: &T| delayed.shows(item);
376                        delayed.walk(|| flatten(roots.get(), &*key, &*children, Some(&shows), &open))
377                    }
378                    None => flatten(roots.get(), &*key, &*children, None, &open),
379                }
380            }))
381        };
382        let mount: Mount<Flat<T>> = Rc::new(move |ui: &Ui, row, flat: Flat<T>| {
383            let host = ui.create(WidgetKind::Container, vec![Prop::Row(row)]);
384            let content = render.render(flat.item).build(ui);
385            ui.append_child(host, content);
386            vec![host]
387        });
388        let tree = TreeParts {
389            shape: Rc::new(|flat: &Flat<T>| flat.shape),
390            on_expand: Rc::new(move |k: K, open: bool| {
391                let has = expanded.with_untracked(|keys| keys.contains(&k));
392                match (open, has) {
393                    (true, false) => expanded.update(|keys| keys.push(k)),
394                    (false, true) => expanded.update(|keys| keys.retain(|o| *o != k)),
395                    _ => {}
396                }
397            }),
398            loading: loads,
399        };
400        let item_key = key.clone();
401        let parts = RowParts {
402            each,
403            key: Rc::new(move |flat: &Flat<T>| item_key(&flat.item)),
404            mount,
405            mode,
406            style,
407            selected,
408            on_activate,
409            estimate,
410            handle,
411            files: files.map(|file| Rc::new(move |flat: &Flat<T>| file(&flat.item)) as FileFn<Flat<T>>),
412            moves,
413            tree: Some(tree),
414        };
415        build_rows(ui, element, parts)
416    }
417}
418
419// `view!` tags: `<Tree roots=… key=… children=… let:item>`. `roots`, `key`
420// and `children` come first; each step is a type of its own, so a missing
421// one is a compile error. Style attributes work at every step, tree
422// attributes after `children`.
423
424impl Tree<(), (), ()> {
425    #[doc(hidden)]
426    pub fn __tag() -> TreeWithoutRoots {
427        TreeWithoutRoots(Element::new(WidgetKind::Tree))
428    }
429}
430
431#[doc(hidden)]
432pub struct TreeWithoutRoots(Element);
433
434impl TreeWithoutRoots {
435    pub fn roots<T: Clone + 'static>(self, roots: impl IntoValue<Vec<T>>) -> TreeWithoutKey<T> {
436        TreeWithoutKey { element: self.0, roots: roots.into_value() }
437    }
438}
439
440impl ElementBuilder for TreeWithoutRoots {
441    fn element(&mut self) -> &mut Element {
442        &mut self.0
443    }
444}
445
446#[doc(hidden)]
447pub struct TreeWithoutKey<T: 'static> {
448    element: Element,
449    roots: Value<Vec<T>>,
450}
451
452impl<T: Clone + 'static> TreeWithoutKey<T> {
453    pub fn key<K: Eq + Hash + Clone + 'static>(self, key: impl Fn(&T) -> K + 'static) -> TreeWithoutChildren<T, K> {
454        TreeWithoutChildren { element: self.element, roots: self.roots, key: Rc::new(key) }
455    }
456}
457
458impl<T: 'static> ElementBuilder for TreeWithoutKey<T> {
459    fn element(&mut self) -> &mut Element {
460        &mut self.element
461    }
462}
463
464#[doc(hidden)]
465pub struct TreeWithoutChildren<T: 'static, K: 'static> {
466    element: Element,
467    roots: Value<Vec<T>>,
468    key: KeyFn<T, K>,
469}
470
471impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> TreeWithoutChildren<T, K> {
472    pub fn children(self, children: impl Fn(&T) -> Option<Vec<T>> + 'static) -> Tree<T, K, ()> {
473        Tree::with_element(self.element, self.roots, self.key, Rc::new(children), ())
474    }
475}
476
477impl<T: 'static, K: 'static> ElementBuilder for TreeWithoutChildren<T, K> {
478    fn element(&mut self) -> &mut Element {
479        &mut self.element
480    }
481}
482
483impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> Tree<T, K, ()> {
484    #[doc(hidden)]
485    pub fn __children<V: View>(self, render: impl Fn(T) -> V + 'static) -> Tree<T, K> {
486        let Tree {
487            element,
488            roots,
489            key,
490            children,
491            expanded,
492            mode,
493            style,
494            selected,
495            on_activate,
496            estimate,
497            handle,
498            files,
499            moves,
500            loading,
501            ..
502        } = self;
503        Tree {
504            element,
505            roots,
506            key,
507            children,
508            render: RowRender::new(move |item| AnyView::new(render(item))),
509            expanded,
510            mode,
511            style,
512            selected,
513            on_activate,
514            estimate,
515            handle,
516            files,
517            moves,
518            loading,
519        }
520    }
521}