1use std::cmp::Ordering;
6use std::fmt;
7use std::rc::Rc;
8use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Ref};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
12pub enum SortDirection {
13 #[default]
14 None,
15 Ascending,
16 Descending,
17}
18
19type ItemPredicate<T> = Rc<dyn Fn(&T) -> bool>;
21
22pub(crate) type SortComparer<T> = Rc<dyn Fn(&T, &T) -> Ordering>;
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub(crate) enum ViewChange {
28 ItemInserted(usize),
30 ItemRemoved(usize),
32 RowInserted(usize),
34 RowRemoved(usize),
36 RowReplaced(usize),
38 RowMoved(usize, usize),
40 Reset,
42}
43
44struct SortAxis<T> {
46 token: Option<HandleId>,
47 compare: SortComparer<T>,
48 direction: SortDirection,
49}
50
51pub struct TableViewSource<T> {
55 notifier: ChangeNotifierData,
56 items: Vec<Rc<T>>,
58 filter: Option<ItemPredicate<T>>,
60 sorts: Vec<SortAxis<T>>,
62 view: Vec<usize>,
64 owner: Option<HandleId>,
66 changes: Vec<ViewChange>,
68}
69
70impl<T: 'static> TableViewSource<T> {
71 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 pub fn dispose(self: Handle<Self>, app: &mut App) {
88 ChangeNotifierData::dispose(app, self);
89 }
90
91 pub fn item_count(self: Handle<Self>, app: &App) -> usize {
93 app.get(self).items.len()
94 }
95
96 pub fn item(self: Handle<Self>, app: &App, index: usize) -> &T {
98 &app.get(self).items[index]
99 }
100
101 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 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 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 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 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 pub(crate) fn shared_item(self: Handle<Self>, app: &App, index: usize) -> Rc<T> {
140 app.get(self).items[index].clone()
141 }
142
143 pub(crate) fn changes(self: Handle<Self>, app: &App) -> &[ViewChange] {
145 &app.get(self).changes
146 }
147
148 pub fn view(self: Handle<Self>, app: &App) -> &[usize] {
150 &app.get(self).view
151 }
152
153 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 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 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 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 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 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 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 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 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 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 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 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 fn view_order(&self, a: usize, b: usize) -> Ordering {
320 self.compare(a, b).then(a.cmp(&b))
321 }
322
323 fn placement(&self, index: usize) -> usize {
325 self.view
326 .partition_point(|&row| self.view_order(row, index) == Ordering::Less)
327 }
328
329 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 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 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 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 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 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 #[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 #[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 #[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 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 #[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}