Skip to main content

waft_winui/controls/items_view/
mod.rs

1//! `ItemsView` (`controls/dev/ItemsView`: `ItemsView.cpp`, `ItemsViewInteractions.cpp` and the selectors) over Waft's lazy list: items an application builds as `ItemContainer`s, one or several selected by the selection mode's rules, the current item moved by the arrow keys, Home, End, Page Up and Page Down, and an item invoked.
2//!
3//! WinUI makes the items through an `ItemsRepeater` that can make any item on demand. Here a vertical `StackLayout` is Waft's `ListView`, which builds only what is in sight and a margin around it; an item out of that range is brought into view by its estimated offset, from the extents measured so far, and focused once built. A horizontal `StackLayout`, as `SelectorBar` uses, builds every item in a row. The view keeps the built items by index ([`ItemsViewState::register`]), and a later editor must keep that registry exact: focus, Tab and page navigation read it.
4
5mod selection;
6pub(crate) mod selection_model;
7mod selector;
8
9pub use selection::ItemsViewSource;
10pub use selector::ItemsViewSelectionMode;
11
12use crate::FocusState;
13use crate::*;
14use std::{collections::HashMap, fmt, rc::Rc};
15use waft_embedder::{Clip, Offset, Radius, Rect, Size, TextDirection};
16use waft_foundation::{App, Handle, ListenableObject, Listener, OptionRetained, Ref};
17use waft_painting::{Axis, BorderRadius, EdgeInsetsGeometry};
18use waft_rendering::MainAxisSize;
19use waft_scheduler::FrameCallback;
20use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey};
21use waft_widgets::*;
22
23/// Builds the `ItemContainer` of the item at an index: XAML's `ItemTemplate` over `ItemsSource`.
24pub type ItemsViewItemTemplate = Rc<dyn Fn(&mut App, BuildContext, usize) -> ItemContainer>;
25
26/// `ItemInvoked`: the index of the item invoked.
27pub type ItemsViewItemInvoked = Rc<dyn Fn(&mut App, usize)>;
28
29/// XAML `StackLayout`, the one `Layout` this port has: items one after another along `orientation`, `spacing` apart.
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub struct StackLayout {
32    /// `Orientation`.
33    pub orientation: Axis,
34    /// `Spacing`.
35    pub spacing: f64,
36}
37
38impl Default for StackLayout {
39    fn default() -> Self {
40        Self {
41            orientation: Axis::Vertical,
42            spacing: 0.0,
43        }
44    }
45}
46
47/// XAML `ItemsView`.
48#[derive(Clone)]
49pub struct ItemsView {
50    /// `ItemsSource` and the selection over it: the items' count, what is selected and the current item.
51    pub items_source: Ref<ItemsViewSource>,
52    /// `ItemTemplate`.
53    pub item_template: ItemsViewItemTemplate,
54    /// `Layout`.
55    pub layout: StackLayout,
56    /// `SelectionMode`.
57    pub selection_mode: ItemsViewSelectionMode,
58    /// `IsItemInvokedEnabled`.
59    pub is_item_invoked_enabled: bool,
60    /// `ItemInvoked`.
61    pub item_invoked: Option<ItemsViewItemInvoked>,
62    /// `SelectionChanged`.
63    pub selection_changed: Option<Listener>,
64    /// `Padding`: around the items, inside the scrolling.
65    pub padding: [f64; 4],
66    /// The extent of every item along a vertical stack, which lets the list place an item far away without building every item before it, as Flutter's `ListView.itemExtent` does; `None` measures each item as it is built.
67    pub item_extent: Option<f64>,
68    /// Identity retained across parent rebuilds.
69    pub key: Option<KeyRef>,
70}
71
72impl ItemsView {
73    /// Creates a view of the items of `items_source`, each the container `item_template` builds. A view whose application does not care about selection still gives a source, for the count, and sets [`selection_mode`](Self::selection_mode) to [`ItemsViewSelectionMode::None`].
74    pub fn new(
75        items_source: Ref<ItemsViewSource>,
76        item_template: impl Fn(&mut App, BuildContext, usize) -> ItemContainer + 'static,
77    ) -> Self {
78        Self {
79            items_source,
80            item_template: Rc::new(item_template),
81            layout: StackLayout::default(),
82            selection_mode: ItemsViewSelectionMode::default(),
83            is_item_invoked_enabled: false,
84            item_invoked: None,
85            selection_changed: None,
86            padding: [0.0; 4],
87            item_extent: None,
88            key: None,
89        }
90    }
91
92    /// Sets the XAML `Layout`.
93    pub fn layout(mut self, value: StackLayout) -> Self {
94        self.layout = value;
95        self
96    }
97
98    /// Sets the XAML `SelectionMode`.
99    pub fn selection_mode(mut self, value: ItemsViewSelectionMode) -> Self {
100        self.selection_mode = value;
101        self
102    }
103
104    /// Sets the XAML `IsItemInvokedEnabled`.
105    pub fn is_item_invoked_enabled(mut self, value: bool) -> Self {
106        self.is_item_invoked_enabled = value;
107        self
108    }
109
110    /// Sets the XAML `ItemInvoked` handler.
111    pub fn item_invoked(mut self, handler: impl Fn(&mut App, usize) + 'static) -> Self {
112        self.item_invoked = Some(Rc::new(handler));
113        self
114    }
115
116    /// Sets the XAML `SelectionChanged` handler.
117    pub fn selection_changed(mut self, handler: impl Fn(&mut App) + 'static) -> Self {
118        self.selection_changed = Some(Listener::new(handler));
119        self
120    }
121
122    /// Sets the XAML `Padding`.
123    pub fn padding(mut self, value: [f64; 4]) -> Self {
124        self.padding = value;
125        self
126    }
127
128    /// Gives every item the same extent along a vertical stack.
129    pub fn item_extent(mut self, value: f64) -> Self {
130        self.item_extent = Some(value);
131        self
132    }
133
134    /// Sets the identity retained across rebuilds.
135    pub fn key(mut self, key: KeyRef) -> Self {
136        self.key = Some(key);
137        self
138    }
139}
140
141impl fmt::Debug for ItemsView {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.debug_struct("ItemsView")
144            .field("items_source", &self.items_source)
145            .field("layout", &self.layout)
146            .field("selection_mode", &self.selection_mode)
147            .field("is_item_invoked_enabled", &self.is_item_invoked_enabled)
148            .finish_non_exhaustive()
149    }
150}
151
152impl StatefulWidget for ItemsView {
153    type State = ItemsViewState;
154
155    fn key(&self) -> Option<&KeyRef> {
156        self.key.as_ref()
157    }
158
159    fn create_state(&self) -> ItemsViewState {
160        ItemsViewState {
161            state: StateData::new(),
162            listening: None,
163            seen_revision: 0,
164            shown_count: 0,
165            scroll: None,
166            items: HashMap::new(),
167            extents: HashMap::new(),
168            tab_stop: None,
169            focus_epoch: 0,
170        }
171    }
172}
173
174/// An item's index and the view it is an item of, which the view puts around each container it builds.
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub(crate) struct ItemsViewItem {
177    pub(crate) index: usize,
178    pub(crate) view: Handle<ItemsViewState>,
179}
180
181impl ItemsViewItem {
182    /// The item `context` is in, if it is in an `ItemsView`.
183    pub(crate) fn of(app: &App, context: BuildContext) -> Option<ItemsViewItem> {
184        context
185            .get_inherited_widget_of_exact_type::<ItemsViewItemScope>(app)
186            .map(|scope| scope.item)
187    }
188}
189
190/// Tells the container under it which item of which view it is.
191#[derive(Debug)]
192struct ItemsViewItemScope {
193    item: ItemsViewItem,
194    child: WidgetRef,
195}
196
197impl InheritedWidget for ItemsViewItemScope {
198    fn child(&self) -> &WidgetRef {
199        &self.child
200    }
201
202    fn update_should_notify(&self, old: &Self) -> bool {
203        self.item != old.item
204    }
205}
206
207/// A container the list has built.
208#[derive(Clone, Copy, Debug)]
209struct BuiltItem {
210    container: Handle<ItemContainerState>,
211    focus: Handle<FocusNode>,
212}
213
214/// The selection the view listens to, the built items, their measured extents and the scrolling.
215pub struct ItemsViewState {
216    state: StateData<ItemsView>,
217    /// The selection listened to, and the listener.
218    listening: Option<(Ref<ItemsViewSource>, Listener)>,
219    /// The selection's revision `SelectionChanged` was last raised for.
220    seen_revision: u64,
221    /// The count the list was last built for.
222    shown_count: usize,
223    scroll: Option<Ref<ScrollViewportController>>,
224    /// The built containers by index.
225    items: HashMap<usize, BuiltItem>,
226    /// Each built item's extent along the layout, as last laid out.
227    extents: HashMap<usize, f64>,
228    /// The item Tab stops at, as last told to the containers.
229    tab_stop: Option<usize>,
230    /// Counts focus requests, so that a request waiting for its item to be built gives way to a later one.
231    focus_epoch: u64,
232}
233
234// MARK: The containers' view of the view
235
236impl ItemsViewState {
237    /// The view's `ItemsSource`, which also holds the selection over the items.
238    pub(crate) fn items_source(self: Handle<Self>, app: &App) -> Handle<ItemsViewSource> {
239        self.widget(app).items_source.handle()
240    }
241
242    fn item_count(self: Handle<Self>, app: &App) -> usize {
243        self.items_source(app).item_count(app)
244    }
245
246    pub(crate) fn is_selected(self: Handle<Self>, app: &App, index: usize) -> bool {
247        self.items_source(app).is_selected(app, index)
248    }
249
250    pub(crate) fn is_tab_stop(self: Handle<Self>, app: &App, index: usize) -> bool {
251        self.tab_stop_index(app) == Some(index)
252    }
253
254    /// `ItemsView::OnItemsRepeaterElementPrepared`'s `MultiSelectMode` for `Auto`.
255    pub(crate) fn multi_select_mode(self: Handle<Self>, app: &App) -> ItemContainerMultiSelectMode {
256        match self.widget(app).selection_mode {
257            ItemsViewSelectionMode::None | ItemsViewSelectionMode::Single => {
258                ItemContainerMultiSelectMode::Single
259            }
260            ItemsViewSelectionMode::Extended => ItemContainerMultiSelectMode::Extended,
261            ItemsViewSelectionMode::Multiple => ItemContainerMultiSelectMode::Multiple,
262        }
263    }
264
265    /// A container's `CanUserSelect`, `Auto` resolved from the selection mode.
266    pub(crate) fn can_user_select(
267        self: Handle<Self>,
268        app: &App,
269        mode: ItemContainerUserSelectMode,
270    ) -> bool {
271        match mode {
272            ItemContainerUserSelectMode::Auto => {
273                self.widget(app).selection_mode != ItemsViewSelectionMode::None
274            }
275            ItemContainerUserSelectMode::UserCanSelect => true,
276            ItemContainerUserSelectMode::UserCannotSelect => false,
277        }
278    }
279
280    /// A container's `CanUserInvoke`, `Auto` resolved from `IsItemInvokedEnabled`.
281    pub(crate) fn can_user_invoke(
282        self: Handle<Self>,
283        app: &App,
284        mode: ItemContainerUserInvokeMode,
285    ) -> bool {
286        match mode {
287            ItemContainerUserInvokeMode::Auto => self.widget(app).is_item_invoked_enabled,
288            ItemContainerUserInvokeMode::UserCanInvoke => true,
289            ItemContainerUserInvokeMode::UserCannotInvoke => false,
290        }
291    }
292
293    /// A container was built for `index`.
294    pub(crate) fn register(
295        self: Handle<Self>,
296        app: &mut App,
297        index: usize,
298        container: Handle<ItemContainerState>,
299        focus: Handle<FocusNode>,
300    ) {
301        app.get_mut(self)
302            .items
303            .insert(index, BuiltItem { container, focus });
304        self.sync_tab_stop_after_frame(app);
305    }
306
307    /// The container for `index` went, unless another has taken its place.
308    pub(crate) fn unregister(
309        self: Handle<Self>,
310        app: &mut App,
311        index: usize,
312        container: Handle<ItemContainerState>,
313    ) {
314        let items = &mut app.get_mut(self).items;
315        if items
316            .get(&index)
317            .is_some_and(|item| item.container == container)
318        {
319            items.remove(&index);
320            self.sync_tab_stop_after_frame(app);
321        }
322    }
323
324    /// `ItemsView::OnItemsViewItemContainerItemInvoked`: answers whether it handled the interaction.
325    pub(crate) fn item_container_invoked(
326        self: Handle<Self>,
327        app: &mut App,
328        index: usize,
329        container: &ItemContainer,
330        trigger: ItemContainerInteractionTrigger,
331    ) -> bool {
332        let handled = match trigger {
333            ItemContainerInteractionTrigger::PointerReleased => {
334                self.process_interaction(app, index, FocusState::Pointer)
335            }
336            ItemContainerInteractionTrigger::EnterKey
337            | ItemContainerInteractionTrigger::SpaceKey => {
338                self.process_interaction(app, index, FocusState::Keyboard)
339            }
340            ItemContainerInteractionTrigger::Tap | ItemContainerInteractionTrigger::DoubleTap => {
341                false
342            }
343        };
344        if trigger != ItemContainerInteractionTrigger::PointerReleased
345            && self.can_raise_item_invoked(app, trigger, container)
346            && let Some(invoked) = self.widget(app).item_invoked.clone()
347        {
348            invoked(app, index);
349        }
350        handled
351    }
352
353    /// `OnItemsViewElementGettingFocus`: the focused item becomes the current one.
354    pub(crate) fn item_got_focus(self: Handle<Self>, app: &mut App, index: usize) {
355        self.items_source(app)
356            .set_current_item_index(app, Some(index));
357        self.sync_tab_stop(app);
358    }
359}
360
361// MARK: Interaction
362
363impl ItemsViewState {
364    /// `ItemsView::CanRaiseItemInvoked`: invoking is on, and with a selection mode a tap or Space selects rather than invokes, and without one a double tap does nothing more than a tap.
365    fn can_raise_item_invoked(
366        self: Handle<Self>,
367        app: &App,
368        trigger: ItemContainerInteractionTrigger,
369        container: &ItemContainer,
370    ) -> bool {
371        use ItemContainerInteractionTrigger::*;
372        if !self.can_user_invoke(app, container.can_user_invoke) {
373            return false;
374        }
375        let widget = self.widget(app);
376        let none = widget.selection_mode == ItemsViewSelectionMode::None;
377        widget.is_item_invoked_enabled
378            && !(none && trigger == DoubleTap)
379            && !(!none && matches!(trigger, Tap | SpaceKey))
380    }
381
382    /// `ItemsView::ProcessInteraction`: the item becomes current and takes the focus, brought into view for a pointer, and the selector acts on it.
383    fn process_interaction(
384        self: Handle<Self>,
385        app: &mut App,
386        index: usize,
387        focus: FocusState,
388    ) -> bool {
389        let handled = self.set_current_element_index(app, index, focus);
390        if focus == FocusState::Pointer {
391            self.bring_item_into_view(app, index, None);
392        }
393        let (ctrl, shift) = modifiers(app);
394        let selection = self.items_source(app);
395        selection.interacted(app, index, ctrl, shift);
396        self.deselect_unselectable_items(app);
397        handled
398    }
399
400    /// `ApplySelectionModelSelectionChange` while processing an interaction: a built item that cannot be selected is deselected, the anchor kept.
401    fn deselect_unselectable_items(self: Handle<Self>, app: &mut App) {
402        let selection = self.items_source(app);
403        let items: Vec<(usize, BuiltItem)> = app
404            .get(self)
405            .items
406            .iter()
407            .map(|(i, item)| (*i, *item))
408            .collect();
409        for (index, item) in items {
410            let mode = item.container.widget(app).can_user_select;
411            if mode == ItemContainerUserSelectMode::UserCannotSelect
412                && selection.is_selected(app, index)
413            {
414                selection.deselect_with_anchor_preservation(app, index);
415            }
416        }
417    }
418
419    /// `SetCurrentElementIndex` with `SetFocusElementIndex`: answers whether the item took the focus.
420    fn set_current_element_index(
421        self: Handle<Self>,
422        app: &mut App,
423        index: usize,
424        focus: FocusState,
425    ) -> bool {
426        self.items_source(app)
427            .set_current_item_index(app, Some(index));
428        self.sync_tab_stop(app);
429        let Some(item) = app.get(self).items.get(&index).copied() else {
430            return false;
431        };
432        FocusState::name(app, item.focus.as_node(), focus);
433        item.focus.request_focus(app, None);
434        true
435    }
436
437    /// `ItemsView::OnKeyDown`'s Control+A and `OnItemsViewElementKeyDown`'s navigation keys.
438    fn key(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
439        if matches!(event, KeyEvent::Up(_)) {
440            return KeyEventResult::Ignored;
441        }
442        let key = event.logical_key();
443        if key == LogicalKeyboardKey::KEY_A {
444            return self.select_all_key(app);
445        }
446        match self.navigation_target(app, key) {
447            Some(Navigation::To(index)) => {
448                self.focus_by_keyboard(app, index, None);
449                KeyEventResult::Handled
450            }
451            Some(Navigation::Edge(index, alignment)) => {
452                self.focus_by_keyboard(app, index, Some(alignment));
453                KeyEventResult::Handled
454            }
455            Some(Navigation::Page(forward)) => {
456                self.page(app, forward);
457                KeyEventResult::Handled
458            }
459            None => KeyEventResult::Ignored,
460        }
461    }
462
463    /// Control+A selects every item in `Multiple` and `Extended` modes.
464    fn select_all_key(self: Handle<Self>, app: &mut App) -> KeyEventResult {
465        let mode = self.widget(app).selection_mode;
466        let multiple = matches!(
467            mode,
468            ItemsViewSelectionMode::Multiple | ItemsViewSelectionMode::Extended
469        );
470        if multiple && HardwareKeyboard::instance(app).is_control_pressed(app) {
471            self.items_source(app).select_all(app);
472            KeyEventResult::Handled
473        } else {
474            KeyEventResult::Ignored
475        }
476    }
477
478    /// `ProcessNavigationKeys` for a stack: the arrows along it move to the adjacent focusable item, Home and End to the first and last, and Page Up and Page Down page along a vertical one.
479    fn navigation_target(
480        self: Handle<Self>,
481        app: &mut App,
482        key: LogicalKeyboardKey,
483    ) -> Option<Navigation> {
484        let count = self.item_count(app);
485        if count == 0 {
486            return None;
487        }
488        let vertical = self.widget(app).layout.orientation == Axis::Vertical;
489        let rtl = Directionality::maybe_of(app, self.context(app)) == Some(TextDirection::Rtl);
490        let previous = match key {
491            LogicalKeyboardKey::ARROW_UP if vertical => Some(true),
492            LogicalKeyboardKey::ARROW_DOWN if vertical => Some(false),
493            LogicalKeyboardKey::ARROW_LEFT if !vertical => Some(!rtl),
494            LogicalKeyboardKey::ARROW_RIGHT if !vertical => Some(rtl),
495            _ => None,
496        };
497        if let Some(previous) = previous {
498            let target = self.adjacent_focusable_index(app, previous)?;
499            return Some(Navigation::To(target));
500        }
501        match key {
502            LogicalKeyboardKey::HOME => Some(Navigation::Edge(0, 0.0)),
503            LogicalKeyboardKey::END => Some(Navigation::Edge(count - 1, 1.0)),
504            LogicalKeyboardKey::PAGE_UP if vertical => Some(Navigation::Page(false)),
505            LogicalKeyboardKey::PAGE_DOWN if vertical => Some(Navigation::Page(true)),
506            _ => None,
507        }
508    }
509
510    /// `GetAdjacentFocusableElementByIndex`: the nearest item before or after the current one that can take the focus; an item not built is taken to be able to.
511    fn adjacent_focusable_index(self: Handle<Self>, app: &App, previous: bool) -> Option<usize> {
512        let count = self.item_count(app);
513        let current = self.items_source(app).current_item_index(app)?;
514        let mut index = current;
515        loop {
516            index = if previous {
517                index.checked_sub(1)?
518            } else if index + 1 < count {
519                index + 1
520            } else {
521                return None;
522            };
523            if self.is_focusable(app, index) {
524                return Some(index);
525            }
526        }
527    }
528
529    fn is_focusable(self: Handle<Self>, app: &App, index: usize) -> bool {
530        app.get(self)
531            .items
532            .get(&index)
533            .is_none_or(|item| item.container.widget(app).is_enabled)
534    }
535
536    /// `SetFocusElementIndex` with `FocusState::Keyboard` and the selector's `OnFocusedAction`: the item is brought into view, aligned when `alignment` says so, and takes the focus once built.
537    fn focus_by_keyboard(self: Handle<Self>, app: &mut App, index: usize, alignment: Option<f64>) {
538        self.bring_item_into_view(app, index, alignment);
539        let epoch = {
540            let state = app.get_mut(self);
541            state.focus_epoch += 1;
542            state.focus_epoch
543        };
544        self.focus_when_built(app, index, epoch, 0);
545    }
546
547    /// Focuses the item at `index` once the list has built it, a few frames at most, unless a later request came.
548    fn focus_when_built(self: Handle<Self>, app: &mut App, index: usize, epoch: u64, attempt: u32) {
549        if app.get(self).focus_epoch != epoch {
550            return;
551        }
552        if app.get(self).items.contains_key(&index) {
553            self.set_current_element_index(app, index, FocusState::Keyboard);
554            self.bring_item_into_view(app, index, None);
555            let (ctrl, shift) = modifiers(app);
556            self.items_source(app).focused(app, index, ctrl, shift);
557            self.deselect_unselectable_items(app);
558            return;
559        }
560        if attempt < 3 {
561            self.bring_item_into_view(app, index, None);
562            self.after_frame(app, move |app| {
563                self.focus_when_built(app, index, epoch, attempt + 1)
564            });
565        }
566    }
567
568    /// Page Up and Page Down: the last item wholly in view in that direction, or when the current item already is, the last a page further.
569    fn page(self: Handle<Self>, app: &mut App, forward: bool) {
570        let current = self.items_source(app).current_item_index(app);
571        if let Some(target) = self.last_visible_index(app, forward)
572            && Some(target) != current
573        {
574            self.focus_by_keyboard(app, target, None);
575            return;
576        }
577        let scroll = self.scroll(app);
578        let page = scroll.metrics(app).viewport_length;
579        scroll.scroll_by(app, if forward { page } else { -page }, true);
580        self.after_frame(app, move |app| {
581            if let Some(target) = self.last_visible_index(app, forward) {
582                self.focus_by_keyboard(app, target, None);
583            }
584        });
585    }
586
587    /// The built item wholly in view furthest along, or back; an item larger than the view counts when partly in view.
588    fn last_visible_index(self: Handle<Self>, app: &mut App, forward: bool) -> Option<usize> {
589        let viewport = self.viewport_rect(app)?;
590        let mut indices: Vec<usize> = app.get(self).items.keys().copied().collect();
591        indices.sort_unstable();
592        indices.retain(|index| self.is_focusable(app, *index));
593        let rects: Vec<(usize, Rect)> = indices
594            .into_iter()
595            .filter_map(|index| Some((index, self.item_rect(app, index)?)))
596            .collect();
597        let wholly =
598            |rect: &Rect| rect.top >= viewport.top - 0.5 && rect.bottom <= viewport.bottom + 0.5;
599        let partly = |rect: &Rect| rect.top < viewport.bottom && rect.bottom > viewport.top;
600        let pick = |test: &dyn Fn(&Rect) -> bool| {
601            let mut found = rects
602                .iter()
603                .filter(|(_, rect)| test(rect))
604                .map(|(index, _)| *index);
605            if forward { found.last() } else { found.next() }
606        };
607        pick(&wholly).or_else(|| pick(&partly))
608    }
609}
610
611/// Where a navigation key moves the focus.
612#[derive(Clone, Copy, Debug, PartialEq)]
613enum Navigation {
614    /// To an item, brought into view as little as it takes.
615    To(usize),
616    /// To the first or last item, aligned to that end of the view.
617    Edge(usize, f64),
618    /// A page forward or back.
619    Page(bool),
620}
621
622/// Whether Control and Shift are down, as the selectors take them.
623fn modifiers(app: &mut App) -> (bool, bool) {
624    let keyboard = HardwareKeyboard::instance(app);
625    (
626        keyboard.is_control_pressed(app),
627        keyboard.is_shift_pressed(app),
628    )
629}
630
631// MARK: Scrolling
632
633impl ItemsViewState {
634    fn scroll(self: Handle<Self>, app: &App) -> Handle<ScrollViewportController> {
635        app.get(self).scroll.handle().expect("made in `init_state`")
636    }
637
638    fn axis(self: Handle<Self>, app: &App) -> Axis {
639        self.widget(app).layout.orientation
640    }
641
642    /// `StartBringItemIntoView`: scrolls so the item is in view, its start at the view's start for an `alignment` of 0 and its end at the view's end for 1, or as little as it takes for none. An item not built is placed by the extents of the items between it and a built one.
643    fn bring_item_into_view(
644        self: Handle<Self>,
645        app: &mut App,
646        index: usize,
647        alignment: Option<f64>,
648    ) {
649        let Some((start, extent)) = self.item_offset_in_view(app, index) else {
650            return;
651        };
652        let scroll = self.scroll(app);
653        let view = scroll.metrics(app).viewport_length;
654        let end = start + extent;
655        let delta = match alignment {
656            Some(alignment) => start - alignment * (view - extent),
657            None if start < 0.0 => start,
658            None if end > view => (end - view).min(start),
659            None => return,
660        };
661        scroll.scroll_by(app, delta, true);
662    }
663
664    /// The item's start along the layout, from the start of the view, and its extent.
665    fn item_offset_in_view(self: Handle<Self>, app: &mut App, index: usize) -> Option<(f64, f64)> {
666        let viewport = self.viewport_rect(app)?;
667        let axis = self.axis(app);
668        let start_of = |rect: Rect| match axis {
669            Axis::Vertical => rect.top - viewport.top,
670            Axis::Horizontal => rect.left - viewport.left,
671        };
672        if let Some(rect) = self.item_rect(app, index) {
673            return Some((start_of(rect), self.extent(app, index)));
674        }
675        let anchor = app
676            .get(self)
677            .items
678            .keys()
679            .copied()
680            .min_by_key(|built| built.abs_diff(index))?;
681        let mut start = start_of(self.item_rect(app, anchor)?);
682        let spacing = self.widget(app).layout.spacing;
683        if index > anchor {
684            for between in anchor..index {
685                start += self.extent(app, between) + spacing;
686            }
687        } else {
688            for between in index..anchor {
689                start -= self.extent(app, between) + spacing;
690            }
691        }
692        Some((start, self.extent(app, index)))
693    }
694
695    /// An item's extent: the view's `item_extent`, else as last laid out, else the average of those measured.
696    fn extent(self: Handle<Self>, app: &App, index: usize) -> f64 {
697        if let Some(extent) = self.widget(app).item_extent {
698            return extent;
699        }
700        let extents = &app.get(self).extents;
701        extents.get(&index).copied().unwrap_or_else(|| {
702            if extents.is_empty() {
703                0.0
704            } else {
705                extents.values().sum::<f64>() / extents.len() as f64
706            }
707        })
708    }
709
710    fn item_measured(self: Handle<Self>, app: &mut App, index: usize, size: Size) {
711        if !app.contains(self) {
712            return;
713        }
714        let extent = match self.axis(app) {
715            Axis::Vertical => size.height(),
716            Axis::Horizontal => size.width(),
717        };
718        app.get_mut(self).extents.insert(index, extent);
719    }
720
721    /// Where a built item is laid out, in global coordinates.
722    fn item_rect(self: Handle<Self>, app: &mut App, index: usize) -> Option<Rect> {
723        let focus = app.get(self).items.get(&index)?.focus;
724        global_rect(app, focus.as_node().context(app)?)
725    }
726
727    /// Where the view is laid out, in global coordinates.
728    fn viewport_rect(self: Handle<Self>, app: &mut App) -> Option<Rect> {
729        global_rect(app, self.context(app))
730    }
731}
732
733fn global_rect(app: &mut App, context: BuildContext) -> Option<Rect> {
734    let render = context.find_render_object(app)?.as_box()?;
735    let origin = render.local_to_global(app, Offset::ZERO, None);
736    Some(origin & render.size(app))
737}
738
739// MARK: Tab stop and selection
740
741impl ItemsViewState {
742    /// `TabNavigation="Once"`: Tab stops at the current item, else at the selected one in `Single` mode, else at the first built.
743    fn tab_stop_index(self: Handle<Self>, app: &App) -> Option<usize> {
744        let selection = self.items_source(app);
745        if let Some(current) = selection.current_item_index(app) {
746            return Some(current);
747        }
748        let single = self.widget(app).selection_mode == ItemsViewSelectionMode::Single;
749        let selected = selection.selected_index(app).filter(|_| single);
750        selected.or_else(|| app.get(self).items.keys().copied().min())
751    }
752
753    /// Tells the containers when the item Tab stops at changed.
754    fn sync_tab_stop(self: Handle<Self>, app: &mut App) {
755        let tab_stop = self.tab_stop_index(app);
756        if app.get(self).tab_stop != tab_stop {
757            app.get_mut(self).tab_stop = tab_stop;
758            self.items_source(app).notify_items(app);
759        }
760    }
761
762    /// The same after the frame, for the registry changing while the list builds.
763    fn sync_tab_stop_after_frame(self: Handle<Self>, app: &mut App) {
764        self.after_frame(app, move |app| self.sync_tab_stop(app));
765    }
766
767    /// The selection heard: `SelectionChanged` is raised for a change of the selection, not of the current item.
768    fn selection_heard(self: Handle<Self>, app: &mut App) {
769        let source = self.items_source(app);
770        let revision = source.revision(app);
771        if revision == app.get(self).seen_revision {
772            return;
773        }
774        app.get_mut(self).seen_revision = revision;
775        let count = source.item_count(app);
776        if count != app.get(self).shown_count {
777            app.get_mut(self).shown_count = count;
778            self.set_state(app, |_| {});
779        }
780        if let Some(changed) = self.widget(app).selection_changed.clone() {
781            changed.call(app);
782        }
783    }
784
785    /// Listens to the selection in use, and gives it the view's mode and count.
786    fn sync_selection(self: Handle<Self>, app: &mut App) {
787        let selection = self.items_source(app);
788        if app
789            .get(self)
790            .listening
791            .as_ref()
792            .map(|(listened, _)| listened.handle())
793            != Some(selection)
794        {
795            if let Some((old, listener)) = app.get_mut(self).listening.take() {
796                old.remove_listener(app, &listener);
797            }
798            let listener = Listener::new(move |app| self.selection_heard(app));
799            selection.add_listener(app, listener.clone());
800            let revision = selection.revision(app);
801            let kept = selection.keep(app);
802            let state = app.get_mut(self);
803            state.listening = Some((kept, listener));
804            state.seen_revision = revision;
805        }
806        let widget = self.widget(app).clone();
807        app.get_mut(self).shown_count = selection.item_count(app);
808        selection.set_selection_mode(app, widget.selection_mode);
809    }
810
811    fn alive(self: Handle<Self>, app: &App) -> bool {
812        app.contains(self) && self.mounted(app)
813    }
814
815    /// Runs `work` once the frame is over, if the view is still mounted.
816    fn after_frame(self: Handle<Self>, app: &mut App, work: impl Fn(&mut App) + 'static) {
817        let view = View::maybe_id_of(app, self.context(app));
818        after_next_frame(
819            app,
820            view,
821            FrameCallback::new(move |app, _| {
822                if self.alive(app) {
823                    work(app);
824                }
825            }),
826        );
827    }
828}
829
830// MARK: Building
831
832impl ItemsViewState {
833    /// One item: the application's container in the scope that tells it its index, measured, `Spacing` after it but the last.
834    fn item(self: Handle<Self>, app: &mut App, context: BuildContext, index: usize) -> WidgetRef {
835        let widget = self.widget(app).clone();
836        let container = (widget.item_template)(app, context, index);
837        let scoped = ItemsViewItemScope {
838            item: ItemsViewItem { index, view: self },
839            child: container.into_widget(),
840        };
841        let measured = SizeObserver::new(
842            scoped,
843            Rc::new(move |app, _, size| self.item_measured(app, index, size)),
844        );
845        let spacing = if index + 1 < self.item_count(app) {
846            widget.layout.spacing
847        } else {
848            0.0
849        };
850        let gap = match widget.layout.orientation {
851            Axis::Vertical => EdgeInsetsGeometry::from_ltrb(0.0, 0.0, 0.0, spacing),
852            Axis::Horizontal => EdgeInsetsGeometry::from_ltrb(0.0, 0.0, spacing, 0.0),
853        };
854        Padding::new(gap).child(measured).into_widget()
855    }
856
857    /// `PART_ItemsRepeater` in `PART_ScrollView`: a lazy list along a vertical stack, a row of every item along a horizontal one.
858    fn items(self: Handle<Self>, app: &mut App) -> WidgetRef {
859        let widget = self.widget(app).clone();
860        let scroll = self.scroll(app);
861        let [left, top, right, bottom] = widget.padding;
862        let padding = EdgeInsetsGeometry::from_ltrb(left, top, right, bottom);
863        match widget.layout.orientation {
864            Axis::Vertical => {
865                let list = ListView::builder(move |app, context, index| {
866                    Some(self.item(app, context, index as usize))
867                })
868                .item_count(self.item_count(app) as i32)
869                .build()
870                .controller(scroll.native_controller(app))
871                .padding(padding);
872                let list = match widget.item_extent {
873                    Some(extent) => list.item_extent(extent + widget.layout.spacing),
874                    None => list,
875                };
876                ScrollBarViewport::scroller(
877                    app.get(self).scroll.clone().expect("made in `init_state`"),
878                    list,
879                )
880                .into_widget()
881            }
882            Axis::Horizontal => {
883                let context = self.context(app);
884                let items: Vec<WidgetRef> = (0..self.item_count(app))
885                    .map(|index| self.item(app, context, index))
886                    .collect();
887                let row = Padding::new(padding)
888                    .child(Row::new().main_axis_size(MainAxisSize::Min).children(items));
889                ScrollBarViewport::new(
890                    app.get(self).scroll.clone().expect("made in `init_state`"),
891                    row,
892                )
893                .axis(Axis::Horizontal)
894                .into_widget()
895            }
896        }
897    }
898}
899
900impl State for ItemsViewState {
901    type Widget = ItemsView;
902    waft_widgets::state_accessors!();
903
904    fn init_state(self: Handle<Self>, app: &mut App) {
905        InputDevice::initialize(app);
906        let scroll = ScrollViewportController::new(app);
907        app.get_mut(self).scroll = Some(scroll);
908        self.sync_selection(app);
909    }
910
911    fn did_update_widget(self: Handle<Self>, app: &mut App, _old: &ItemsView) {
912        self.sync_selection(app);
913    }
914
915    fn dispose(self: Handle<Self>, app: &mut App) {
916        if let Some((selection, listener)) = app.get_mut(self).listening.take() {
917            selection.remove_listener(app, &listener);
918        }
919        if let Some(scroll) = app.get_mut(self).scroll.take() {
920            scroll.dispose(app);
921        }
922    }
923
924    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
925        let corner = ThemeResources::of(app, context).control_corner_radius;
926        let items = self.items(app);
927        let [top_left, top_right, bottom_right, bottom_left] = corner.map(Radius::circular);
928        let clipped = ClipRRect::new()
929            .border_radius(
930                BorderRadius::only(top_left, top_right, bottom_left, bottom_right).into(),
931            )
932            .clip_behavior(Clip::AntiAlias)
933            .child(items);
934        Focus::new(clipped)
935            .can_request_focus(false)
936            .skip_traversal(true)
937            .on_key_event(Rc::new(move |app, _, event| self.key(app, event)))
938            .into_widget()
939    }
940}