Skip to main content

mitsuami_core/
list.rs

1//! `List`: the platform's list control, with rows built by the core.
2//!
3//! The native control (NSTableView, ListView, gtk::ListView, QML ListView)
4//! virtualises: it scrolls, decides which rows to realise, recycles them,
5//! and draws and handles the selection. When it realises a row it reports
6//! `RowShown`, and the list mounts that row, in a host `Container` carrying
7//! its [`RowKey`]; when it lets a row go (`RowHidden`), the list disposes
8//! it. Rows are keyed like [`For`](crate::For)'s.
9
10use std::cell::RefCell;
11use std::collections::{HashMap, HashSet};
12use std::hash::Hash;
13use std::path::PathBuf;
14use std::rc::Rc;
15
16use mitsuami_reactive::{IntoValue, Owner, Signal, Value, effect, untrack};
17
18use crate::command::{EventValue, UiEvent};
19use crate::element::{Element, ElementBuilder};
20use crate::services::Shortcut;
21use crate::tweak::Tweak;
22use crate::ui::{Ui, WeakUi};
23use crate::units::Length;
24use crate::view::{AnyView, View};
25use crate::widget::{ListStyle, NodeId, Prop, RowKey, SelectionMode, WidgetKind};
26
27pub(crate) type KeyFn<T, K> = Rc<dyn Fn(&T) -> K>;
28/// The file a row's item stands for, which dragging the row carries.
29pub(crate) type FileFn<T> = Rc<dyn Fn(&T) -> Option<PathBuf>>;
30type RowOf<K> = Rc<dyn Fn(&K) -> Option<RowKey>>;
31
32/// How a `List` renders a row.
33pub struct RowRender<T>(Rc<dyn Fn(T) -> AnyView>);
34
35/// A virtualised list of rows, shown by the platform's own list control.
36///
37/// ```ignore
38/// List::new(move || contacts.get(), |c| c.id, |c| ContactRow(c))
39///     .selected(selected)            // Signal<Vec<K>>: the selected keys
40///     .on_activate(|id| open(id))    // double-click or Enter
41///     .grow(1.0)
42/// ```
43///
44/// Only the rows the platform shows (in view, or about to be) are mounted;
45/// the others exist only as their keys. Rows can hold any view. Each row is
46/// laid out at the width the list gives its rows, and is as high as its
47/// content.
48///
49/// Rows are read by screen readers (and found by tests) as list items named
50/// by their text.
51///
52/// The type's defaults make `List` alone name the widget, for
53/// [`Tweak<List>`](Tweak).
54pub struct List<T: 'static = (), K: 'static = (), R = RowRender<T>> {
55    element: Element,
56    each: Value<Vec<T>>,
57    key: KeyFn<T, K>,
58    render: R,
59    mode: Option<Value<SelectionMode>>,
60    style: Option<ListStyle>,
61    selected: Option<Signal<Vec<K>>>,
62    on_activate: Option<Rc<dyn Fn(K)>>,
63    estimate: Option<f32>,
64    handle: Option<ListHandle<K>>,
65    files: Option<FileFn<T>>,
66}
67
68impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> List<T, K> {
69    pub fn new<V: View>(
70        each: impl IntoValue<Vec<T>>,
71        key: impl Fn(&T) -> K + 'static,
72        render: impl Fn(T) -> V + 'static,
73    ) -> List<T, K> {
74        List::keyed(each.into_value(), Rc::new(key), RowRender(Rc::new(move |item| AnyView::new(render(item)))))
75    }
76}
77
78impl<T: 'static, K: 'static, R> List<T, K, R> {
79    fn keyed(each: Value<Vec<T>>, key: KeyFn<T, K>, render: R) -> List<T, K, R> {
80        List::with_element(Element::new(WidgetKind::List), each, key, render)
81    }
82
83    fn with_element(element: Element, each: Value<Vec<T>>, key: KeyFn<T, K>, render: R) -> List<T, K, R> {
84        List {
85            element,
86            each,
87            key,
88            render,
89            mode: None,
90            style: None,
91            selected: None,
92            on_activate: None,
93            estimate: None,
94            handle: None,
95            files: None,
96        }
97    }
98
99    /// Rows can be dragged out of the app, carrying the files their items
100    /// stand for (`None`: that row doesn't drag), to the file manager,
101    /// another app or a folder, as a file manager's rows are: the
102    /// platform's own drag, which drags the selected rows when a selected
103    /// one is dragged. The drag offers to copy, so the files stay where
104    /// they are. Dragging isn't reachable from the keyboard or assistive
105    /// technology, so offer another way too (Copy, Share, Export).
106    ///
107    /// ```ignore
108    /// List::new(..).drag_files(|entry: &Entry| Some(entry.path.clone()))
109    /// ```
110    pub fn drag_files(mut self, file: impl Fn(&T) -> Option<PathBuf> + 'static) -> Self {
111        self.files = Some(Rc::new(file));
112        self
113    }
114
115    /// Binds the selection, as the selected rows' keys, both ways. Lists
116    /// with a selection bound select one row at a time unless
117    /// [`selection_mode`](List::selection_mode) says otherwise.
118    pub fn selected(mut self, selected: Signal<Vec<K>>) -> Self {
119        self.selected = Some(selected);
120        self
121    }
122
123    /// How many rows can be selected. It can change while the list shows:
124    /// the selection keeps what the new mode can hold (none, or the row the
125    /// platform keeps), and the rows let go are reported as deselected.
126    pub fn selection_mode(mut self, mode: impl IntoValue<SelectionMode>) -> Self {
127        self.mode = Some(mode.into_value());
128        self
129    }
130
131    /// How the list sits in its surroundings: edge to edge (the default) or
132    /// framed. Pick per platform with `platform!`:
133    ///
134    /// ```ignore
135    /// List::new(..).list_style(platform! { kde => ListStyle::Framed, _ => ListStyle::Plain })
136    /// ```
137    pub fn list_style(mut self, style: ListStyle) -> Self {
138        self.style = Some(style);
139        self
140    }
141
142    /// Called with a row's key when it's activated: double-clicked, or Enter
143    /// pressed on it.
144    pub fn on_activate(mut self, handler: impl Fn(K) + 'static) -> Self {
145        self.on_activate = Some(Rc::new(handler));
146        self
147    }
148
149    /// Runs `handler` when `key` is pressed while the list, or a control
150    /// inside it, has keyboard focus, and the focused control doesn't use
151    /// the key itself (the arrows, Home and End, typing to
152    /// select, and what else the platform's list takes): Space for a preview, Delete for Move to Trash.
153    /// A key goes to the nearest node around the focused control that
154    /// takes it. Nothing shows keys taken this way, so give the command a
155    /// menu item or a button too, and pick the keys the platform's own apps
156    /// use (`platform!`).
157    ///
158    /// ```ignore
159    /// List::new(..).on_key(' ', preview)
160    /// ```
161    pub fn on_key(mut self, key: impl Into<Shortcut>, handler: impl Fn() + 'static) -> Self {
162        self.element.on_key(key.into(), handler);
163        self
164    }
165
166    /// How high rows are likely to be, for platforms that size rows before
167    /// they're shown (AppKit). By default, the rows shown so far tell.
168    pub fn estimated_row_height(mut self, height: impl Into<Length>) -> Self {
169        self.estimate = match height.into() {
170            Length::Px(px) => Some(px),
171            _ => None,
172        };
173        self
174    }
175
176    /// Connects a [`ListHandle`], to scroll the list from code.
177    pub fn handle(mut self, handle: ListHandle<K>) -> Self {
178        self.handle = Some(handle);
179        self
180    }
181
182    /// Raw platform settings: see [`Tweak`]. They run on the list view,
183    /// not the scroll view around it. Lists have no semantic options past
184    /// their rows, selection and style: what the platforms offer
185    /// (alternating rows on AppKit, separators on GTK, key navigation on Qt
186    /// and WinUI) is each one's own.
187    pub fn native(mut self, tweak: Tweak<List>) -> Self {
188        tweak.apply(&mut self.element);
189        self
190    }
191}
192
193impl<T: 'static, K: 'static, R> ElementBuilder for List<T, K, R> {
194    fn element(&mut self) -> &mut Element {
195        &mut self.element
196    }
197}
198
199/// Scrolls a [`List`] from code: create one, pass it to
200/// [`List::handle`], and call [`scroll_to`](ListHandle::scroll_to).
201pub struct ListHandle<K: 'static>(Rc<RefCell<HandleState<K>>>);
202
203struct HandleState<K> {
204    connection: Option<Connection<K>>,
205    /// A key asked for before the list had it: an app's effect can run
206    /// before the list's own takes the items. Scrolled to when the rows
207    /// next change, if it's among them.
208    pending: Option<K>,
209}
210
211struct Connection<K> {
212    ui: WeakUi,
213    id: NodeId,
214    row_of: RowOf<K>,
215}
216
217impl<K: 'static> ListHandle<K> {
218    pub fn new() -> ListHandle<K> {
219        ListHandle(Rc::new(RefCell::new(HandleState { connection: None, pending: None })))
220    }
221
222    /// The list's node, once it's built.
223    pub fn id(&self) -> Option<NodeId> {
224        self.0.borrow().connection.as_ref().map(|c| c.id)
225    }
226
227    /// Scrolls just enough to show the row with this key, mounted or not.
228    /// A key whose item the list doesn't have yet, arriving with the same
229    /// change, is scrolled to once the list has it.
230    pub fn scroll_to(&self, key: &K)
231    where
232        K: Clone,
233    {
234        let mut state = self.0.borrow_mut();
235        let found = state
236            .connection
237            .as_ref()
238            .and_then(|Connection { ui, id, row_of }| Some((ui.upgrade()?, *id, row_of(key)?)));
239        match found {
240            Some((ui, id, row)) => {
241                state.pending = None;
242                drop(state);
243                ui.scroll_to_row(id, row);
244            }
245            None => state.pending = Some(key.clone()),
246        }
247    }
248}
249
250impl<K: 'static> Clone for ListHandle<K> {
251    fn clone(&self) -> Self {
252        ListHandle(self.0.clone())
253    }
254}
255
256impl<K: 'static> Default for ListHandle<K> {
257    fn default() -> Self {
258        ListHandle::new()
259    }
260}
261
262/// The list's items and mounted rows, shared by its effects and handlers.
263struct Rows<T, K> {
264    /// The rows, in order.
265    order: Vec<RowKey>,
266    items: HashMap<RowKey, T>,
267    position: HashMap<RowKey, usize>,
268    row_keys: HashMap<K, RowKey>,
269    keys: HashMap<RowKey, K>,
270    next_key: u64,
271    /// Mounted rows: their hosts (a list's row host, a table's cell hosts,
272    /// in column order) and scope.
273    mounted: HashMap<RowKey, (Vec<NodeId>, Owner)>,
274}
275
276/// Builds a mounted row's hosts, in the scope of the row.
277pub(crate) type Mount<T> = Rc<dyn Fn(&Ui, RowKey, T) -> Vec<NodeId>>;
278
279/// What a `List` and a `Table` share: their data, selection, activation
280/// and handle, and the rows the platform shows.
281pub(crate) struct RowParts<T: 'static, K: 'static> {
282    pub each: Value<Vec<T>>,
283    pub key: KeyFn<T, K>,
284    pub mount: Mount<T>,
285    pub mode: Option<Value<SelectionMode>>,
286    pub style: Option<ListStyle>,
287    pub selected: Option<Signal<Vec<K>>>,
288    pub on_activate: Option<Rc<dyn Fn(K)>>,
289    pub estimate: Option<f32>,
290    pub handle: Option<ListHandle<K>>,
291    pub files: Option<FileFn<T>>,
292}
293
294impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> View for List<T, K> {
295    fn build(self, ui: &Ui) -> NodeId {
296        let List { element, each, key, render, mode, style, selected, on_activate, estimate, handle, files } = self;
297        let mount: Mount<T> = Rc::new(move |ui: &Ui, row, item| {
298            let host = ui.create(WidgetKind::Container, vec![Prop::Row(row)]);
299            let content = (render.0)(item).build(ui);
300            ui.append_child(host, content);
301            vec![host]
302        });
303        let parts = RowParts { each, key, mount, mode, style, selected, on_activate, estimate, handle, files };
304        build_rows(ui, element, parts)
305    }
306}
307
308/// Builds a `List` or `Table` from its element, and mounts the rows the
309/// platform shows.
310pub(crate) fn build_rows<T: Clone + 'static, K: Eq + Hash + Clone + 'static>(
311    ui: &Ui,
312    mut element: Element,
313    parts: RowParts<T, K>,
314) -> NodeId {
315    let RowParts { each, key, mount, mode, style, selected, on_activate, estimate, handle, files } = parts;
316    let mode = mode.unwrap_or(Value::Static(match selected {
317        Some(_) => SelectionMode::Single,
318        None => SelectionMode::None,
319    }));
320    element.prop(mode, Prop::SelectionMode);
321    element.prop(Value::Static(Vec::new()), Prop::Rows);
322    element.prop(Value::Static(Vec::new()), Prop::Selected);
323    if let Some(style) = style {
324        element.prop(Value::Static(style), Prop::ListStyle);
325    }
326    if let Some(estimate) = estimate {
327        element.prop(Value::Static(estimate), Prop::EstimatedRowHeight);
328    }
329    let id = element.build(ui);
330
331    let rows: Rc<RefCell<Rows<T, K>>> = Rc::new(RefCell::new(Rows {
332        order: Vec::new(),
333        items: HashMap::new(),
334        position: HashMap::new(),
335        row_keys: HashMap::new(),
336        keys: HashMap::new(),
337        next_key: 1,
338        mounted: HashMap::new(),
339    }));
340    // Row scopes hang off a scope of their own in the building owner, so
341    // they survive re-runs of the list's effects. With no owner, the rows
342    // and the effects go with the list's node.
343    let scope = ui.owner_or_node_scope(id);
344    let rows_scope = scope.child();
345
346    // Both take the `Ui`: the row handler, kept in the tree, holds it weakly.
347    // Puts the mounted rows' hosts in row order.
348    let arrange = {
349        let rows = rows.clone();
350        move |ui: &Ui| {
351            let rows = rows.borrow();
352            let mut mounted: Vec<(usize, &Vec<NodeId>)> =
353                rows.mounted.iter().map(|(row, (hosts, _))| (rows.position[row], hosts)).collect();
354            mounted.sort_by_key(|(position, _)| *position);
355            ui.set_children(id, mounted.into_iter().flat_map(|(_, hosts)| hosts.iter().copied()).collect());
356        }
357    };
358    let unmount = move |ui: &Ui, rows: &mut Rows<T, K>, row: RowKey| {
359        if let Some((hosts, owner)) = rows.mounted.remove(&row) {
360            owner.dispose();
361            for host in hosts {
362                ui.destroy(host);
363            }
364        }
365    };
366    // The platform shows and lets go of rows: mount and dispose them.
367    {
368        let (weak, rows, arrange, unmount) = (ui.downgrade(), rows.clone(), arrange.clone(), unmount);
369        ui.on_event(id, move |event| {
370            let Some(ui) = weak.upgrade() else { return };
371            match event {
372                UiEvent::RowShown(row) => {
373                    let item = {
374                        let rows = rows.borrow();
375                        if rows.mounted.contains_key(row) {
376                            return;
377                        }
378                        let Some(item) = rows.items.get(row).cloned() else { return };
379                        item
380                    };
381                    let owner = rows_scope.child();
382                    let hosts = owner.with(|| mount(&ui, *row, item));
383                    // The row's own code may have changed the data so that
384                    // its item went: it's let go of, as the data's effect
385                    // lets go of rows that go, not left for `arrange`.
386                    let gone = {
387                        let mut rows = rows.borrow_mut();
388                        match rows.items.contains_key(row) {
389                            true => {
390                                rows.mounted.insert(*row, (hosts, owner));
391                                None
392                            }
393                            false => Some(hosts),
394                        }
395                    };
396                    if let Some(hosts) = gone {
397                        owner.dispose();
398                        for host in hosts {
399                            ui.destroy(host);
400                        }
401                    }
402                }
403                UiEvent::RowHidden(row) => unmount(&ui, &mut rows.borrow_mut(), *row),
404                _ => return,
405            }
406            arrange(&ui);
407        });
408    }
409
410    // The data: keep the row keys of items that stay, give new ones
411    // theirs, and dispose the rows of items that went.
412    {
413        let (ui, rows) = (ui.clone(), rows.clone());
414        let pending = handle.as_ref().map(|h| h.0.clone());
415        let update = move || {
416            let items = each.get();
417            untrack(|| {
418                let mut row_files = Vec::new();
419                let (order, was) = {
420                    let mut rows = rows.borrow_mut();
421                    let rows = &mut *rows;
422                    let was: HashSet<RowKey> = rows.order.iter().copied().collect();
423                    let mut row_keys = HashMap::with_capacity(items.len());
424                    let mut keys = HashMap::with_capacity(items.len());
425                    let mut by_key = HashMap::with_capacity(items.len());
426                    let mut order = Vec::with_capacity(items.len());
427                    for item in items {
428                        let k = key(&item);
429                        // A key that came before in these items gets a row
430                        // of its own, as `For` renders it: the same row twice
431                        // in `Prop::Rows` would show one mounted row twice.
432                        let row = match rows.row_keys.get(&k) {
433                            Some(row) if !row_keys.contains_key(&k) => *row,
434                            _ => {
435                                rows.next_key += 1;
436                                RowKey(rows.next_key - 1)
437                            }
438                        };
439                        if let Some(path) = files.as_ref().and_then(|file| file(&item)) {
440                            row_files.push((row, path));
441                        }
442                        row_keys.entry(k.clone()).or_insert(row);
443                        keys.insert(row, k);
444                        by_key.insert(row, item);
445                        order.push(row);
446                    }
447                    rows.position = order.iter().enumerate().map(|(i, row)| (*row, i)).collect();
448                    rows.items = by_key;
449                    rows.row_keys = row_keys;
450                    rows.keys = keys;
451                    rows.order = order.clone();
452                    let gone: Vec<RowKey> =
453                        rows.mounted.keys().filter(|row| !rows.items.contains_key(row)).copied().collect();
454                    for row in gone {
455                        unmount(&ui, rows, row);
456                    }
457                    (order, was)
458                };
459                // Before the rows, so a row can be dragged once it's there.
460                if files.is_some() {
461                    ui.set_prop(id, Prop::RowFiles(row_files));
462                }
463                // A key scrolled to before its item came.
464                let pending = pending.as_ref().and_then(|state| state.borrow_mut().pending.take());
465                let scroll = pending.and_then(|k| rows.borrow().row_keys.get(&k).copied());
466                let Some(selected) = selected else {
467                    ui.set_prop(id, Prop::Rows(order));
468                    if let Some(row) = scroll {
469                        ui.scroll_to_row(id, row);
470                    }
471                    return arrange(&ui);
472                };
473                // Selected rows that go are deselected here, before the
474                // rows change: the platform would report it later, after
475                // whatever the app selects next.
476                let keys = selected.get_untracked();
477                let (kept, shown) = {
478                    let rows = rows.borrow();
479                    let kept: Vec<K> = keys.iter().filter(|k| rows.row_keys.contains_key(k)).cloned().collect();
480                    let mut shown: Vec<RowKey> = kept.iter().map(|k| rows.row_keys[k]).collect();
481                    shown.sort_by_key(|row| rows.position[row]);
482                    (kept, shown)
483                };
484                let staying = shown.iter().filter(|row| was.contains(row)).copied().collect();
485                ui.set_prop(id, Prop::Selected(staying));
486                ui.set_prop(id, Prop::Rows(order));
487                // With the rows in, keys selected before theirs came.
488                ui.set_prop(id, Prop::Selected(shown));
489                if let Some(row) = scroll {
490                    ui.scroll_to_row(id, row);
491                }
492                if kept.len() != keys.len() {
493                    selected.set(kept);
494                }
495                arrange(&ui);
496            });
497        };
498        scope.with(|| effect(update));
499    }
500
501    // The selection, both ways.
502    if let Some(selected) = selected {
503        let (ui_, rows_) = (ui.clone(), rows.clone());
504        let update = move || {
505            let keys = selected.get();
506            let rows = rows_.borrow();
507            // In row order, as platforms report their selection.
508            let mut selection: Vec<RowKey> = keys.iter().filter_map(|k| rows.row_keys.get(k).copied()).collect();
509            selection.sort_by_key(|row| rows.position[row]);
510            drop(rows);
511            untrack(|| ui_.set_prop(id, Prop::Selected(selection)));
512        };
513        scope.with(|| effect(update));
514        let rows = rows.clone();
515        ui.on_event(id, move |event| {
516            if let UiEvent::Changed(EventValue::Rows(selection)) = event {
517                let keys: Vec<K> = {
518                    let rows = rows.borrow();
519                    selection.iter().filter_map(|row| rows.keys.get(row).cloned()).collect()
520                };
521                selected.set(keys);
522            }
523        });
524    }
525    if let Some(on_activate) = on_activate {
526        let rows = rows.clone();
527        ui.on_event(id, move |event| {
528            if let UiEvent::RowActivated(row) = event {
529                let key = rows.borrow().keys.get(row).cloned();
530                if let Some(key) = key {
531                    on_activate(key);
532                }
533            }
534        });
535    }
536    if let Some(handle) = handle {
537        let rows = rows.clone();
538        handle.0.borrow_mut().connection = Some(Connection {
539            ui: ui.downgrade(),
540            id,
541            row_of: Rc::new(move |k| rows.borrow().row_keys.get(k).copied()),
542        });
543    }
544    id
545}
546
547// `view!` tags: `<List each=… key=… let:item>`. `each` and `key` come
548// first; each step is a type of its own, so a missing one is a compile
549// error. Style attributes work at every step, list attributes after `key`.
550
551impl List<(), (), ()> {
552    #[doc(hidden)]
553    pub fn __tag() -> ListWithoutEach {
554        ListWithoutEach(Element::new(WidgetKind::List))
555    }
556}
557
558#[doc(hidden)]
559pub struct ListWithoutEach(Element);
560
561impl ListWithoutEach {
562    pub fn each<T: Clone + 'static>(self, each: impl IntoValue<Vec<T>>) -> ListWithoutKey<T> {
563        ListWithoutKey { element: self.0, each: each.into_value() }
564    }
565}
566
567impl ElementBuilder for ListWithoutEach {
568    fn element(&mut self) -> &mut Element {
569        &mut self.0
570    }
571}
572
573#[doc(hidden)]
574pub struct ListWithoutKey<T: 'static> {
575    element: Element,
576    each: Value<Vec<T>>,
577}
578
579impl<T: Clone + 'static> ListWithoutKey<T> {
580    pub fn key<K: Eq + Hash + Clone + 'static>(self, key: impl Fn(&T) -> K + 'static) -> List<T, K, ()> {
581        List::with_element(self.element, self.each, Rc::new(key), ())
582    }
583}
584
585impl<T: 'static> ElementBuilder for ListWithoutKey<T> {
586    fn element(&mut self) -> &mut Element {
587        &mut self.element
588    }
589}
590
591impl<T: Clone + 'static, K: Eq + Hash + Clone + 'static> List<T, K, ()> {
592    #[doc(hidden)]
593    pub fn __children<V: View>(self, render: impl Fn(T) -> V + 'static) -> List<T, K> {
594        let List { element, each, key, mode, style, selected, on_activate, estimate, handle, files, .. } = self;
595        let render = RowRender(Rc::new(move |item| AnyView::new(render(item))) as Rc<dyn Fn(T) -> AnyView>);
596        List { element, each, key, render, mode, style, selected, on_activate, estimate, handle, files }
597    }
598}