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