1use super::super::items_view::selection_model::SelectionModel;
6use super::source::{TableViewSource, ViewChange};
7use super::*;
8use std::fmt;
9use std::rc::Rc;
10use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Ref};
11
12pub(crate) type ItemOfRow = Rc<dyn Fn(&App, usize) -> Option<usize>>;
14
15type AddSourceListener = Rc<dyn Fn(&mut App, Listener)>;
17type RemoveSourceListener = Rc<dyn Fn(&mut App, &Listener)>;
19type ReadSourceChanges = Rc<dyn Fn(&App) -> Vec<ViewChange>>;
21type ReadSourceRowCount = Rc<dyn Fn(&App) -> usize>;
23
24#[derive(Clone)]
27pub(crate) struct SelectionSource {
28 id: HandleId,
29 add_listener: AddSourceListener,
30 remove_listener: RemoveSourceListener,
31 changes: ReadSourceChanges,
32 row_count: ReadSourceRowCount,
33}
34
35impl SelectionSource {
36 pub(crate) fn new<T: 'static>(source: &Ref<TableViewSource<T>>) -> SelectionSource {
38 let for_adding = source.clone();
39 let for_removing = source.clone();
40 let for_changes = source.clone();
41 let for_rows = source.clone();
42 SelectionSource {
43 id: source.handle().id(),
44 add_listener: Rc::new(move |app, listener| for_adding.add_listener(app, listener)),
45 remove_listener: Rc::new(move |app, listener| {
46 for_removing.remove_listener(app, listener)
47 }),
48 changes: Rc::new(move |app| for_changes.changes(app).to_vec()),
49 row_count: Rc::new(move |app| for_rows.view(app).len()),
50 }
51 }
52}
53
54struct SelectionBinding {
56 owner: HandleId,
58 can_select: bool,
60 item_of_row: ItemOfRow,
62}
63
64pub struct TableViewSelection {
68 notifier: ChangeNotifierData,
69 model: SelectionModel,
70 binding: Option<SelectionBinding>,
71 source: Option<SelectionSource>,
74 source_listener: Option<Listener>,
76 last_raised_item: Option<usize>,
78}
79
80impl TableViewSelection {
81 pub fn new(app: &mut App) -> Ref<Self> {
83 let mut model = SelectionModel::default();
84 model.set_single_select(true);
85 app.create(Self {
86 notifier: ChangeNotifierData::new(),
87 model,
88 binding: None,
89 source: None,
90 source_listener: None,
91 last_raised_item: None,
92 })
93 }
94
95 pub fn dispose(self: Handle<Self>, app: &mut App) {
98 self.stop_following_source(app);
99 ChangeNotifierData::dispose(app, self);
100 }
101
102 pub fn select(self: Handle<Self>, app: &mut App, index: usize) {
104 if !self.can_select(app) || index >= self.row_count(app) {
105 return;
106 }
107 self.apply(app, Some(index));
108 }
109
110 pub fn deselect(self: Handle<Self>, app: &mut App, index: usize) {
112 if self.is_selected(app, index) {
113 self.apply(app, None);
114 }
115 }
116
117 pub fn is_selected(self: Handle<Self>, app: &App, index: usize) -> bool {
119 index < self.row_count(app) && app.get(self).model.is_selected(index)
120 }
121
122 pub fn deselect_all(self: Handle<Self>, app: &mut App) {
124 self.apply(app, None);
125 }
126
127 pub fn selected_index(self: Handle<Self>, app: &App) -> Option<usize> {
129 app.get(self)
130 .model
131 .selected_index()
132 .filter(|index| *index < self.row_count(app))
133 }
134
135 pub fn selected_item(self: Handle<Self>, app: &App) -> Option<usize> {
137 let index = self.selected_index(app)?;
138 let binding = app.get(self).binding.as_ref()?;
139 (binding.item_of_row)(app, index)
140 }
141}
142
143impl TableViewSelection {
146 pub(crate) fn bind(
148 self: Handle<Self>,
149 app: &mut App,
150 owner: HandleId,
151 can_select: bool,
152 row_count: usize,
153 source: SelectionSource,
154 item_of_row: ItemOfRow,
155 ) -> bool {
156 let source_changed = app
157 .get(self)
158 .source
159 .as_ref()
160 .is_none_or(|bound| bound.id != source.id);
161 if source_changed {
162 self.stop_following_source(app);
165 let listener = Listener::handle_method(self, Self::source_heard);
166 (source.add_listener)(app, listener.clone());
167 let selection = app.get_mut(self);
168 selection.source = Some(source);
169 selection.source_listener = Some(listener);
170 }
171 app.get_mut(self).binding = Some(SelectionBinding {
172 owner,
173 can_select,
174 item_of_row,
175 });
176 let cleared = if source_changed {
177 app.get_mut(self).start_over(row_count)
178 } else {
179 false
180 };
181 if !can_select {
182 self.apply(app, None);
184 }
185 cleared
186 }
187
188 fn stop_following_source(self: Handle<Self>, app: &mut App) {
190 let (source, listener) = {
191 let selection = app.get_mut(self);
192 (selection.source.take(), selection.source_listener.take())
193 };
194 if let (Some(source), Some(listener)) = (source, listener) {
195 (source.remove_listener)(app, &listener);
196 }
197 }
198
199 fn source_heard(self: Handle<Self>, app: &mut App) {
202 let (changes, row_count) = {
203 let selection = app.get(self);
204 let Some(source) = &selection.source else {
205 return;
206 };
207 ((source.changes)(app), (source.row_count)(app))
208 };
209 self.source_changed(app, &changes, row_count);
210 }
211
212 pub(crate) fn unbind(self: Handle<Self>, app: &mut App, owner: HandleId) {
214 let selection = app.get_mut(self);
215 if selection
216 .binding
217 .as_ref()
218 .is_some_and(|binding| binding.owner == owner)
219 {
220 selection.binding = None;
221 }
222 }
223
224 pub(crate) fn source_changed(
226 self: Handle<Self>,
227 app: &mut App,
228 changes: &[ViewChange],
229 row_count: usize,
230 ) {
231 let mut invalidated = false;
232 for &change in changes {
233 let selection = app.get_mut(self);
234 invalidated |= match change {
235 ViewChange::ItemInserted(index) => {
236 if let Some(item) = &mut selection.last_raised_item
237 && *item >= index
238 {
239 *item += 1;
240 }
241 false
242 }
243 ViewChange::ItemRemoved(index) => {
244 if let Some(item) = &mut selection.last_raised_item
246 && *item > index
247 {
248 *item -= 1;
249 }
250 false
251 }
252 ViewChange::RowInserted(row) => selection.model.on_items_added(row, 1),
253 ViewChange::RowRemoved(row) => selection.model.on_items_removed(row, 1),
254 ViewChange::RowMoved(from, to) => {
255 let was_selected = selection.model.is_selected(from);
257 selection.model.on_items_removed(from, 1);
258 selection.model.on_items_added(to, 1);
259 if was_selected {
260 selection.model.select(to);
261 }
262 true
263 }
264 ViewChange::RowReplaced(row) => {
265 let removed = selection.model.on_items_removed(row, 1);
266 selection.model.on_items_added(row, 1) | removed
267 }
268 ViewChange::Reset => selection.start_over(row_count),
269 };
270 }
271 debug_assert_eq!(app.get(self).model.item_count(), row_count);
272 if invalidated {
274 self.notify_listeners(app);
275 }
276 }
277
278 pub(crate) fn select_from_interaction(
280 self: Handle<Self>,
281 app: &mut App,
282 index: usize,
283 toggle: bool,
284 ) {
285 if !self.can_select(app) {
286 return;
287 }
288 if toggle && self.is_selected(app, index) {
289 self.apply(app, None);
290 } else {
291 self.apply(app, Some(index));
292 }
293 }
294
295 pub(crate) fn take_change(
297 self: Handle<Self>,
298 app: &mut App,
299 ) -> Option<(Option<usize>, Option<usize>)> {
300 let added = self.selected_item(app);
301 let removed = app.get(self).last_raised_item;
302 if removed == added {
303 return None;
304 }
305 app.get_mut(self).last_raised_item = added;
306 Some((removed, added))
307 }
308
309 fn start_over(&mut self, row_count: usize) -> bool {
311 let cleared = self.model.selected_index().is_some();
312 self.model.set_source(row_count);
313 cleared
314 }
315
316 fn can_select(self: Handle<Self>, app: &App) -> bool {
317 app.get(self)
318 .binding
319 .as_ref()
320 .is_some_and(|binding| binding.can_select)
321 }
322
323 fn row_count(self: Handle<Self>, app: &App) -> usize {
324 app.get(self).model.item_count()
325 }
326
327 fn apply(self: Handle<Self>, app: &mut App, index: Option<usize>) {
329 let index = index.filter(|index| self.can_select(app) && *index < self.row_count(app));
330 let model = &mut app.get_mut(self).model;
331 let changed = match index {
332 Some(index) => model.select(index),
333 None => model.selected_index().is_some() && model.clear_selection(),
334 };
335 if changed {
336 self.notify_listeners(app);
337 }
338 }
339}
340
341impl ChangeNotifier for TableViewSelection {
342 fn change_notifier_data(&self) -> &ChangeNotifierData {
343 &self.notifier
344 }
345
346 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
347 &mut self.notifier
348 }
349}
350
351impl fmt::Debug for TableViewSelection {
352 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353 f.debug_struct("TableViewSelection")
354 .field("selected_index", &self.model.selected_index())
355 .field("bound", &self.binding.is_some())
356 .finish_non_exhaustive()
357 }
358}
359
360impl<T: 'static> TableViewState<T> {
363 pub(super) fn sync_selection(self: Handle<Self>, app: &mut App) {
365 let id = self.id_of();
366 let selection = self.widget(app).selection.clone();
367 let held = app
368 .get(self)
369 .selection
370 .as_ref()
371 .map(|(held, _)| held.handle());
372 if held != selection.as_ref().map(|selection| selection.handle()) {
373 if let Some((old, listener)) = app.get_mut(self).selection.take() {
374 old.remove_listener(app, &listener);
375 old.unbind(app, id);
376 }
377 if let Some(selection) = &selection {
378 let listener = Listener::new(move |app| self.selection_heard(app));
379 selection.add_listener(app, listener.clone());
380 app.get_mut(self).selection = Some((selection.clone(), listener));
381 }
382 }
383 if let Some(selection) = selection {
384 let can_select = self.widget(app).selection_mode != TableViewSelectionMode::None;
385 let count = self.row_count(app);
386 let item_of_row: selection::ItemOfRow = Rc::new(move |app, row| {
387 if !app.contains(self) {
388 return None;
389 }
390 self.source_handle(app).view(app).get(row).copied()
391 });
392 let source = SelectionSource::new(&self.widget(app).items_source);
393 if selection.bind(app, id, can_select, count, source, item_of_row) {
397 let selection = selection.clone();
398 self.after_frame(app, move |app| {
399 if app.contains(selection.handle()) {
400 selection.handle().notify_listeners(app);
401 }
402 });
403 }
404 }
405 }
406
407 pub(super) fn selection_heard(self: Handle<Self>, app: &mut App) {
409 if !self.alive(app) {
410 return;
411 }
412 let Some(selection) = self.selection_handle(app) else {
413 return;
414 };
415 let Some((removed, added)) = selection.take_change(app) else {
416 return;
417 };
418 if let Some(changed) = self.widget(app).selection_changed.clone() {
419 let args = TableViewSelectionChangedEventArgs {
420 removed_items: removed.into_iter().collect(),
421 added_items: added.into_iter().collect(),
422 };
423 changed(app, &args);
424 }
425 }
426
427 pub(super) fn can_select_rows(self: Handle<Self>, app: &App) -> bool {
428 self.widget(app).selection.is_some()
429 && self.widget(app).selection_mode != TableViewSelectionMode::None
430 }
431
432 pub(super) fn select_row_from_interaction(self: Handle<Self>, app: &mut App, index: usize) {
434 let control = HardwareKeyboard::instance(app).is_control_pressed(app);
435 if let Some(selection) = self.selection_handle(app) {
436 selection.select_from_interaction(app, index, control);
437 }
438 }
439}
440
441#[cfg(test)]
442mod tests {
443 use super::*;
444 use waft_foundation::AppCell;
445
446 fn bound(app: &mut App, rows: usize, can_select: bool) -> Ref<TableViewSelection> {
447 let source = TableViewSource::from(app, vec![0u8; rows]);
448 bound_to(app, rows, can_select, &source)
449 }
450
451 fn bound_to(
452 app: &mut App,
453 rows: usize,
454 can_select: bool,
455 source: &Ref<TableViewSource<u8>>,
456 ) -> Ref<TableViewSelection> {
457 let selection = TableViewSelection::new(app);
458 let owner = app.create(0u8);
459 selection.bind(
460 app,
461 owner.handle().id(),
462 can_select,
463 rows,
464 SelectionSource::new(source),
465 Rc::new(|_, row| Some(row + 10)),
466 );
467 selection
468 }
469
470 #[test]
473 fn a_select_that_cannot_be_resolved_does_nothing() {
474 let cell = AppCell::new();
475 let mut app = cell.borrow_mut();
476 let unbound = TableViewSelection::new(&mut app);
477 unbound.select(&mut app, 0);
478 assert_eq!(unbound.selected_index(&app), None);
479
480 let selection = bound(&mut app, 3, true);
481 selection.select(&mut app, 1);
482 selection.select(&mut app, 9);
483 assert_eq!(selection.selected_index(&app), Some(1));
484 assert_eq!(selection.selected_item(&app), Some(11));
485
486 let off = bound(&mut app, 3, false);
487 off.select(&mut app, 1);
488 assert_eq!(off.selected_index(&app), None);
489 }
490
491 #[test]
492 fn deselect_clears_only_the_selected_row_and_control_toggles() {
493 let cell = AppCell::new();
494 let mut app = cell.borrow_mut();
495 let selection = bound(&mut app, 3, true);
496 selection.select(&mut app, 2);
497 selection.deselect(&mut app, 1);
498 assert_eq!(selection.selected_index(&app), Some(2));
499 selection.select_from_interaction(&mut app, 2, true);
500 assert_eq!(selection.selected_index(&app), None);
501 selection.select_from_interaction(&mut app, 0, false);
502 selection.select_from_interaction(&mut app, 1, false);
503 assert_eq!(selection.selected_index(&app), Some(1));
504 }
505
506 #[test]
507 fn a_change_is_reported_once_from_the_item_reported_last() {
508 let cell = AppCell::new();
509 let mut app = cell.borrow_mut();
510 let selection = bound(&mut app, 3, true);
511 selection.select(&mut app, 0);
512 assert_eq!(selection.take_change(&mut app), Some((None, Some(10))));
513 assert_eq!(selection.take_change(&mut app), None);
514 let owner = app.create(0u8);
516 let other_source = TableViewSource::from(&mut app, vec![0u8; 3]);
517 assert!(selection.bind(
518 &mut app,
519 owner.handle().id(),
520 true,
521 3,
522 SelectionSource::new(&other_source),
523 Rc::new(|_, row| Some(row)),
524 ));
525 assert_eq!(selection.take_change(&mut app), Some((Some(10), None)));
526 }
527
528 #[test]
531 fn rebinding_the_same_source_keeps_the_selection() {
532 let cell = AppCell::new();
533 let mut app = cell.borrow_mut();
534 let source = TableViewSource::from(&mut app, vec![0u8; 3]);
535 let selection = bound_to(&mut app, 3, true, &source);
536 selection.select(&mut app, 1);
537 assert_eq!(selection.selected_index(&app), Some(1));
538
539 let heard = Rc::new(std::cell::Cell::new(0));
540 let heard_here = Rc::clone(&heard);
541 selection.add_listener(
542 &mut app,
543 Listener::new(move |_app| heard_here.set(heard_here.get() + 1)),
544 );
545
546 let owner = app.create(0u8);
547 let cleared = selection.bind(
548 &mut app,
549 owner.handle().id(),
550 true,
551 3,
552 SelectionSource::new(&source),
553 Rc::new(|_, row| Some(row)),
554 );
555 assert!(!cleared);
556 assert_eq!(selection.selected_index(&app), Some(1));
557 assert_eq!(heard.get(), 0);
558 }
559
560 #[test]
563 fn the_selection_follows_its_source_with_no_table_holding_it() {
564 let cell = AppCell::new();
565 let mut app = cell.borrow_mut();
566 let source = TableViewSource::from(&mut app, vec![10u8, 20, 30, 40]);
567 let owner = app.create(0u8);
568 let selection = TableViewSelection::new(&mut app);
569 let rows_of = source.clone();
570 selection.bind(
571 &mut app,
572 owner.handle().id(),
573 true,
574 4,
575 SelectionSource::new(&source),
576 Rc::new(move |app, row| rows_of.view(app).get(row).copied()),
577 );
578 selection.select(&mut app, 2);
579 assert_eq!(selection.selected_index(&app), Some(2));
580
581 selection.unbind(&mut app, owner.handle().id());
583 source.insert(&mut app, 0, 5);
584 assert_eq!(selection.selected_index(&app), Some(3));
585
586 source.remove(&mut app, 4);
588 source.remove(&mut app, 3);
589 assert_eq!(selection.selected_index(&app), None);
590 }
591
592 #[test]
594 fn a_moved_row_keeps_its_selection() {
595 let cell = AppCell::new();
596 let mut app = cell.borrow_mut();
597 let selection = bound(&mut app, 3, true);
598 selection.select(&mut app, 2);
599 selection.source_changed(&mut app, &[ViewChange::RowMoved(2, 0)], 3);
600 assert_eq!(selection.selected_index(&app), Some(0));
601 selection.source_changed(&mut app, &[ViewChange::RowMoved(2, 0)], 3);
602 assert_eq!(selection.selected_index(&app), Some(1));
603 }
604}