Skip to main content

waft_winui/controls/
tree_view.rs

1//! TreeView.cpp, TreeView.xaml and TreeViewList.cpp, with the ListView behaviour TreeViewList
2//! inherits from ListViewBase_Partial*.cpp and Selector_Partial.cpp: a tree of nodes the
3//! application owns, flattened into the rows of a lazy list as ViewModel.cpp flattens it.
4//!
5//! The application owns the nodes, their `is_expanded`, and the selection. The tree reports what
6//! it asks for: `expanding` and `collapsed` for a node it expands or collapses, `selection_changed`
7//! for a selection, and `move_requested` for nodes a drop or a keyboard reorder moves. Until the
8//! application next builds the tree, the tree shows what it asked for; then it shows what the
9//! application passes.
10//!
11//! Selection follows the source per mode. In Single mode the selection is the list's own, as
12//! TreeViewList takes it from ListView: a click or Enter selects, the arrow keys move it with the
13//! focus, Ctrl with a click or Space toggles it, and a node that leaves the rows (an ancestor
14//! collapses, or the node moves) is no longer selected. In Multiple mode each row has a check box,
15//! and ViewModel's rules apply: a node takes its whole subtree with it, and its ancestors become
16//! selected or partly selected from their children.
17
18mod drag;
19mod item;
20mod view_model;
21
22pub use drag::{
23    DataPackageOperation, TreeViewDragItemsCompletedEventArgs, TreeViewDragItemsStartingEventArgs,
24};
25
26use crate::*;
27// Waft exports a `FocusState` of its own; the XAML one is meant here.
28use crate::FocusState;
29use drag::TreeDragState;
30use item::{ItemFocus, PressedPart, TreeViewItemContainer, estimated_row_height};
31use std::{
32    collections::{HashMap, HashSet},
33    fmt,
34    rc::Rc,
35};
36use view_model::{MovePlan, NodeSelectionState, NodeTree, Rows, SelectionChange};
37use waft_embedder::{Offset, Rect, Size, TextDirection};
38use waft_foundation::{App, Handle, OptionRetained, Ref, ValueKey};
39use waft_painting::EdgeInsetsGeometry;
40use waft_scheduler::{FrameCallback, Ticker};
41use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey};
42use waft_widgets::*;
43
44/// XAML `TreeViewSelectionMode`.
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
46pub enum TreeViewSelectionMode {
47    /// Nothing can be selected.
48    None,
49    /// One node at a time, the list's selection.
50    #[default]
51    Single,
52    /// Any nodes, through each row's check box.
53    Multiple,
54}
55
56/// XAML `TreeViewNode`: one node of the tree the application passes.
57#[derive(Clone)]
58pub struct TreeViewNode {
59    /// Identity across rebuilds and moves; unique within the whole tree.
60    pub id: String,
61
62    /// `Content`: what the node's row shows.
63    pub content: WidgetRef,
64
65    /// `Children`, in order.
66    pub children: Vec<TreeViewNode>,
67
68    /// `IsExpanded`: whether the node's children are rows of the list.
69    pub is_expanded: bool,
70
71    /// `HasUnrealizedChildren`: the node has children the application has not passed yet, which
72    /// it loads in `expanding`. Such a node shows its chevron.
73    pub has_unrealized_children: bool,
74}
75
76impl TreeViewNode {
77    /// Creates a node showing `content`, without children.
78    #[cfg_attr(debug_assertions, track_caller)]
79    pub fn new<K>(id: impl Into<String>, content: impl IntoWidget<K>) -> Self {
80        Self {
81            id: id.into(),
82            content: content.into_widget(),
83            children: Vec::new(),
84            is_expanded: false,
85            has_unrealized_children: false,
86        }
87    }
88
89    /// Creates a node that is `text`, as a node whose `Content` is a string shows it.
90    pub fn text(id: impl Into<String>, text: impl Into<String>) -> Self {
91        Self::new(id, Text::new(text).soft_wrap(false))
92    }
93
94    /// Sets Children.
95    pub fn children(mut self, value: Vec<TreeViewNode>) -> Self {
96        self.children = value;
97        self
98    }
99
100    /// Sets IsExpanded.
101    pub fn is_expanded(mut self, value: bool) -> Self {
102        self.is_expanded = value;
103        self
104    }
105
106    /// Sets HasUnrealizedChildren.
107    pub fn has_unrealized_children(mut self, value: bool) -> Self {
108        self.has_unrealized_children = value;
109        self
110    }
111}
112
113impl fmt::Debug for TreeViewNode {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.debug_struct("TreeViewNode")
116            .field("id", &self.id)
117            .field("is_expanded", &self.is_expanded)
118            .field("has_unrealized_children", &self.has_unrealized_children)
119            .field("children", &self.children)
120            .finish_non_exhaustive()
121    }
122}
123
124/// XAML `TreeViewSelectionChangedEventArgs`, with the selection the tree asks for.
125#[derive(Clone, Debug, PartialEq, Eq)]
126pub struct TreeViewSelectionChangedEventArgs {
127    /// `AddedItems`: the nodes that became selected, in order.
128    pub added_items: Vec<String>,
129
130    /// `RemovedItems`: the nodes that stopped being selected, in order.
131    pub removed_items: Vec<String>,
132
133    /// `SelectedNodes` after the change, which the application passes back in `selected_nodes`.
134    pub selected_nodes: Vec<String>,
135}
136
137/// XAML `TreeViewItemInvokedEventArgs`.
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct TreeViewItemInvokedEventArgs {
140    /// `InvokedItem`: the node clicked, or the focused node of Enter or Space.
141    pub invoked_item: String,
142}
143
144/// XAML `TreeViewExpandingEventArgs`: the tree expanded a node, which the application stores in
145/// its `is_expanded`.
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct TreeViewExpandingEventArgs {
148    /// `Node`.
149    pub node: String,
150}
151
152/// XAML `TreeViewCollapsedEventArgs`: the tree collapsed a node, which the application stores in
153/// its `is_expanded`.
154#[derive(Clone, Debug, PartialEq, Eq)]
155pub struct TreeViewCollapsedEventArgs {
156    /// `Node`.
157    pub node: String,
158}
159
160/// One move of a node, which the application applies to its tree: the node leaves its parent
161/// and becomes the child of `new_parent` at `index`.
162#[derive(Clone, Debug, PartialEq, Eq)]
163pub struct TreeViewNodeMove {
164    /// The node, with its subtree.
165    pub node: String,
166
167    /// The node's new parent; `None` for the tree's root nodes.
168    pub new_parent: Option<String>,
169
170    /// The node's index among `new_parent`'s children, counted after the node has left its
171    /// parent.
172    pub index: usize,
173}
174
175/// The moves a drop or a keyboard reorder makes, which TreeView makes on its own nodes in
176/// WinUI.
177#[derive(Clone, Debug, PartialEq, Eq)]
178pub struct TreeViewMoveRequestedEventArgs {
179    /// The moves, applied one after another.
180    pub moves: Vec<TreeViewNodeMove>,
181}
182
183/// Receives XAML `SelectionChanged`.
184pub type TreeViewSelectionChangedHandler = Rc<dyn Fn(&mut App, TreeViewSelectionChangedEventArgs)>;
185
186/// Receives XAML `ItemInvoked`.
187pub type TreeViewItemInvokedHandler = Rc<dyn Fn(&mut App, TreeViewItemInvokedEventArgs)>;
188
189/// Receives XAML `Expanding`.
190pub type TreeViewExpandingHandler = Rc<dyn Fn(&mut App, TreeViewExpandingEventArgs)>;
191
192/// Receives XAML `Collapsed`.
193pub type TreeViewCollapsedHandler = Rc<dyn Fn(&mut App, TreeViewCollapsedEventArgs)>;
194
195/// Receives the moves the tree asks the application to make.
196pub type TreeViewMoveRequestedHandler = Rc<dyn Fn(&mut App, TreeViewMoveRequestedEventArgs)>;
197
198/// Receives XAML `DragItemsStarting`.
199pub type TreeViewDragItemsStartingHandler =
200    Rc<dyn Fn(&mut App, &mut TreeViewDragItemsStartingEventArgs)>;
201
202/// Receives XAML `DragItemsCompleted`.
203pub type TreeViewDragItemsCompletedHandler =
204    Rc<dyn Fn(&mut App, TreeViewDragItemsCompletedEventArgs)>;
205
206/// XAML `TreeView` with the template of `DefaultTreeViewStyle`: a `TreeViewList` of
207/// `TreeViewItem`s.
208#[derive(Clone)]
209pub struct TreeView {
210    /// `RootNodes`, with their descendants.
211    pub root_nodes: Vec<TreeViewNode>,
212
213    /// `SelectedNodes`, by id: the nodes drawn selected. In Single mode the first is the list's
214    /// selection, which clicks and the arrow keys replace, and every one is drawn selected, so an
215    /// application can keep several selected. In Multiple mode a node not among them is drawn
216    /// partly selected when one of its descendants is among them.
217    pub selected_nodes: Vec<String>,
218
219    /// `SelectionChanged`: asks the application for another selection.
220    pub selection_changed: TreeViewSelectionChangedHandler,
221
222    /// `SelectionMode`; `Single` by default.
223    pub selection_mode: TreeViewSelectionMode,
224
225    /// `IsEnabled`.
226    pub is_enabled: bool,
227
228    /// `Expanding`.
229    pub expanding: Option<TreeViewExpandingHandler>,
230
231    /// `Collapsed`.
232    pub collapsed: Option<TreeViewCollapsedHandler>,
233
234    /// `ItemInvoked`.
235    pub item_invoked: Option<TreeViewItemInvokedHandler>,
236
237    /// `CanDragItems`: whether a drag raises `DragItemsStarting` and `DragItemsCompleted` and can
238    /// move nodes; true by default.
239    pub can_drag_items: bool,
240
241    /// `CanReorderItems`: whether a drag or Shift+Alt with an arrow key can move nodes; true by
242    /// default.
243    pub can_reorder_items: bool,
244
245    /// `AllowDrop`: whether the list takes drops between rows; true by default. Drops onto a row
246    /// are the row's, which allows them either way.
247    pub allow_drop: bool,
248
249    /// Asks the application to move nodes.
250    pub move_requested: Option<TreeViewMoveRequestedHandler>,
251
252    /// `DragItemsStarting`.
253    pub drag_items_starting: Option<TreeViewDragItemsStartingHandler>,
254
255    /// `DragItemsCompleted`.
256    pub drag_items_completed: Option<TreeViewDragItemsCompletedHandler>,
257
258    /// Identity retained across parent rebuilds.
259    pub key: Option<KeyRef>,
260}
261
262impl TreeView {
263    /// Creates a tree of `root_nodes` showing `selected_nodes` selected, which asks for other
264    /// selections through `selection_changed`.
265    pub fn new(
266        root_nodes: Vec<TreeViewNode>,
267        selected_nodes: Vec<String>,
268        selection_changed: impl Fn(&mut App, TreeViewSelectionChangedEventArgs) + 'static,
269    ) -> TreeView {
270        TreeView {
271            root_nodes,
272            selected_nodes,
273            selection_changed: Rc::new(selection_changed),
274            selection_mode: TreeViewSelectionMode::Single,
275            is_enabled: true,
276            expanding: None,
277            collapsed: None,
278            item_invoked: None,
279            can_drag_items: true,
280            can_reorder_items: true,
281            allow_drop: true,
282            move_requested: None,
283            drag_items_starting: None,
284            drag_items_completed: None,
285            key: None,
286        }
287    }
288
289    /// Sets SelectionMode.
290    pub fn selection_mode(mut self, value: TreeViewSelectionMode) -> Self {
291        self.selection_mode = value;
292        self
293    }
294
295    /// Sets IsEnabled.
296    pub fn is_enabled(mut self, value: bool) -> Self {
297        self.is_enabled = value;
298        self
299    }
300
301    /// Sets Expanding.
302    pub fn expanding(
303        mut self,
304        value: impl Fn(&mut App, TreeViewExpandingEventArgs) + 'static,
305    ) -> Self {
306        self.expanding = Some(Rc::new(value));
307        self
308    }
309
310    /// Sets Collapsed.
311    pub fn collapsed(
312        mut self,
313        value: impl Fn(&mut App, TreeViewCollapsedEventArgs) + 'static,
314    ) -> Self {
315        self.collapsed = Some(Rc::new(value));
316        self
317    }
318
319    /// Sets ItemInvoked.
320    pub fn item_invoked(
321        mut self,
322        value: impl Fn(&mut App, TreeViewItemInvokedEventArgs) + 'static,
323    ) -> Self {
324        self.item_invoked = Some(Rc::new(value));
325        self
326    }
327
328    /// Sets CanDragItems.
329    pub fn can_drag_items(mut self, value: bool) -> Self {
330        self.can_drag_items = value;
331        self
332    }
333
334    /// Sets CanReorderItems.
335    pub fn can_reorder_items(mut self, value: bool) -> Self {
336        self.can_reorder_items = value;
337        self
338    }
339
340    /// Sets AllowDrop.
341    pub fn allow_drop(mut self, value: bool) -> Self {
342        self.allow_drop = value;
343        self
344    }
345
346    /// Sets the handler of the moves the tree asks for.
347    pub fn move_requested(
348        mut self,
349        value: impl Fn(&mut App, TreeViewMoveRequestedEventArgs) + 'static,
350    ) -> Self {
351        self.move_requested = Some(Rc::new(value));
352        self
353    }
354
355    /// Sets DragItemsStarting.
356    pub fn drag_items_starting(
357        mut self,
358        value: impl Fn(&mut App, &mut TreeViewDragItemsStartingEventArgs) + 'static,
359    ) -> Self {
360        self.drag_items_starting = Some(Rc::new(value));
361        self
362    }
363
364    /// Sets DragItemsCompleted.
365    pub fn drag_items_completed(
366        mut self,
367        value: impl Fn(&mut App, TreeViewDragItemsCompletedEventArgs) + 'static,
368    ) -> Self {
369        self.drag_items_completed = Some(Rc::new(value));
370        self
371    }
372
373    /// Sets widget identity.
374    pub fn key(mut self, key: KeyRef) -> Self {
375        self.key = Some(key);
376        self
377    }
378}
379
380impl fmt::Debug for TreeView {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        f.debug_struct("TreeView")
383            .field("root_nodes", &self.root_nodes)
384            .field("selected_nodes", &self.selected_nodes)
385            .field("selection_mode", &self.selection_mode)
386            .field("is_enabled", &self.is_enabled)
387            .finish_non_exhaustive()
388    }
389}
390
391/// `ScrollViewerLineDelta`: the scroll of a line, which an arrow key no row takes scrolls.
392const LINE_DELTA: f64 = 16.0;
393
394impl StatefulWidget for TreeView {
395    type State = TreeViewState;
396
397    fn key(&self) -> Option<&KeyRef> {
398        self.key.as_ref()
399    }
400
401    fn create_state(&self) -> TreeViewState {
402        let tree = NodeTree::new(&self.root_nodes);
403        let rows = tree.rows();
404        TreeViewState {
405            state: StateData::new(),
406            single_ticker_provider: Default::default(),
407            ticker: None,
408            tree: Rc::new(tree),
409            rows,
410            requested_expansion: HashMap::new(),
411            requested_selection: None,
412            row_estimate: 0.0,
413            item_focus: HashMap::new(),
414            row_keys: HashMap::new(),
415            viewport_key: GlobalKey::new(),
416            heights: HashMap::new(),
417            widths: HashMap::new(),
418            realized: HashSet::new(),
419            focused: None,
420            last_focused: None,
421            focus_epoch: 0,
422            pressed_part: None,
423            scroll: None,
424            building: false,
425            drag: TreeDragState::default(),
426        }
427    }
428}
429
430/// TreeView's view model and list: the nodes as the tree reads them, the rows, the focus, and
431/// what the tree asked of the application since it last built the tree.
432pub struct TreeViewState {
433    state: StateData<TreeView>,
434
435    /// The height of a row of one line of text, as the last build resolved it from the theme.
436    row_estimate: f64,
437
438    /// TickerMode subscription.
439    single_ticker_provider: SingleTickerProviderStateMixinData,
440
441    /// The clock of edge scrolling.
442    ticker: Option<Ref<Ticker>>,
443
444    /// The nodes, with the expansions and moves the tree asked for.
445    tree: Rc<NodeTree>,
446
447    /// The view model's flat list.
448    rows: Rows,
449
450    /// The `IsExpanded` the tree set, by node, until the application next builds it.
451    requested_expansion: HashMap<String, bool>,
452
453    /// The `SelectedNodes` the tree asked for, until the application next builds it.
454    requested_selection: Option<Vec<String>>,
455
456    /// The rows' focus, by node, owned here so that the tree can focus a row it scrolls to.
457    item_focus: HashMap<String, Ref<FocusNode>>,
458
459    /// Identifies each row's container, where the row is laid out.
460    row_keys: HashMap<String, GlobalKey>,
461
462    /// Identifies the list's viewport.
463    viewport_key: GlobalKey,
464
465    /// Each row's height and width, by node, as last laid out.
466    heights: HashMap<String, f64>,
467    widths: HashMap<String, f64>,
468
469    /// The rows the lazy list has built.
470    realized: HashSet<String>,
471
472    /// The node whose row has the focus.
473    focused: Option<String>,
474
475    /// `LastFocusedIndex`, by node: the row Tab enters the list at.
476    last_focused: Option<String>,
477
478    /// Invalidates focus requests a later one replaced.
479    focus_epoch: u64,
480
481    /// The row part the last press went down on, with the row and the pointer.
482    pressed_part: Option<(String, PressedPart, i64)>,
483
484    /// The list's scroll position.
485    scroll: Option<Ref<ScrollViewportController>>,
486
487    /// The application's values are being applied, during a build: callbacks to the application
488    /// wait for the frame's end.
489    building: bool,
490
491    /// TreeViewList's and ListViewBase's drag and drop.
492    drag: TreeDragState,
493}
494
495impl SingleTickerProviderStateMixin for TreeViewState {
496    fn single_ticker_provider_data(
497        self: Handle<Self>,
498        app: &App,
499    ) -> &SingleTickerProviderStateMixinData {
500        &app.get(self).single_ticker_provider
501    }
502
503    fn single_ticker_provider_data_mut(
504        self: Handle<Self>,
505        app: &mut App,
506    ) -> &mut SingleTickerProviderStateMixinData {
507        &mut app.get_mut(self).single_ticker_provider
508    }
509}
510
511/// The keyboard modifiers `GetKeyboardModifiers` reports.
512#[derive(Clone, Copy, Debug)]
513struct Modifiers {
514    alt: bool,
515    control: bool,
516    shift: bool,
517}
518
519impl Modifiers {
520    fn of(app: &mut App) -> Modifiers {
521        let keyboard = HardwareKeyboard::instance(app);
522        Modifiers {
523            alt: keyboard.is_alt_pressed(app),
524            control: keyboard.is_control_pressed(app),
525            shift: keyboard.is_shift_pressed(app),
526        }
527    }
528}
529
530/// Whether `key` is one of `IsDirectionalKey`'s.
531fn is_directional(key: LogicalKeyboardKey) -> bool {
532    matches!(
533        key,
534        LogicalKeyboardKey::ARROW_UP
535            | LogicalKeyboardKey::ARROW_DOWN
536            | LogicalKeyboardKey::ARROW_LEFT
537            | LogicalKeyboardKey::ARROW_RIGHT
538    )
539}
540
541impl TreeViewState {
542    fn alive(self: Handle<Self>, app: &App) -> bool {
543        self.mounted(app)
544    }
545
546    fn view(self: Handle<Self>, app: &App) -> Option<waft_embedder::ViewId> {
547        View::maybe_id_of(app, self.context(app))
548    }
549
550    /// Runs `work` once the frame is over, if the tree is still mounted.
551    fn after_frame(self: Handle<Self>, app: &mut App, work: impl Fn(&mut App) + 'static) {
552        let view = self.view(app);
553        after_next_frame(
554            app,
555            view,
556            FrameCallback::new(move |app, _| {
557                if self.alive(app) {
558                    work(app);
559                }
560            }),
561        );
562    }
563
564    /// Calls the application now, or at the frame's end while its values are being applied.
565    fn raise(self: Handle<Self>, app: &mut App, call: impl Fn(&mut App) + 'static) {
566        if app.get(self).building {
567            let view = self.view(app);
568            after_next_frame(app, view, FrameCallback::new(move |app, _| call(app)));
569        } else {
570            call(app);
571        }
572    }
573
574    fn mode(self: Handle<Self>, app: &App) -> TreeViewSelectionMode {
575        self.widget(app).selection_mode
576    }
577
578    fn scroll(self: Handle<Self>, app: &App) -> Handle<ScrollViewportController> {
579        app.get(self)
580            .scroll
581            .handle()
582            .expect("an initialized TreeView")
583    }
584
585    // MARK: The application's values
586
587    /// Reads the application's nodes, with the expansions the tree asked for, and checks its
588    /// selection: unique ids, which `NodeTree::new` checks.
589    fn sync_tree(self: Handle<Self>, app: &mut App) {
590        let mut tree = NodeTree::new(&self.widget(app).root_nodes);
591        for (id, expanded) in &app.get(self).requested_expansion {
592            tree.set_expanded(id, *expanded);
593        }
594        let rows = tree.rows();
595        let state = app.get_mut(self);
596        state.tree = Rc::new(tree);
597        state.rows = rows;
598        self.prune_rows(app);
599    }
600
601    /// Releases the focus of the nodes no longer in the tree, once their rows are gone.
602    fn prune_rows(self: Handle<Self>, app: &mut App) {
603        let tree = app.get(self).tree.clone();
604        let removed: Vec<String> = app
605            .get(self)
606            .item_focus
607            .keys()
608            .filter(|id| !tree.contains(id))
609            .cloned()
610            .collect();
611        for id in removed {
612            let state = app.get_mut(self);
613            let node = state.item_focus.remove(&id).unwrap();
614            state.row_keys.remove(&id);
615            state.heights.remove(&id);
616            state.widths.remove(&id);
617            let view = self.view(app);
618            after_next_frame(
619                app,
620                view,
621                FrameCallback::new(move |app, _| {
622                    node.dispose(app);
623                }),
624            );
625        }
626    }
627
628    // MARK: Selection
629
630    /// `SelectedNodes` as the tree reads them: what it last asked for, until the application
631    /// answers, else the application's.
632    fn selected_nodes(self: Handle<Self>, app: &App) -> Vec<String> {
633        let state = app.get(self);
634        state
635            .requested_selection
636            .clone()
637            .unwrap_or_else(|| self.widget(app).selected_nodes.clone())
638    }
639
640    /// The list's selection in Single mode: the first of `SelectedNodes`.
641    fn list_selection(self: Handle<Self>, app: &App) -> Option<String> {
642        if self.mode(app) != TreeViewSelectionMode::Single {
643            return None;
644        }
645        self.selected_nodes(app).into_iter().next()
646    }
647
648    /// Whether the node is among `SelectedNodes`: `TreeViewList::IsSelected`.
649    fn is_node_selected(self: Handle<Self>, app: &App, id: &str) -> bool {
650        self.selected_nodes(app).iter().any(|node| node == id)
651    }
652
653    /// `IsMutiSelectWithSelectedItems`.
654    fn is_multi_select_with_selected_items(self: Handle<Self>, app: &App) -> bool {
655        self.mode(app) == TreeViewSelectionMode::Multiple && !self.selected_nodes(app).is_empty()
656    }
657
658    /// Asks the application for `selected`, after `added` and `removed`.
659    fn request_selection(
660        self: Handle<Self>,
661        app: &mut App,
662        selected: Vec<String>,
663        added: Vec<String>,
664        removed: Vec<String>,
665    ) {
666        app.get_mut(self).requested_selection = Some(selected.clone());
667        let args = TreeViewSelectionChangedEventArgs {
668            added_items: added,
669            removed_items: removed,
670            selected_nodes: selected,
671        };
672        let handler = self.widget(app).selection_changed.clone();
673        self.raise(app, move |app| handler(app, args.clone()));
674        self.set_state(app, |_| {});
675    }
676
677    /// The list's `MakeSingleSelection` and `MakeToggleSelection`: `id` becomes the selection,
678    /// or nothing does.
679    fn set_list_selection(self: Handle<Self>, app: &mut App, id: Option<&str>) {
680        let old = self.selected_nodes(app);
681        let new: Vec<String> = id.map(str::to_owned).into_iter().collect();
682        if old == new {
683            return;
684        }
685        let removed = old
686            .iter()
687            .filter(|node| !new.contains(node))
688            .cloned()
689            .collect();
690        let added = new
691            .iter()
692            .filter(|node| !old.contains(node))
693            .cloned()
694            .collect();
695        self.request_selection(app, new, added, removed);
696    }
697
698    /// The selection a node leaving the rows clears in Single mode: ListView unselects a removed
699    /// item, and TreeView follows its `SelectedItem`.
700    fn deselect_if_hidden(self: Handle<Self>, app: &mut App, before: &Rows) {
701        if let Some(selected) = self.list_selection(app)
702            && before.index_of(&selected).is_some()
703            && app.get(self).rows.index_of(&selected).is_none()
704        {
705            self.set_list_selection(app, None);
706        }
707    }
708
709    /// `TreeViewItem::OnCheckToggle`: the check box of a row in Multiple mode changed, and
710    /// `SelectByIndex` applies ViewModel's rules.
711    fn check_toggled(self: Handle<Self>, app: &mut App, id: &str, is_checked: Option<bool>) {
712        let state = match is_checked {
713            Some(true) => NodeSelectionState::Selected,
714            Some(false) => NodeSelectionState::UnSelected,
715            None => NodeSelectionState::PartialSelected,
716        };
717        self.update_multiple_selection(app, id, state);
718    }
719
720    /// `ViewModel::SelectByIndex` between `BeginSelectionChanges` and `EndSelectionChanges`,
721    /// which raises `SelectionChanged` when anything changed.
722    fn update_multiple_selection(
723        self: Handle<Self>,
724        app: &mut App,
725        id: &str,
726        state: NodeSelectionState,
727    ) {
728        let tree = app.get(self).tree.clone();
729        if !tree.contains(id) {
730            return;
731        }
732        let selected = self.selected_nodes(app);
733        let mut change = SelectionChange::new(&tree, &selected);
734        change.update_selection(id, state);
735        if !change.added.is_empty() || !change.removed.is_empty() {
736            let SelectionChange {
737                selected,
738                added,
739                removed,
740                ..
741            } = change;
742            self.request_selection(app, selected, added, removed);
743        }
744    }
745
746    /// Each node's state in Multiple mode, as the check boxes draw it.
747    fn multiple_selection_states(
748        self: Handle<Self>,
749        app: &App,
750    ) -> HashMap<String, NodeSelectionState> {
751        let tree = app.get(self).tree.clone();
752        view_model::selection_states(&tree, &self.selected_nodes(app))
753    }
754
755    // MARK: Expansion and moves
756
757    /// `TreeViewNode::IsExpanded` set by the tree: ViewModel adds or removes the node's
758    /// descendants from the rows, then TreeView raises `Expanding` or `Collapsed`.
759    fn set_node_expanded(self: Handle<Self>, app: &mut App, id: &str, expanded: bool) {
760        let tree = app.get(self).tree.clone();
761        if !tree.contains(id) || tree.is_expanded(id) == expanded {
762            return;
763        }
764        let before = app.get(self).rows.clone();
765        let state = app.get_mut(self);
766        state.requested_expansion.insert(id.to_owned(), expanded);
767        Rc::make_mut(&mut state.tree).set_expanded(id, expanded);
768        state.rows = state.tree.rows();
769        if !expanded {
770            self.deselect_if_hidden(app, &before);
771        }
772        self.raise_expansion(app, id, expanded);
773        self.set_state(app, |_| {});
774    }
775
776    /// Raises `Expanding` or `Collapsed`.
777    fn raise_expansion(self: Handle<Self>, app: &mut App, id: &str, expanded: bool) {
778        let node = id.to_owned();
779        if expanded {
780            if let Some(handler) = self.widget(app).expanding.clone() {
781                self.raise(app, move |app| {
782                    handler(app, TreeViewExpandingEventArgs { node: node.clone() })
783                });
784            }
785        } else if let Some(handler) = self.widget(app).collapsed.clone() {
786            self.raise(app, move |app| {
787                handler(app, TreeViewCollapsedEventArgs { node: node.clone() })
788            });
789        }
790    }
791
792    /// Asks the application for the moves of `plan` and shows them until it answers: the moved
793    /// nodes leave the rows, which in Single mode unselects the selected one among them, and the
794    /// parents the moves leave without children collapse.
795    fn request_moves(self: Handle<Self>, app: &mut App, plan: MovePlan) {
796        if plan.moves.is_empty() && plan.collapsed.is_empty() {
797            return;
798        }
799        let before_rows = app.get(self).rows.clone();
800        let before_tree = app.get(self).tree.clone();
801        let state = app.get_mut(self);
802        let tree = Rc::make_mut(&mut state.tree);
803        for node_move in &plan.moves {
804            tree.move_node(
805                &node_move.node,
806                node_move.new_parent.as_deref(),
807                node_move.index,
808            );
809        }
810        for id in &plan.collapsed {
811            tree.set_expanded(id, false);
812        }
813        state.rows = state.tree.rows();
814        for id in &plan.collapsed {
815            state.requested_expansion.insert(id.clone(), false);
816        }
817        if !plan.moves.is_empty()
818            && let Some(handler) = self.widget(app).move_requested.clone()
819        {
820            let args = TreeViewMoveRequestedEventArgs {
821                moves: plan.moves.clone(),
822            };
823            self.raise(app, move |app| handler(app, args.clone()));
824        }
825        if let Some(selected) = self.list_selection(app)
826            && before_rows.index_of(&selected).is_some()
827            && plan
828                .moves
829                .iter()
830                .any(|node_move| before_tree.is_within(&selected, &node_move.node))
831        {
832            self.set_list_selection(app, None);
833        }
834        for id in &plan.collapsed {
835            self.raise_expansion(app, id, false);
836        }
837        self.set_state(app, |_| {});
838    }
839
840    // MARK: Focus
841
842    /// The focus of the node's row, made the first time it is asked for.
843    fn item_focus_node(self: Handle<Self>, app: &mut App, id: &str) -> Ref<FocusNode> {
844        if let Some(node) = app.get(self).item_focus.get(id) {
845            return node.clone();
846        }
847        let node = FocusNode::new(app);
848        app.get_mut(self)
849            .item_focus
850            .insert(id.to_owned(), node.clone());
851        node
852    }
853
854    /// The key of the node's row.
855    fn row_key(self: Handle<Self>, app: &mut App, id: &str) -> GlobalKey {
856        app.get_mut(self)
857            .row_keys
858            .entry(id.to_owned())
859            .or_insert_with(GlobalKey::new)
860            .clone()
861    }
862
863    /// `ListViewBase::FocusItem`: the row becomes the last focused and takes the focus once it
864    /// is built.
865    fn focus_item(self: Handle<Self>, app: &mut App, id: &str, state: FocusState) {
866        if !app.get(self).tree.contains(id) {
867            return;
868        }
869        let node = self.item_focus_node(app, id);
870        let tree_state = app.get_mut(self);
871        tree_state.last_focused = Some(id.to_owned());
872        tree_state.focus_epoch += 1;
873        let epoch = tree_state.focus_epoch;
874        FocusState::name(app, node.as_node(), state);
875        if node.has_primary_focus(app) {
876            self.set_state(app, |_| {});
877            return;
878        }
879        self.request_item_focus(app, id.to_owned(), node, epoch, 0);
880    }
881
882    /// Requests focus for a row, retrying for a few frames while the list builds it.
883    fn request_item_focus(
884        self: Handle<Self>,
885        app: &mut App,
886        id: String,
887        node: Ref<FocusNode>,
888        epoch: u64,
889        attempt: u32,
890    ) {
891        if node.as_node().context(app).is_some() {
892            if let Some(row) = app.get(self).rows.index_of(&id) {
893                self.scroll_into_view(app, row);
894            }
895            node.request_focus(app, None);
896            return;
897        }
898        if attempt < 3 {
899            self.after_frame(app, move |app| {
900                if app.get(self).focus_epoch == epoch {
901                    self.request_item_focus(app, id.clone(), node.clone(), epoch, attempt + 1);
902                }
903            });
904        }
905    }
906
907    /// `SetFocusedItem` with the row scrolled into view when asked.
908    fn set_focused_row(
909        self: Handle<Self>,
910        app: &mut App,
911        row: usize,
912        scroll: bool,
913        state: FocusState,
914    ) {
915        let Some(id) = app.get(self).rows.get(row).map(str::to_owned) else {
916            return;
917        };
918        if scroll {
919            self.scroll_into_view(app, row);
920        }
921        self.focus_item(app, &id, state);
922    }
923
924    /// A row's focus changed: `ListViewBase::ItemFocused`, which records the row as the last
925    /// focused, and `ItemUnfocused`.
926    fn item_focus_changed(self: Handle<Self>, app: &mut App, id: &str, focused: bool) {
927        if focused {
928            let tree_state = app.get_mut(self);
929            tree_state.focused = Some(id.to_owned());
930            tree_state.last_focused = Some(id.to_owned());
931        } else if app.get(self).focused.as_deref() == Some(id) {
932            app.get_mut(self).focused = None;
933        }
934        self.set_state(app, |_| {});
935    }
936
937    /// The row Tab reaches: TreeViewList's `TabNavigation="Once"` makes the list one tab stop,
938    /// entered at the last focused row, else the selected one, else the first.
939    fn tab_stop(self: Handle<Self>, app: &App) -> Option<String> {
940        let state = app.get(self);
941        let rows = &state.rows;
942        state
943            .last_focused
944            .clone()
945            .filter(|id| rows.index_of(id).is_some())
946            .or_else(|| {
947                self.list_selection(app)
948                    .filter(|id| rows.index_of(id).is_some())
949            })
950            .or_else(|| rows.get(0).map(str::to_owned))
951    }
952
953    // MARK: Pointer
954
955    /// A press went down on a part of a row. A press handled by the chevron or the check box
956    /// neither invokes nor drags the row.
957    fn part_pressed(self: Handle<Self>, app: &mut App, id: &str, part: PressedPart, pointer: i64) {
958        let state = app.get_mut(self);
959        let same_press = state
960            .pressed_part
961            .as_ref()
962            .is_some_and(|(pressed, _, down)| pressed == id && *down == pointer);
963        if part != PressedPart::Item || !same_press {
964            state.pressed_part = Some((id.to_owned(), part, pointer));
965        }
966    }
967
968    /// Whether the last press on the row went down on `part`.
969    fn pressed_part_is(self: Handle<Self>, app: &App, id: &str, part: PressedPart) -> bool {
970        app.get(self)
971            .pressed_part
972            .as_ref()
973            .is_some_and(|(pressed, pressed_part, _)| pressed == id && *pressed_part == part)
974    }
975
976    /// `TreeViewItem::OnExpandCollapseChevronPointerPressed`: the node's `IsExpanded` toggles,
977    /// whether the chevron shows or not.
978    fn chevron_pressed(self: Handle<Self>, app: &mut App, id: &str) {
979        if self.is_in_drag(app) {
980            return;
981        }
982        let expanded = app.get(self).tree.is_expanded(id);
983        self.set_node_expanded(app, id, !expanded);
984    }
985
986    /// `ListViewBaseItem::DoTapInteraction`: a click is the primary gesture, a click with Ctrl
987    /// the secondary.
988    fn item_tapped(self: Handle<Self>, app: &mut App, id: &str) {
989        if self.is_in_drag(app) || !app.get(self).tree.contains(id) {
990            return;
991        }
992        if Modifiers::of(app).control {
993            self.secondary_gesture(app, id, false);
994        } else {
995            self.primary_gesture(app, id, false);
996        }
997    }
998
999    /// `ListViewBaseItem::OnRightTapped`: the row takes the focus.
1000    fn item_right_tapped(self: Handle<Self>, app: &mut App, id: &str) {
1001        let state = FocusState::coerce_programmatic(app);
1002        self.focus_item(app, id, state);
1003    }
1004
1005    /// `OnItemPrimaryInteractionGesture` with `IsItemClickEnabled`, which TreeViewList sets: the
1006    /// row takes the focus, `ItemInvoked` is raised, and in Single mode the row is selected.
1007    fn primary_gesture(self: Handle<Self>, app: &mut App, id: &str, keyboard: bool) {
1008        let state = if keyboard {
1009            FocusState::Keyboard
1010        } else {
1011            FocusState::Pointer
1012        };
1013        self.focus_item(app, id, state);
1014        self.raise_item_invoked(app, id);
1015        if self.mode(app) == TreeViewSelectionMode::Single {
1016            self.set_list_selection(app, Some(id));
1017        }
1018    }
1019
1020    /// `OnItemSecondaryInteractionGesture`: `ItemInvoked` is raised, then in Single mode the row
1021    /// takes the focus and its selection toggles.
1022    fn secondary_gesture(self: Handle<Self>, app: &mut App, id: &str, keyboard: bool) {
1023        self.raise_item_invoked(app, id);
1024        if self.mode(app) == TreeViewSelectionMode::Single {
1025            let state = if keyboard {
1026                FocusState::Keyboard
1027            } else {
1028                FocusState::Pointer
1029            };
1030            self.focus_item(app, id, state);
1031            let selected = self.list_selection(app).as_deref() == Some(id);
1032            self.set_list_selection(app, (!selected).then_some(id));
1033        }
1034    }
1035
1036    /// `TreeView::OnItemClick`.
1037    fn raise_item_invoked(self: Handle<Self>, app: &mut App, id: &str) {
1038        if let Some(handler) = self.widget(app).item_invoked.clone() {
1039            let args = TreeViewItemInvokedEventArgs {
1040                invoked_item: id.to_owned(),
1041            };
1042            self.raise(app, move |app| handler(app, args.clone()));
1043        }
1044    }
1045
1046    /// A row's container mounted or unmounted in the lazy list.
1047    fn row_realized(self: Handle<Self>, app: &mut App, id: &str, realized: bool) {
1048        if !app.contains(self) {
1049            return;
1050        }
1051        let state = app.get_mut(self);
1052        if realized {
1053            state.realized.insert(id.to_owned());
1054        } else {
1055            state.realized.remove(id);
1056        }
1057    }
1058
1059    /// A row reported its size.
1060    fn row_measured(self: Handle<Self>, app: &mut App, id: &str, size: Size) {
1061        if !app.contains(self) {
1062            return;
1063        }
1064        let state = app.get_mut(self);
1065        state.heights.insert(id.to_owned(), size.height());
1066        state.widths.insert(id.to_owned(), size.width());
1067    }
1068
1069    // MARK: Keyboard
1070
1071    /// The keys of the focused row, as `TreeViewItem::OnKeyDown`, `ListViewBaseItem::OnKeyDown`
1072    /// and `ListViewBase::OnKeyDown` take them in turn.
1073    fn on_key(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
1074        if !matches!(event, KeyEvent::Down(_) | KeyEvent::Repeat(_)) {
1075            return KeyEventResult::Ignored;
1076        }
1077        let Some(id) = app.get(self).focused.clone() else {
1078            return KeyEventResult::Ignored;
1079        };
1080        if !app.get(self).tree.contains(&id) || app.get(self).rows.index_of(&id).is_none() {
1081            return KeyEventResult::Ignored;
1082        }
1083        // During a drag, the list takes every key.
1084        if self.is_in_drag(app) {
1085            return KeyEventResult::Handled;
1086        }
1087        let key = event.logical_key();
1088        let modifiers = Modifiers::of(app);
1089        let handled = self.item_key_down(app, &id, key, modifiers)
1090            || self.list_view_item_key_down(key, modifiers)
1091            || self.list_key_down(app, &id, key, modifiers);
1092        if handled {
1093            KeyEventResult::Handled
1094        } else {
1095            KeyEventResult::Ignored
1096        }
1097    }
1098
1099    /// `TreeViewItem::OnKeyDown`: Shift+Alt with an arrow reorders, an arrow alone expands,
1100    /// collapses or moves to the parent or first child, and Space in Multiple mode toggles the
1101    /// check box.
1102    fn item_key_down(
1103        self: Handle<Self>,
1104        app: &mut App,
1105        id: &str,
1106        key: LogicalKeyboardKey,
1107        modifiers: Modifiers,
1108    ) -> bool {
1109        let directional = is_directional(key);
1110        if directional
1111            && modifiers.shift
1112            && modifiers.alt
1113            && !modifiers.control
1114            && self.widget(app).can_reorder_items
1115        {
1116            self.keyboard_reorder(app, id, key);
1117            return true;
1118        }
1119        if directional && !modifiers.shift && !modifiers.alt && !modifiers.control {
1120            return self.expand_collapse_key(app, id, key);
1121        }
1122        if key == LogicalKeyboardKey::SPACE && self.mode(app) == TreeViewSelectionMode::Multiple {
1123            let selected = self.multiple_selection_states(app).get(id).copied()
1124                == Some(NodeSelectionState::Selected);
1125            self.check_toggled(app, id, Some(!selected));
1126            return true;
1127        }
1128        false
1129    }
1130
1131    /// `ListViewBaseItem::OnKeyDown`: Shift+Alt with an arrow is ListView's keyboard reorder,
1132    /// which does nothing for a tree that cannot reorder, and takes the key.
1133    fn list_view_item_key_down(
1134        self: Handle<Self>,
1135        key: LogicalKeyboardKey,
1136        modifiers: Modifiers,
1137    ) -> bool {
1138        is_directional(key) && modifiers.alt && modifiers.shift && !modifiers.control
1139    }
1140
1141    /// `TreeViewItem::HandleReorder`: Up, or Left past the first row, moves the node before its
1142    /// previous sibling; Down or Right, short of the last row, after its next sibling.
1143    fn keyboard_reorder(self: Handle<Self>, app: &mut App, id: &str, key: LogicalKeyboardKey) {
1144        let Some(row) = app.get(self).rows.index_of(id) else {
1145            return;
1146        };
1147        let last = app.get(self).rows.len() - 1;
1148        let forward = if key == LogicalKeyboardKey::ARROW_UP
1149            || (key == LogicalKeyboardKey::ARROW_LEFT && row != 0)
1150        {
1151            false
1152        } else if (key == LogicalKeyboardKey::ARROW_DOWN || key == LogicalKeyboardKey::ARROW_RIGHT)
1153            && row != last
1154        {
1155            true
1156        } else {
1157            return;
1158        };
1159        let tree = app.get(self).tree.clone();
1160        if let Some(plan) = tree.plan_reorder(id, forward) {
1161            self.request_moves(app, plan);
1162            self.focus_item(app, id, FocusState::Keyboard);
1163        }
1164    }
1165
1166    /// `TreeViewItem::HandleExpandCollapse`, with Left and Right swapped right to left.
1167    fn expand_collapse_key(
1168        self: Handle<Self>,
1169        app: &mut App,
1170        id: &str,
1171        key: LogicalKeyboardKey,
1172    ) -> bool {
1173        let rtl = Directionality::maybe_of(app, self.context(app)) == Some(TextDirection::Rtl);
1174        let (collapse, expand) = if rtl {
1175            (
1176                LogicalKeyboardKey::ARROW_RIGHT,
1177                LogicalKeyboardKey::ARROW_LEFT,
1178            )
1179        } else {
1180            (
1181                LogicalKeyboardKey::ARROW_LEFT,
1182                LogicalKeyboardKey::ARROW_RIGHT,
1183            )
1184        };
1185        let tree = app.get(self).tree.clone();
1186        let expanded = tree.is_expanded(id);
1187        if key == collapse {
1188            if expanded {
1189                self.set_node_expanded(app, id, false);
1190                self.focus_item(app, id, FocusState::Keyboard);
1191                return true;
1192            }
1193            // A root node's parent is the tree's hidden root, which has no row.
1194            if let Some(parent) = tree.parent(id)
1195                && let Some(row) = app.get(self).rows.index_of(parent)
1196            {
1197                self.set_focused_row(app, row, true, FocusState::Keyboard);
1198                return true;
1199            }
1200        } else if key == expand {
1201            if !expanded && tree.has_children(id) {
1202                self.set_node_expanded(app, id, true);
1203                return true;
1204            }
1205            if let Some(child) = tree.node(id).children.first()
1206                && let Some(row) = app.get(self).rows.index_of(child)
1207            {
1208                self.set_focused_row(app, row, true, FocusState::Keyboard);
1209                return true;
1210            }
1211        }
1212        false
1213    }
1214
1215    /// `ListViewBase::OnKeyDown`: Enter and Space invoke, Ctrl+Space toggles the selection, and
1216    /// the navigation keys move the focus, and in Single mode without Ctrl the selection with it.
1217    fn list_key_down(
1218        self: Handle<Self>,
1219        app: &mut App,
1220        id: &str,
1221        key: LogicalKeyboardKey,
1222        modifiers: Modifiers,
1223    ) -> bool {
1224        match key {
1225            LogicalKeyboardKey::ENTER | LogicalKeyboardKey::NUMPAD_ENTER => {
1226                self.primary_gesture(app, id, true);
1227                true
1228            }
1229            // Alt+Space opens the window's menu.
1230            LogicalKeyboardKey::SPACE if !modifiers.alt => {
1231                if modifiers.control {
1232                    self.secondary_gesture(app, id, true);
1233                } else {
1234                    self.primary_gesture(app, id, true);
1235                }
1236                true
1237            }
1238            LogicalKeyboardKey::ARROW_UP
1239            | LogicalKeyboardKey::ARROW_DOWN
1240            | LogicalKeyboardKey::ARROW_LEFT
1241            | LogicalKeyboardKey::ARROW_RIGHT
1242            | LogicalKeyboardKey::HOME
1243            | LogicalKeyboardKey::END
1244            | LogicalKeyboardKey::PAGE_UP
1245            | LogicalKeyboardKey::PAGE_DOWN => self.keyboard_navigation(app, id, key, modifiers),
1246            _ => false,
1247        }
1248    }
1249
1250    /// `OnKeyboardNavigation` on the vertical ItemsStackPanel, then the selection and focus that
1251    /// follow. A key that moves to no other row scrolls the list instead and is not taken.
1252    fn keyboard_navigation(
1253        self: Handle<Self>,
1254        app: &mut App,
1255        id: &str,
1256        key: LogicalKeyboardKey,
1257        modifiers: Modifiers,
1258    ) -> bool {
1259        let rows = app.get(self).rows.clone();
1260        let Some(row) = rows.index_of(id) else {
1261            return false;
1262        };
1263        let last = rows.len() - 1;
1264        let target = match key {
1265            LogicalKeyboardKey::ARROW_UP => row.checked_sub(1),
1266            LogicalKeyboardKey::ARROW_DOWN => (row < last).then_some(row + 1),
1267            LogicalKeyboardKey::HOME => Some(0),
1268            LogicalKeyboardKey::END => Some(last),
1269            LogicalKeyboardKey::PAGE_UP => self.page_target(app, row, false),
1270            LogicalKeyboardKey::PAGE_DOWN => self.page_target(app, row, true),
1271            // Left and Right run across a vertical panel.
1272            _ => None,
1273        }
1274        .filter(|target| *target != row);
1275        let Some(target) = target else {
1276            self.scroll_in_direction(app, key);
1277            return false;
1278        };
1279        if self.mode(app) == TreeViewSelectionMode::Single && !modifiers.control {
1280            let target_id = rows.get(target).unwrap().to_owned();
1281            self.set_list_selection(app, Some(&target_id));
1282        }
1283        self.set_focused_row(app, target, true, FocusState::Keyboard);
1284        true
1285    }
1286
1287    /// `ElementScrollViewerScrollInDirection`: a line for Up and Down, a page for Page Up and Page
1288    /// Down, and the ends for Home and End.
1289    fn scroll_in_direction(self: Handle<Self>, app: &mut App, key: LogicalKeyboardKey) {
1290        let scroll = self.scroll(app);
1291        let metrics = scroll.metrics(app);
1292        let offset = match key {
1293            LogicalKeyboardKey::ARROW_UP => metrics.offset - LINE_DELTA,
1294            LogicalKeyboardKey::ARROW_DOWN => metrics.offset + LINE_DELTA,
1295            LogicalKeyboardKey::PAGE_UP => metrics.offset - metrics.viewport_length,
1296            LogicalKeyboardKey::PAGE_DOWN => metrics.offset + metrics.viewport_length,
1297            LogicalKeyboardKey::HOME => 0.0,
1298            LogicalKeyboardKey::END => metrics.scrollable_length,
1299            _ => return,
1300        };
1301        scroll.change_view(app, offset, true);
1302    }
1303
1304    // MARK: Geometry
1305
1306    /// The list's viewport, in global coordinates.
1307    fn viewport_rect(self: Handle<Self>, app: &mut App) -> Option<Rect> {
1308        let key = app.get(self).viewport_key.clone();
1309        let render = key
1310            .current_context(app)?
1311            .find_render_object(app)?
1312            .as_box()?;
1313        let origin = render.local_to_global(app, Offset::ZERO, None);
1314        Some(origin & render.size(app))
1315    }
1316
1317    /// Where a built row's container is laid out, before a drag displaces it, in global
1318    /// coordinates.
1319    fn row_rect(self: Handle<Self>, app: &mut App, id: &str) -> Option<Rect> {
1320        let key = app.get(self).row_keys.get(id)?.clone();
1321        let render = key
1322            .current_context(app)?
1323            .find_render_object(app)?
1324            .as_box()?;
1325        let origin = render.local_to_global(app, Offset::ZERO, None);
1326        Some(origin & render.size(app))
1327    }
1328
1329    /// A row's height, as last laid out, or the height of a row of one line of text.
1330    fn row_height(self: Handle<Self>, app: &App, id: &str) -> f64 {
1331        app.get(self)
1332            .heights
1333            .get(id)
1334            .copied()
1335            .unwrap_or(app.get(self).row_estimate)
1336    }
1337
1338    /// Each row's top relative to the top of the viewport: the built rows where they are laid
1339    /// out, the others counted from them by their heights.
1340    fn row_tops(self: Handle<Self>, app: &mut App) -> Option<Vec<f64>> {
1341        let viewport = self.viewport_rect(app)?;
1342        let rows = app.get(self).rows.clone();
1343        let anchor = app
1344            .get(self)
1345            .realized
1346            .clone()
1347            .into_iter()
1348            .filter_map(|id| Some((rows.index_of(&id)?, id)))
1349            .min_by_key(|(row, _)| *row)?;
1350        let anchor_top = self.row_rect(app, &anchor.1)?.top - viewport.top;
1351        let heights: Vec<f64> = rows
1352            .ids()
1353            .iter()
1354            .map(|id| self.row_height(app, id))
1355            .collect();
1356        let mut tops = vec![0.0; rows.len()];
1357        tops[anchor.0] = anchor_top;
1358        for row in anchor.0 + 1..rows.len() {
1359            tops[row] = tops[row - 1] + heights[row - 1];
1360        }
1361        for row in (0..anchor.0).rev() {
1362            tops[row] = tops[row + 1] - heights[row];
1363        }
1364        Some(tops)
1365    }
1366
1367    /// `ScrollIntoView` with the default alignment: the least scroll that shows the row.
1368    fn scroll_into_view(self: Handle<Self>, app: &mut App, row: usize) {
1369        let scroll = self.scroll(app);
1370        let viewport = scroll.metrics(app).viewport_length;
1371        let Some(id) = app.get(self).rows.get(row).map(str::to_owned) else {
1372            return;
1373        };
1374        let Some(tops) = self.row_tops(app) else {
1375            return;
1376        };
1377        let top = tops[row];
1378        let bottom = top + self.row_height(app, &id);
1379        if top < 0.0 {
1380            scroll.scroll_by(app, top, true);
1381        } else if bottom > viewport {
1382            scroll.scroll_by(app, (bottom - viewport).min(top), true);
1383        }
1384    }
1385
1386    /// `GetTargetIndexFromNavigationActionByPage`: the last row fully in view in the direction
1387    /// of travel, or when the row already is, the last one a page further; a row out of view is
1388    /// first brought to the edge it pages from.
1389    fn page_target(self: Handle<Self>, app: &mut App, source: usize, down: bool) -> Option<usize> {
1390        let metrics = self.scroll(app).metrics(app);
1391        let viewport = metrics.viewport_length;
1392        let tops = self.row_tops(app)?;
1393        let rows = app.get(self).rows.clone();
1394        let heights: Vec<f64> = rows
1395            .ids()
1396            .iter()
1397            .map(|id| self.row_height(app, id))
1398            .collect();
1399        let count = rows.len();
1400        // The scrolls the list can make from where it is.
1401        let clamp =
1402            |delta: f64| delta.clamp(-metrics.offset, metrics.scrollable_length - metrics.offset);
1403        // `GetLastVisibleContainer` with the window scrolled by `delta`: fully in view, or for a
1404        // row taller than the window, partly.
1405        let last_visible = |delta: f64| {
1406            let fully = |row: &usize| {
1407                tops[*row] - delta >= -0.5 && tops[*row] - delta + heights[*row] <= viewport + 0.5
1408            };
1409            let partly = |row: &usize| {
1410                tops[*row] - delta < viewport && tops[*row] - delta + heights[*row] > 0.0
1411            };
1412            if down {
1413                (0..count)
1414                    .rev()
1415                    .find(fully)
1416                    .or_else(|| (0..count).rev().find(partly))
1417            } else {
1418                (0..count).find(fully).or_else(|| (0..count).find(partly))
1419            }
1420        };
1421        let in_view = tops[source] < viewport && tops[source] + heights[source] > 0.0;
1422        if !in_view {
1423            // `ScrollItemIntoView` with the leading alignment, then a page from there.
1424            let leading = clamp(tops[source]);
1425            let page = (if down { viewport } else { -viewport }).clamp(
1426                -(metrics.offset + leading),
1427                metrics.scrollable_length - metrics.offset - leading,
1428            );
1429            return last_visible(leading + page);
1430        }
1431        let last = last_visible(0.0)?;
1432        let past_last = if down { source >= last } else { source <= last };
1433        let at_end = if down {
1434            source == count - 1
1435        } else {
1436            source == 0
1437        };
1438        if !past_last || at_end {
1439            return Some(last);
1440        }
1441        let mut last = last_visible(clamp(if down { viewport } else { -viewport }))?;
1442        if source == last {
1443            if down && last + 1 < count {
1444                last += 1;
1445            } else if !down && last > 0 {
1446                last -= 1;
1447            }
1448        }
1449        Some(last)
1450    }
1451
1452    // MARK: Template
1453
1454    /// The row container for the node `id`, a row of the list with `focus`, or else the drag
1455    /// preview.
1456    fn container(
1457        self: Handle<Self>,
1458        app: &mut App,
1459        id: &str,
1460        focus: Option<ItemFocus>,
1461    ) -> TreeViewItemContainer {
1462        let widget = self.widget(app).clone();
1463        let tree = app.get(self).tree.clone();
1464        let node = tree.node(id);
1465        let multi_select = (widget.selection_mode == TreeViewSelectionMode::Multiple).then(|| {
1466            self.multiple_selection_states(app)
1467                .get(id)
1468                .copied()
1469                .unwrap_or(NodeSelectionState::UnSelected)
1470        });
1471        TreeViewItemContainer {
1472            owner: self,
1473            id: id.to_owned(),
1474            content: node.content.clone(),
1475            depth: tree.depth(id),
1476            has_children: tree.has_children(id),
1477            is_expanded: node.is_expanded,
1478            is_enabled: widget.is_enabled,
1479            multi_select,
1480            is_selected: self.mode(app) == TreeViewSelectionMode::Single
1481                && self.is_node_selected(app, id),
1482            drag: self.item_drag(app, id, focus.is_none()),
1483            focus,
1484        }
1485    }
1486
1487    /// The row at `index` of the list: the container, displaced and draggable, measured where it
1488    /// is laid out.
1489    fn row(
1490        self: Handle<Self>,
1491        app: &mut App,
1492        index: usize,
1493        tab_stop: Option<&str>,
1494    ) -> Option<WidgetRef> {
1495        let id = app.get(self).rows.get(index)?.to_owned();
1496        let node = self.item_focus_node(app, &id);
1497        let keyboard = FocusState::current(app).shows_focus_visual();
1498        let state = app.get(self);
1499        let focus = ItemFocus {
1500            node,
1501            is_tab_stop: tab_stop == Some(id.as_str()),
1502            shows_focus_visual: state.focused.as_deref() == Some(id.as_str()) && keyboard,
1503        };
1504        let container = self.container(app, &id, Some(focus));
1505        let row = self.drag_source(app, &id, index, container);
1506        let key = self.row_key(app, &id);
1507        let measured = id.clone();
1508        Some(
1509            KeyedSubtree::new(
1510                SizeObserver::new(
1511                    row,
1512                    Rc::new(move |app, _, size| self.row_measured(app, &measured, size)),
1513                )
1514                .key(key.into()),
1515            )
1516            .key(ValueKey::new(id).into())
1517            .into_widget(),
1518        )
1519    }
1520
1521    /// `ListControl`: TreeViewList's `ScrollViewer` around the lazy list of rows. Without a bound
1522    /// on its height, the list is as tall as its rows.
1523    fn list(self: Handle<Self>, app: &mut App, shrink_wrap: bool) -> WidgetRef {
1524        let scroll = app
1525            .get(self)
1526            .scroll
1527            .clone()
1528            .expect("an initialized TreeView");
1529        let ids = app.get(self).rows.ids().to_vec();
1530        let tab_stop = self.tab_stop(app);
1531        let list = ListView::builder(move |app, _, index| {
1532            self.row(app, index as usize, tab_stop.as_deref())
1533        })
1534        .item_count(ids.len() as i32)
1535        .find_child_index_callback(Rc::new(move |key| {
1536            (key.key() as &dyn std::any::Any)
1537                .downcast_ref::<ValueKey<String>>()
1538                .and_then(|key| ids.iter().position(|id| *id == key.value))
1539                .map(|index| index as i32)
1540        }))
1541        .build()
1542        .controller(scroll.native_controller(app))
1543        .shrink_wrap(shrink_wrap)
1544        .padding(EdgeInsetsGeometry::ZERO);
1545        let viewport = KeyedSubtree::new(list).key(app.get(self).viewport_key.clone().into());
1546        ScrollBarViewport::scroller(scroll, viewport).into_widget()
1547    }
1548}
1549
1550impl State for TreeViewState {
1551    type Widget = TreeView;
1552    waft_widgets::state_accessors!();
1553
1554    fn init_state(self: Handle<Self>, app: &mut App) {
1555        // Programmatic focus shows the focus visual only after keyboard input.
1556        InputDevice::initialize(app);
1557        let scroll = ScrollViewportController::new(app);
1558        app.get_mut(self).scroll = Some(scroll);
1559        let ticker = SingleTickerProviderStateMixin::create_ticker(
1560            self,
1561            app,
1562            FrameCallback::new(move |app, elapsed| self.edge_scroll_tick(app, elapsed)),
1563        );
1564        app.get_mut(self).ticker = Some(ticker.clone());
1565    }
1566
1567    fn did_update_widget(self: Handle<Self>, app: &mut App, _old: &TreeView) {
1568        app.get_mut(self).building = true;
1569        let before = app.get(self).rows.clone();
1570        let state = app.get_mut(self);
1571        state.requested_expansion.clear();
1572        state.requested_selection = None;
1573        self.sync_tree(app);
1574        // A selected node the application's change hides is no longer the list's selection.
1575        if let Some(selected) = self.list_selection(app)
1576            && before.index_of(&selected).is_some()
1577            && app.get(self).rows.index_of(&selected).is_none()
1578        {
1579            self.after_frame(app, move |app| {
1580                if self.list_selection(app).as_deref() == Some(selected.as_str())
1581                    && app.get(self).rows.index_of(&selected).is_none()
1582                {
1583                    self.set_list_selection(app, None);
1584                }
1585            });
1586        }
1587        self.drag_tree_changed(app);
1588        app.get_mut(self).building = false;
1589    }
1590
1591    fn activate(self: Handle<Self>, app: &mut App) {
1592        SingleTickerProviderStateMixin::activate(self, app);
1593    }
1594
1595    fn dispose(self: Handle<Self>, app: &mut App) {
1596        self.dispose_drag(app);
1597        let state = app.get_mut(self);
1598        let scroll = state.scroll.take().expect("an initialized TreeView");
1599        let ticker = state.ticker.take().expect("an initialized TreeView");
1600        let nodes: Vec<_> = state.item_focus.drain().map(|(_, node)| node).collect();
1601        for node in nodes {
1602            node.dispose(app);
1603        }
1604        ticker.dispose(app);
1605        SingleTickerProviderStateMixin::dispose(self, app);
1606        scroll.dispose(app);
1607    }
1608
1609    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1610        let estimate = estimated_row_height(&ThemeResources::of(app, context));
1611        app.get_mut(self).row_estimate = estimate;
1612        let list = LayoutBuilder::new(move |app, _, constraints| {
1613            self.list(app, constraints.max_height.is_infinite())
1614        });
1615        let target = self.drop_target(app, list.into_widget());
1616        Focus::new(target)
1617            .can_request_focus(false)
1618            .skip_traversal(true)
1619            .on_key_event(Rc::new(move |app, _, event| self.on_key(app, event)))
1620            .into_widget()
1621    }
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626    use super::*;
1627
1628    #[test]
1629    fn a_node_is_built_collapsed_without_children() {
1630        let node = TreeViewNode::text("a", "A");
1631        assert!(!node.is_expanded && node.children.is_empty() && !node.has_unrealized_children);
1632        let node = node
1633            .children(vec![TreeViewNode::text("b", "B")])
1634            .is_expanded(true);
1635        assert_eq!(node.children.len(), 1);
1636        assert!(node.is_expanded);
1637    }
1638
1639    #[test]
1640    fn a_tree_defaults_to_single_selection_with_drag_and_reorder() {
1641        let tree = TreeView::new(Vec::new(), Vec::new(), |_, _| {});
1642        assert_eq!(tree.selection_mode, TreeViewSelectionMode::Single);
1643        assert!(tree.can_drag_items && tree.can_reorder_items && tree.allow_drop);
1644        assert!(tree.is_enabled);
1645    }
1646}