Skip to main content

waft_winui/controls/table_view/
source.rs

1//! `TableViewSource` (`controls/dev/TableView/TableViewSource.cpp`) over the shaping engine it fronts (`controls/dev/ShapedItemsSource/ShapedItemsSource.cpp`, `controls/dev/TabularShaping/ShapingPipeline.cpp`): the application's items, one filter predicate, and sort axes in the order they were declared, projected as the view a `TableView` shows.
2//!
3//! The view is rebuilt from the items whenever a verb changes the shape: the filter runs first, over the items in source order, then a stable sort over the active axes, the first declared primary and each later one breaking ties within the earlier. An item inserted, removed, replaced or updated in place is spliced into the view at its place (`ShapedItemsSource::ApplyIncrementalChange`, `TryApplyIncrementalSortedChange`), always exactly, for each row knows its item's source index: source order settles a tie and places a row among a filter's. Every operation notifies once, with the [`ViewChange`]s it made in order, which a `TableView` reads to move its selection as `SelectionNode::OnSourceListChanged` does; a verb that changes nothing (clearing an absent filter) does not notify. A later editor who changes the view without recording the change leaves a `TableView`'s selection on the wrong row.
4
5use std::cmp::Ordering;
6use std::fmt;
7use std::rc::Rc;
8use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Ref};
9
10/// XAML `SortDirection` (`TabularShaping/SortDirection.idl`).
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
12pub enum SortDirection {
13    #[default]
14    None,
15    Ascending,
16    Descending,
17}
18
19/// Keeps an item in the view: `TableViewPredicate`.
20type ItemPredicate<T> = Rc<dyn Fn(&T) -> bool>;
21
22/// Orders two items: a key selector's comparison, or a column's `CustomSortComparer`.
23pub(crate) type SortComparer<T> = Rc<dyn Fn(&T, &T) -> Ordering>;
24
25/// One change an operation made, in order: the items' indices shifting (`ItemInserted`, `ItemRemoved`), and the view's rows changing as its `IObservableVector` raises them (`RowInserted`, `RowRemoved`, `RowReplaced`, `Reset`), and a row moving with its item (`RowMoved`), which an `IObservableVector` raises as a removal and an insertion.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub(crate) enum ViewChange {
28    /// An item was inserted at this index of the items; those at and after it moved up one.
29    ItemInserted(usize),
30    /// The item at this index of the items was removed; those after it moved down one.
31    ItemRemoved(usize),
32    /// A row was inserted at this index of the view.
33    RowInserted(usize),
34    /// The row at this index of the view was removed.
35    RowRemoved(usize),
36    /// The row at this index of the view shows a new item.
37    RowReplaced(usize),
38    /// The row at the first index of the view moved to the second, its item the same.
39    RowMoved(usize, usize),
40    /// The view was rebuilt.
41    Reset,
42}
43
44/// `TabularShapingHelpers::SortAxis`: one active sort axis. `token` names an axis a `TableView` installs for a column; the axes an application declares through [`TableViewSource::sort`] have none.
45struct SortAxis<T> {
46    token: Option<HandleId>,
47    compare: SortComparer<T>,
48    direction: SortDirection,
49}
50
51/// XAML `TableViewSource`: the items a `TableView` shows and the shape it shows them in.
52///
53/// The application makes one with [`TableViewSource::from`], hands it to one `TableView`, and disposes it after the view.
54pub struct TableViewSource<T> {
55    notifier: ChangeNotifierData,
56    /// Each shared, so a cell can be built from an item while the source is reachable through the `App`.
57    items: Vec<Rc<T>>,
58    /// `ShapingPipeline::m_filters`'s single untokenized axis: `Filter` replaces it.
59    filter: Option<ItemPredicate<T>>,
60    /// `ShapingPipeline::m_sorts`, in declaration order, which is precedence order.
61    sorts: Vec<SortAxis<T>>,
62    /// The projection: each row's index in `items`.
63    view: Vec<usize>,
64    /// The `TableView` showing the source, for `SetOwningTableView`'s single-owner check.
65    owner: Option<HandleId>,
66    /// What the last operation changed, for the listeners it notifies.
67    changes: Vec<ViewChange>,
68}
69
70impl<T: 'static> TableViewSource<T> {
71    /// `TableViewSource.From`: a source over `items`, unshaped, its view populated by the time it returns.
72    pub fn from(app: &mut App, items: Vec<T>) -> Ref<Self> {
73        let mut source = Self {
74            notifier: ChangeNotifierData::new(),
75            items: items.into_iter().map(Rc::new).collect(),
76            filter: None,
77            sorts: Vec::new(),
78            view: Vec::new(),
79            owner: None,
80            changes: Vec::new(),
81        };
82        source.rebuild_view();
83        app.create(source)
84    }
85
86    /// Releases the listeners; the source is not used after.
87    pub fn dispose(self: Handle<Self>, app: &mut App) {
88        ChangeNotifierData::dispose(app, self);
89    }
90
91    /// How many items there are.
92    pub fn item_count(self: Handle<Self>, app: &App) -> usize {
93        app.get(self).items.len()
94    }
95
96    /// The item at `index`, in source order.
97    pub fn item(self: Handle<Self>, app: &App, index: usize) -> &T {
98        &app.get(self).items[index]
99    }
100
101    /// Replaces the items, as the collection the source wraps raising a reset: the filter and the sorts stay, the view is rebuilt from the new items, and a `TableView` showing the source clears its selection (`SelectionNode::OnSourceListChanged`, `Reset`).
102    pub fn set_items(self: Handle<Self>, app: &mut App, items: Vec<T>) {
103        let source = app.get_mut(self);
104        source.items = items.into_iter().map(Rc::new).collect();
105        source.rebuild_view();
106        source.changes = vec![ViewChange::Reset];
107        self.notify_listeners(app);
108    }
109
110    /// Inserts `item` at `index` of the items, as the collection raising `Add`: its row goes to its place in the view, unless the filter leaves it out.
111    pub fn insert(self: Handle<Self>, app: &mut App, index: usize, item: T) {
112        app.get_mut(self).insert_item(index, Rc::new(item));
113        self.notify_listeners(app);
114    }
115
116    /// Removes the item at `index`, as the collection raising `Remove`: its row, if shown, is removed.
117    pub fn remove(self: Handle<Self>, app: &mut App, index: usize) {
118        app.get_mut(self).remove_item(index);
119        self.notify_listeners(app);
120    }
121
122    /// Replaces the item at `index` with `item`, as the collection raising `Replace`: without a sort its row shows the new item; with one the row is removed and the new item inserted at its place. A row replaced is no longer selected, as `SelectionNode` treats a replacement as a removal and an insertion; [`update`](Self::update) keeps it.
123    pub fn replace(self: Handle<Self>, app: &mut App, index: usize, item: T) {
124        app.get_mut(self).replace_item(index, Rc::new(item));
125        self.notify_listeners(app);
126    }
127
128    /// Changes the item at `index` in place, as an item raising `PropertyChanged`: its row shows the new values and stays selected, and moves to its new place if a sort key changed, or leaves or joins the view if the filter's answer did.
129    pub fn update(self: Handle<Self>, app: &mut App, index: usize, change: impl FnOnce(&mut T)) {
130        let source = app.get_mut(self);
131        let item = Rc::get_mut(&mut source.items[index])
132            .expect("a cell holds an item only while it is built");
133        change(item);
134        source.update_item(index);
135        self.notify_listeners(app);
136    }
137
138    /// The item at `index`, kept while a cell is built from it.
139    pub(crate) fn shared_item(self: Handle<Self>, app: &App, index: usize) -> Rc<T> {
140        app.get(self).items[index].clone()
141    }
142
143    /// What the operation now notifying changed, in order.
144    pub(crate) fn changes(self: Handle<Self>, app: &App) -> &[ViewChange] {
145        &app.get(self).changes
146    }
147
148    /// `View`: each row of the projection, as its index in the items.
149    pub fn view(self: Handle<Self>, app: &App) -> &[usize] {
150        &app.get(self).view
151    }
152
153    /// `Filter`: the only items shown are those `predicate` keeps, in source order before any sort. Each call replaces the previous predicate.
154    pub fn filter(
155        self: Handle<Self>,
156        app: &mut App,
157        predicate: impl Fn(&T) -> bool + 'static,
158    ) -> Handle<Self> {
159        app.get_mut(self).filter = Some(Rc::new(predicate));
160        self.rebuild(app);
161        self
162    }
163
164    /// `ClearFilter`: nothing at all when no filter is set, not even a rebuild.
165    pub fn clear_filter(self: Handle<Self>, app: &mut App) -> Handle<Self> {
166        if app.get_mut(self).filter.take().is_some() {
167            self.rebuild(app);
168        }
169        self
170    }
171
172    /// `Sort`: adds a sort axis ordering the rows by `key` in `direction`, after the axes already declared, which it breaks ties within. `SortDirection::None` adds nothing.
173    pub fn sort<K: Ord>(
174        self: Handle<Self>,
175        app: &mut App,
176        key: impl Fn(&T) -> K + 'static,
177        direction: SortDirection,
178    ) -> Handle<Self> {
179        let compare: SortComparer<T> = Rc::new(move |a, b| key(a).cmp(&key(b)));
180        if app.get_mut(self).set_sort(None, None, compare, direction) {
181            self.rebuild(app);
182        }
183        self
184    }
185
186    /// `ClearSort`: every axis, the ones a `TableView` installed included; nothing when there are none.
187    pub fn clear_sort(self: Handle<Self>, app: &mut App) -> Handle<Self> {
188        let source = app.get_mut(self);
189        if !source.sorts.is_empty() {
190            source.sorts.clear();
191            self.rebuild(app);
192        }
193        self
194    }
195
196    /// `SortReplacing`: the axis a `TableView` keeps for its sorted column, named by `token`, replacing the one named by `previous` (a different column), or removed when `direction` is `None`.
197    pub(crate) fn sort_replacing(
198        self: Handle<Self>,
199        app: &mut App,
200        previous: Option<HandleId>,
201        token: HandleId,
202        compare: SortComparer<T>,
203        direction: SortDirection,
204    ) {
205        if app
206            .get_mut(self)
207            .set_sort(previous, Some(token), compare, direction)
208        {
209            self.rebuild(app);
210        }
211    }
212
213    /// `ClearSort(sortAxisToken)`: the axis named by `token`.
214    pub(crate) fn clear_sort_axis(self: Handle<Self>, app: &mut App, token: HandleId) {
215        let sorts = &mut app.get_mut(self).sorts;
216        let before = sorts.len();
217        sorts.retain(|axis| axis.token != Some(token));
218        if sorts.len() != before {
219            self.rebuild(app);
220        }
221    }
222
223    /// `SetOwningTableView`: a source has one owner; a second `TableView` is refused while the first holds it. Answers whether `owner` now owns it.
224    pub(crate) fn set_owner(self: Handle<Self>, app: &mut App, owner: Option<HandleId>) -> bool {
225        let source = app.get_mut(self);
226        if let (Some(existing), Some(new)) = (source.owner, owner)
227            && existing != new
228        {
229            debug_assert!(
230                false,
231                "TableViewSource: attempted to bind an already-owned source to a second TableView"
232            );
233            return false;
234        }
235        source.owner = owner;
236        true
237    }
238
239    fn rebuild(self: Handle<Self>, app: &mut App) {
240        let source = app.get_mut(self);
241        source.rebuild_view();
242        source.changes = vec![ViewChange::Reset];
243        self.notify_listeners(app);
244    }
245}
246
247impl<T> TableViewSource<T> {
248    /// `ShapingPipeline::SetSort`: answers whether the axes changed.
249    fn set_sort(
250        &mut self,
251        previous: Option<HandleId>,
252        token: Option<HandleId>,
253        compare: SortComparer<T>,
254        direction: SortDirection,
255    ) -> bool {
256        let mut changed = false;
257        if previous.is_some() && previous != token {
258            let before = self.sorts.len();
259            self.sorts.retain(|axis| axis.token != previous);
260            changed = self.sorts.len() != before;
261        }
262        if let Some(token) = token
263            && let Some(position) = self.sorts.iter().position(|axis| axis.token == Some(token))
264        {
265            if direction == SortDirection::None {
266                self.sorts.remove(position);
267            } else {
268                // Re-sorting an axis replaces it in place and keeps its precedence.
269                let axis = &mut self.sorts[position];
270                axis.compare = compare;
271                axis.direction = direction;
272            }
273            return true;
274        }
275        if direction != SortDirection::None {
276            self.sorts.push(SortAxis {
277                token,
278                compare,
279                direction,
280            });
281            return true;
282        }
283        changed
284    }
285
286    /// `ShapedItemsSource::RebuildFlat`: filter in source order, then a stable sort over the axes.
287    fn rebuild_view(&mut self) {
288        let mut view: Vec<usize> = (0..self.items.len())
289            .filter(|&index| self.passes_filter(index))
290            .collect();
291        if !self.sorts.is_empty() {
292            view.sort_by(|&a, &b| self.compare(a, b));
293        }
294        self.view = view;
295    }
296
297    /// `ShapingPipeline::PassesFilter`.
298    fn passes_filter(&self, index: usize) -> bool {
299        self.filter
300            .as_ref()
301            .is_none_or(|predicate| predicate(&self.items[index]))
302    }
303
304    /// `CompareKeysToRow`: two items on the active axes, each in its direction.
305    fn compare(&self, a: usize, b: usize) -> Ordering {
306        for axis in &self.sorts {
307            let order = (axis.compare)(&self.items[a], &self.items[b]);
308            if order != Ordering::Equal {
309                return match axis.direction {
310                    SortDirection::Descending => order.reverse(),
311                    _ => order,
312                };
313            }
314        }
315        Ordering::Equal
316    }
317
318    /// The view's order: the active axes, ties in source order as the stable sort leaves them; source order alone without a sort.
319    fn view_order(&self, a: usize, b: usize) -> Ordering {
320        self.compare(a, b).then(a.cmp(&b))
321    }
322
323    /// Where the item at `index` belongs among the view's rows: after every row the view's order puts before it. Exact because each row knows its source index, which settles a tie where WinUI's `SortedInsertPlacementFor` cannot.
324    fn placement(&self, index: usize) -> usize {
325        self.view
326            .partition_point(|&row| self.view_order(row, index) == Ordering::Less)
327    }
328
329    /// Puts the item at `index` into the view if the filter keeps it.
330    fn insert_row(&mut self, index: usize) {
331        if self.passes_filter(index) {
332            let row = self.placement(index);
333            self.view.insert(row, index);
334            self.changes.push(ViewChange::RowInserted(row));
335        }
336    }
337
338    /// Takes the item at `index` out of the view, if it is shown.
339    fn remove_row(&mut self, index: usize) -> Option<usize> {
340        let row = self.view.iter().position(|&row| row == index)?;
341        self.view.remove(row);
342        self.changes.push(ViewChange::RowRemoved(row));
343        Some(row)
344    }
345
346    /// `Add`: the items after `index` move up one, and the new item's row goes to its place.
347    fn insert_item(&mut self, index: usize, item: Rc<T>) {
348        self.items.insert(index, item);
349        for row in &mut self.view {
350            if *row >= index {
351                *row += 1;
352            }
353        }
354        self.changes = vec![ViewChange::ItemInserted(index)];
355        self.insert_row(index);
356    }
357
358    /// `Remove`: the item's row goes, if shown, and the items after it move down one.
359    fn remove_item(&mut self, index: usize) {
360        self.changes = vec![ViewChange::ItemRemoved(index)];
361        self.remove_row(index);
362        self.items.remove(index);
363        for row in &mut self.view {
364            if *row > index {
365                *row -= 1;
366            }
367        }
368    }
369
370    /// `Replace`: a new item in the old one's place. Without a sort its row keeps its place (`SetAt`); with one the old row is removed and the new item's inserted at its place, as `TryApplyIncrementalSortedChange` does.
371    fn replace_item(&mut self, index: usize, item: Rc<T>) {
372        self.items[index] = item;
373        self.changes = Vec::new();
374        let shown = self.view.iter().position(|&row| row == index);
375        match shown {
376            Some(row) if self.sorts.is_empty() && self.passes_filter(index) => {
377                self.changes.push(ViewChange::RowReplaced(row));
378            }
379            _ => {
380                self.remove_row(index);
381                self.insert_row(index);
382            }
383        }
384    }
385
386    /// An item's values changed in place, `PropertyChanged` without a collection change: its row stays and keeps its selection, moving to its new place if a sort key changed and leaving or joining the view if the filter's answer did.
387    fn update_item(&mut self, index: usize) {
388        self.changes = Vec::new();
389        let shown = self.view.iter().position(|&row| row == index);
390        let kept = self.passes_filter(index);
391        match (shown, kept) {
392            (Some(from), true) => {
393                self.view.remove(from);
394                let to = self.placement(index);
395                self.view.insert(to, index);
396                if to != from {
397                    self.changes.push(ViewChange::RowMoved(from, to));
398                }
399            }
400            (Some(_), false) => {
401                self.remove_row(index);
402            }
403            (None, true) => self.insert_row(index),
404            (None, false) => {}
405        }
406    }
407}
408
409impl<T: 'static> ChangeNotifier for TableViewSource<T> {
410    fn change_notifier_data(&self) -> &ChangeNotifierData {
411        &self.notifier
412    }
413
414    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
415        &mut self.notifier
416    }
417}
418
419impl<T> fmt::Debug for TableViewSource<T> {
420    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421        f.debug_struct("TableViewSource")
422            .field("items", &self.items.len())
423            .field("view", &self.view)
424            .field("filter", &self.filter.is_some())
425            .field("sorts", &self.sorts.len())
426            .finish_non_exhaustive()
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433    use std::cell::Cell;
434    use waft_foundation::{AppCell, ListenableObject, Listener};
435
436    fn people(app: &mut App) -> Ref<TableViewSource<(&'static str, u32)>> {
437        TableViewSource::from(
438            app,
439            vec![("Mina", 30), ("Asha", 25), ("Diego", 30), ("Lea", 25)],
440        )
441    }
442
443    fn names(app: &App, source: &Ref<TableViewSource<(&'static str, u32)>>) -> Vec<&'static str> {
444        source
445            .view(app)
446            .iter()
447            .map(|&i| source.item(app, i).0)
448            .collect()
449    }
450
451    #[test]
452    fn the_view_is_populated_when_from_returns() {
453        let cell = AppCell::new();
454        let mut app = cell.borrow_mut();
455        let source = people(&mut app);
456        assert_eq!(source.view(&app), [0, 1, 2, 3]);
457    }
458
459    #[test]
460    fn the_filter_runs_before_the_sort_and_each_filter_replaces_the_last() {
461        let cell = AppCell::new();
462        let mut app = cell.borrow_mut();
463        let source = people(&mut app);
464        source
465            .filter(&mut app, |p| p.1 == 30)
466            .sort(&mut app, |p| p.0, SortDirection::Ascending);
467        assert_eq!(names(&app, &source), ["Diego", "Mina"]);
468        source.filter(&mut app, |p| p.1 == 25);
469        assert_eq!(names(&app, &source), ["Asha", "Lea"]);
470        source.clear_filter(&mut app);
471        assert_eq!(names(&app, &source), ["Asha", "Diego", "Lea", "Mina"]);
472    }
473
474    // `ShapingPipeline::ActiveSortAxes`: the first declared axis is primary, a later one breaks
475    // its ties, and the stable sort keeps source order for what is still tied.
476    #[test]
477    fn the_first_declared_axis_is_primary_and_ties_keep_source_order() {
478        let cell = AppCell::new();
479        let mut app = cell.borrow_mut();
480        let source = people(&mut app);
481        source.sort(&mut app, |p| p.1, SortDirection::Descending);
482        assert_eq!(names(&app, &source), ["Mina", "Diego", "Asha", "Lea"]);
483        source.sort(&mut app, |p| p.0, SortDirection::Ascending);
484        assert_eq!(names(&app, &source), ["Diego", "Mina", "Asha", "Lea"]);
485    }
486
487    #[test]
488    fn a_column_axis_is_replaced_in_place_and_removed_by_none() {
489        let cell = AppCell::new();
490        let mut app = cell.borrow_mut();
491        let source = people(&mut app);
492        let token = app.create(0u8);
493        let column = token.handle().id();
494        let by_age: SortComparer<(&str, u32)> = Rc::new(|a, b| a.1.cmp(&b.1));
495        source.sort_replacing(
496            &mut app,
497            None,
498            column,
499            by_age.clone(),
500            SortDirection::Ascending,
501        );
502        assert_eq!(names(&app, &source), ["Asha", "Lea", "Mina", "Diego"]);
503        source.sort_replacing(
504            &mut app,
505            Some(column),
506            column,
507            by_age.clone(),
508            SortDirection::Descending,
509        );
510        assert_eq!(names(&app, &source), ["Mina", "Diego", "Asha", "Lea"]);
511        source.sort_replacing(&mut app, Some(column), column, by_age, SortDirection::None);
512        assert_eq!(source.view(&app), [0, 1, 2, 3]);
513    }
514
515    #[test]
516    fn new_items_keep_the_shape_and_clearing_nothing_does_not_notify() {
517        let cell = AppCell::new();
518        let mut app = cell.borrow_mut();
519        let source = people(&mut app);
520        let heard = Rc::new(Cell::new(0));
521        let counter = heard.clone();
522        source.add_listener(
523            &mut app,
524            Listener::new(move |_| counter.set(counter.get() + 1)),
525        );
526        source.clear_filter(&mut app);
527        source.clear_sort(&mut app);
528        assert_eq!(
529            heard.get(),
530            0,
531            "ClearFilter and ClearSort with no stage do nothing"
532        );
533        source.sort(&mut app, |p| p.0, SortDirection::Descending);
534        source.set_items(&mut app, vec![("Bo", 1), ("Ann", 2)]);
535        assert_eq!(names(&app, &source), ["Bo", "Ann"]);
536        assert_eq!(heard.get(), 2);
537    }
538
539    fn changes(app: &App, source: &Ref<TableViewSource<(&'static str, u32)>>) -> Vec<ViewChange> {
540        source.changes(app).to_vec()
541    }
542
543    // `ApplyIncrementalChange` on an unshaped projection: the row is spliced at the item's index.
544    #[test]
545    fn unshaped_changes_splice_the_row_at_the_items_index() {
546        let cell = AppCell::new();
547        let mut app = cell.borrow_mut();
548        let source = people(&mut app);
549        source.insert(&mut app, 1, ("Bo", 50));
550        assert_eq!(names(&app, &source), ["Mina", "Bo", "Asha", "Diego", "Lea"]);
551        assert_eq!(
552            changes(&app, &source),
553            [ViewChange::ItemInserted(1), ViewChange::RowInserted(1)]
554        );
555        source.replace(&mut app, 0, ("Ana", 20));
556        assert_eq!(changes(&app, &source), [ViewChange::RowReplaced(0)]);
557        source.remove(&mut app, 2);
558        assert_eq!(names(&app, &source), ["Ana", "Bo", "Diego", "Lea"]);
559        assert_eq!(
560            changes(&app, &source),
561            [ViewChange::ItemRemoved(2), ViewChange::RowRemoved(2)]
562        );
563        assert_eq!(source.view(&app), [0, 1, 2, 3]);
564    }
565
566    // `TryApplyIncrementalSortedChange`: an item goes in at its sorted place and one the filter
567    // leaves out changes no row; where WinUI rebuilds for an item tying with a row, source order
568    // places it.
569    #[test]
570    fn sorted_changes_place_the_item_and_source_order_settles_a_tie() {
571        let cell = AppCell::new();
572        let mut app = cell.borrow_mut();
573        let source = people(&mut app);
574        source
575            .filter(&mut app, |p| p.1 < 40)
576            .sort(&mut app, |p| p.1, SortDirection::Ascending);
577        assert_eq!(names(&app, &source), ["Asha", "Lea", "Mina", "Diego"]);
578        source.insert(&mut app, 0, ("Bo", 27));
579        assert_eq!(names(&app, &source), ["Asha", "Lea", "Bo", "Mina", "Diego"]);
580        assert_eq!(
581            changes(&app, &source),
582            [ViewChange::ItemInserted(0), ViewChange::RowInserted(2)]
583        );
584        source.insert(&mut app, 0, ("Old", 90));
585        assert_eq!(
586            changes(&app, &source),
587            [ViewChange::ItemInserted(0)],
588            "filtered out"
589        );
590        let count = source.item_count(&app);
591        source.insert(&mut app, count, ("Zed", 25));
592        assert_eq!(
593            names(&app, &source),
594            ["Asha", "Lea", "Zed", "Bo", "Mina", "Diego"]
595        );
596        assert_eq!(
597            changes(&app, &source)[1],
598            ViewChange::RowInserted(2),
599            "a tie appended at the end"
600        );
601        source.insert(&mut app, 0, ("Ann", 25));
602        assert_eq!(
603            changes(&app, &source),
604            [ViewChange::ItemInserted(0), ViewChange::RowInserted(0)]
605        );
606        assert_eq!(
607            names(&app, &source),
608            ["Ann", "Asha", "Lea", "Zed", "Bo", "Mina", "Diego"]
609        );
610        // Removing a filtered-out item moves the items after it and no row.
611        source.remove(&mut app, 1);
612        assert_eq!(changes(&app, &source), [ViewChange::ItemRemoved(1)]);
613        assert_eq!(
614            names(&app, &source),
615            ["Ann", "Asha", "Lea", "Zed", "Bo", "Mina", "Diego"]
616        );
617    }
618
619    #[test]
620    fn a_sorted_replace_moves_the_row_and_a_filter_alone_places_it_in_source_order() {
621        let cell = AppCell::new();
622        let mut app = cell.borrow_mut();
623        let source = people(&mut app);
624        source.sort(&mut app, |p| p.0, SortDirection::Ascending);
625        source.replace(&mut app, 1, ("Zoe", 25));
626        assert_eq!(names(&app, &source), ["Diego", "Lea", "Mina", "Zoe"]);
627        assert_eq!(
628            changes(&app, &source),
629            [ViewChange::RowRemoved(0), ViewChange::RowInserted(3)]
630        );
631        source.clear_sort(&mut app).filter(&mut app, |p| p.1 == 25);
632        source.remove(&mut app, 3);
633        assert_eq!(
634            changes(&app, &source),
635            [ViewChange::ItemRemoved(3), ViewChange::RowRemoved(1)]
636        );
637        assert_eq!(names(&app, &source), ["Zoe"]);
638        source.insert(&mut app, 0, ("Ann", 25));
639        assert_eq!(
640            changes(&app, &source),
641            [ViewChange::ItemInserted(0), ViewChange::RowInserted(0)]
642        );
643        source.insert(&mut app, 3, ("Kai", 25));
644        assert_eq!(
645            changes(&app, &source),
646            [ViewChange::ItemInserted(3), ViewChange::RowInserted(2)]
647        );
648        assert_eq!(names(&app, &source), ["Ann", "Zoe", "Kai"]);
649    }
650
651    // `update` is `PropertyChanged`: the row stays where it is unless a sort key moved it, and
652    // leaves or joins the view as the filter's answer changes.
653    #[test]
654    fn an_update_moves_a_row_only_when_its_place_changes() {
655        let cell = AppCell::new();
656        let mut app = cell.borrow_mut();
657        let source = people(&mut app);
658        source.sort(&mut app, |p| p.1, SortDirection::Ascending);
659        assert_eq!(names(&app, &source), ["Asha", "Lea", "Mina", "Diego"]);
660        source.update(&mut app, 0, |p| p.0 = "Mia");
661        assert_eq!(changes(&app, &source), []);
662        source.update(&mut app, 0, |p| p.1 = 20);
663        assert_eq!(names(&app, &source), ["Mia", "Asha", "Lea", "Diego"]);
664        assert_eq!(changes(&app, &source), [ViewChange::RowMoved(2, 0)]);
665        source.filter(&mut app, |p| p.1 < 30);
666        source.update(&mut app, 2, |p| p.1 = 10);
667        assert_eq!(changes(&app, &source), [ViewChange::RowInserted(0)]);
668        source.update(&mut app, 2, |p| p.1 = 99);
669        assert_eq!(changes(&app, &source), [ViewChange::RowRemoved(0)]);
670        assert_eq!(names(&app, &source), ["Mia", "Asha", "Lea"]);
671    }
672}