teksilo-data 0.9.0

Reactive data models for Teksilo — list, tree, selection and sort-filter projections, with no GUI dependency.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! SelectionModel — index-based selection state for collection widgets.
//!
//! [`SelectionModel`] manages which flat indices are selected in a
//! `ListView`, `TreeView`, `TableView`, or `GridView`. It is a
//! share-by-clone handle (`Rc<RefCell<…>>` internally): pass a clone to
//! each view that should share selection state. The current selection is
//! exposed as a reactive `Signal<BTreeSet<usize>>` so widgets can bind to
//! it without polling.
//!
//! Three selection behaviours are available via [`SelectionMode`]: `None`
//! (read-only / no interaction), `Single` (at most one item), and `Multi`
//! (Ctrl+click toggle + Shift+click range extension via an internal anchor).
//! Mutators automatically notify all `Signal` observers after every change,
//! and the helper methods `adjust_for_insert` / `adjust_for_remove` /
//! `adjust_for_move` keep selected indices consistent when the underlying
//! source mutates.
//!
//! ## When to use `SelectionModel` vs `KeyedSelectionModel`
//!
//! Use `SelectionModel` (this type) for views that are backed by a plain
//! `ListModel<T>` or a `SortFilterListModel<T>` where *position* is the
//! natural identity. Use [`crate::KeyedSelectionModel`] when items carry a
//! stable app-defined key (e.g. a `NodeId` or a UUID) and selection must
//! survive sort/filter rebuilds or window slides that renumber visible indices.
//!
//! ```rust
//! # use teksilo_data::{SelectionModel, SelectionMode};
//! let sel = SelectionModel::new(SelectionMode::Multi);
//! sel.select(2);         // clear-and-select index 2, anchor = 2
//! sel.toggle(5);         // add index 5 (Ctrl+click behaviour)
//! sel.extend_to(8);      // extend from anchor 5 to 8 (Shift+click behaviour)
//! assert!(sel.is_selected(2));
//! assert_eq!(sel.count(), 5); // 2, 5, 6, 7, 8
//! sel.clear();
//! assert_eq!(sel.count(), 0);
//! ```

use std::cell::Cell;
#[cfg(debug_assertions)]
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::rc::Rc;

use teksilo_core::signal::Signal;

/// Selection behavior mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectionMode {
    /// No selection allowed.
    None,
    /// At most one item selected at a time.
    Single,
    /// Multiple items can be selected (Ctrl+click toggles, Shift+click extends).
    Multi,
}

/// Manages selection state for a collection widget.
///
/// The selection is exposed as a `Signal<BTreeSet<usize>>` so widgets can
/// observe changes reactively.
pub struct SelectionModel {
    mode: SelectionMode,
    selection: Signal<BTreeSet<usize>>,
    /// Anchor index for Shift+click range extension.
    /// Shared via Rc so clones see the same anchor state.
    anchor: Rc<Cell<Option<usize>>>,
    /// Strong holder for the debug-registry adapter. Shared across
    /// clones; once all `SelectionModel` handles drop, the holder Rc
    /// reaches zero and the adapter is freed, marking the registry
    /// entry dead. `None` until `.debug_named()` is called.
    /// Compiled out in release.
    #[cfg(debug_assertions)]
    debug_adapter_holder: Rc<RefCell<Option<Rc<dyn crate::debug_registry::ModelDebug>>>>,
}

impl SelectionModel {
    /// Create a new selection model with the given mode.
    pub fn new(mode: SelectionMode) -> Self {
        Self {
            mode,
            selection: Signal::new(BTreeSet::new()),
            anchor: Rc::new(Cell::new(None)),
            #[cfg(debug_assertions)]
            debug_adapter_holder: Rc::new(RefCell::new(None)),
        }
    }

    /// The selection mode.
    pub fn mode(&self) -> SelectionMode {
        self.mode
    }

    /// Get a clone of the selection signal for reactive binding.
    pub fn selection_signal(&self) -> Signal<BTreeSet<usize>> {
        self.selection.clone()
    }

    /// Whether the given index is currently selected.
    pub fn is_selected(&self, index: usize) -> bool {
        self.selection.get().contains(&index)
    }

    /// The currently selected indices, sorted.
    pub fn selected_indices(&self) -> Vec<usize> {
        self.selection.get().into_iter().collect()
    }

    /// Number of selected items.
    pub fn count(&self) -> usize {
        self.selection.get().len()
    }

    /// Select a single index. In Single mode, clears previous selection.
    /// In Multi mode, clears previous and selects just this one (use `toggle`
    /// for Ctrl+click behavior). Sets the anchor for subsequent Shift+click.
    pub fn select(&self, index: usize) {
        if self.mode == SelectionMode::None {
            return;
        }
        let mut set = BTreeSet::new();
        set.insert(index);
        self.selection.set(set);
        self.anchor.set(Some(index));
    }

    /// Toggle selection of a single index (for Ctrl+click in Multi mode).
    /// In Single mode, behaves like `select()`.
    pub fn toggle(&self, index: usize) {
        match self.mode {
            SelectionMode::None => {}
            SelectionMode::Single => self.select(index),
            SelectionMode::Multi => {
                let mut set = self.selection.get();
                if set.contains(&index) {
                    set.remove(&index);
                } else {
                    set.insert(index);
                }
                self.selection.set(set);
                self.anchor.set(Some(index));
            }
        }
    }

    /// Extend the selection from the anchor to the given index (for Shift+click).
    /// In Single mode, behaves like `select()`.
    pub fn extend_to(&self, index: usize) {
        match self.mode {
            SelectionMode::None => {}
            SelectionMode::Single => self.select(index),
            SelectionMode::Multi => {
                let anchor = self.anchor.get().unwrap_or(index);
                let start = anchor.min(index);
                let end = anchor.max(index);
                let mut set = self.selection.get();
                for i in start..=end {
                    set.insert(i);
                }
                self.selection.set(set);
                // Anchor stays at the original position
            }
        }
    }

    /// Replace the selection with `indices` (or, when `additive`, union them
    /// into the current selection). Used by rubber-band / marquee selection,
    /// where the selected set is an arbitrary subset rather than a range. In
    /// `Single` mode the highest index wins; `None` mode is a no-op.
    pub fn select_indices(&self, indices: impl IntoIterator<Item = usize>, additive: bool) {
        if self.mode == SelectionMode::None {
            return;
        }
        let mut set = if additive {
            self.selection.get()
        } else {
            BTreeSet::new()
        };
        set.extend(indices);
        if self.mode == SelectionMode::Single {
            let last = set.iter().next_back().copied();
            set = last.into_iter().collect();
        }
        self.selection.set(set);
    }

    /// Select all indices from 0 to count-1.
    ///
    /// A no-op in `None` mode, and also in `Single` mode — "select all" has
    /// no coherent meaning for a control that holds at most one item, and
    /// silently selecting one arbitrary row would be worse than doing
    /// nothing. This mirrors what the gated call sites already do
    /// (`ListView`'s Ctrl+A handler, which documents it as "Multi selection
    /// only — a no-op for Single / None, matching every list control", and
    /// `TableView`'s `select_all` helper, which matches only the Multi
    /// modes). Enforcing it here too keeps an ungated caller — `GridView`'s
    /// Ctrl+A handler is one — from breaking the `Single` invariant that
    /// every other mutator on this type upholds.
    pub fn select_all(&self, count: usize) {
        if self.mode == SelectionMode::None || self.mode == SelectionMode::Single {
            return;
        }
        let set: BTreeSet<usize> = (0..count).collect();
        self.selection.set(set);
    }

    /// Clear the selection.
    pub fn clear(&self) {
        self.selection.set(BTreeSet::new());
        self.anchor.set(None);
    }

    /// Adjust selection indices after items are inserted.
    /// Indices >= `start` are shifted up by `count`.
    pub fn adjust_for_insert(&self, start: usize, count: usize) {
        let old = self.selection.get();
        let mut new_set = BTreeSet::new();
        for &idx in &old {
            if idx >= start {
                new_set.insert(idx + count);
            } else {
                new_set.insert(idx);
            }
        }
        if new_set != old {
            self.selection.set(new_set);
        }
        if let Some(a) = self.anchor.get()
            && a >= start
        {
            self.anchor.set(Some(a + count));
        }
    }

    /// Adjust selection indices after items are removed.
    /// Indices in `start..start+count` are deselected; indices above are shifted down.
    pub fn adjust_for_remove(&self, start: usize, count: usize) {
        let old = self.selection.get();
        let end = start + count;
        let mut new_set = BTreeSet::new();
        for &idx in &old {
            if idx < start {
                new_set.insert(idx);
            } else if idx >= end {
                new_set.insert(idx - count);
            }
            // Indices in start..end are dropped
        }
        if new_set != old {
            self.selection.set(new_set);
        }
        if let Some(a) = self.anchor.get() {
            if a >= end {
                self.anchor.set(Some(a - count));
            } else if a >= start {
                self.anchor.set(None);
            }
        }
    }

    /// Adjust selection indices after a block of `count` items moved from
    /// `from` to `to` (a post-removal index, matching `ListModel::move_item`).
    /// Selected indices follow their items, so a dragged row stays selected.
    pub fn adjust_for_move(&self, from: usize, to: usize, count: usize) {
        if from == to || count == 0 {
            return;
        }
        let old = self.selection.get();
        let new_set: BTreeSet<usize> = old
            .iter()
            .map(|&idx| crate::map_index_after_move(idx, from, to, count))
            .collect();
        if new_set != old {
            self.selection.set(new_set);
        }
        if let Some(a) = self.anchor.get() {
            self.anchor
                .set(Some(crate::map_index_after_move(a, from, to, count)));
        }
    }
}

impl Clone for SelectionModel {
    fn clone(&self) -> Self {
        Self {
            mode: self.mode,
            selection: self.selection.clone(),
            anchor: self.anchor.clone(),
            #[cfg(debug_assertions)]
            debug_adapter_holder: self.debug_adapter_holder.clone(),
        }
    }
}

impl SelectionModel {
    /// Register this selection model with the debug inspector under
    /// `name`. In release builds (`!cfg(debug_assertions)`) this is a
    /// no-op pass-through so call sites stay free of `#[cfg]` lines.
    ///
    /// Idempotent on repeated calls — the latest registration wins.
    /// The registration drops automatically when the last
    /// `SelectionModel` handle is freed (the strong adapter `Rc` lives
    /// inside a shared holder; the registry holds only a `Weak`).
    pub fn debug_named(self, _name: impl Into<String>) -> Self {
        #[cfg(debug_assertions)]
        {
            let adapter: Rc<dyn crate::debug_registry::ModelDebug> = Rc::new(SelectionModelDebug {
                selection: self.selection.clone(),
                mode: self.mode,
            });
            crate::debug_registry::register(_name.into(), Rc::downgrade(&adapter));
            *self.debug_adapter_holder.borrow_mut() = Some(adapter);
        }
        self
    }
}

#[cfg(debug_assertions)]
struct SelectionModelDebug {
    selection: Signal<BTreeSet<usize>>,
    mode: SelectionMode,
}

#[cfg(debug_assertions)]
impl crate::debug_registry::ModelDebug for SelectionModelDebug {
    fn kind(&self) -> &'static str {
        "SelectionModel"
    }
    fn len(&self) -> usize {
        self.selection.get().len()
    }
    fn debug_dump(&self, out: &mut dyn std::fmt::Write) {
        let _ = writeln!(out, "mode = {:?}", self.mode);
        let sel = self.selection.get();
        if sel.is_empty() {
            let _ = writeln!(out, "(empty)");
            return;
        }
        for i in sel.iter() {
            let _ = writeln!(out, "[{}]", i);
        }
    }
}

impl std::fmt::Debug for SelectionModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SelectionModel")
            .field("mode", &self.mode)
            .field("selected_count", &self.selection.get().len())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn single_select() {
        let model = SelectionModel::new(SelectionMode::Single);
        model.select(2);
        assert!(model.is_selected(2));
        assert!(!model.is_selected(0));
        assert_eq!(model.selected_indices(), vec![2]);

        model.select(5);
        assert!(!model.is_selected(2));
        assert!(model.is_selected(5));
    }

    #[test]
    fn multi_select_toggle() {
        let model = SelectionModel::new(SelectionMode::Multi);
        model.toggle(1);
        model.toggle(3);
        assert!(model.is_selected(1));
        assert!(model.is_selected(3));
        assert_eq!(model.count(), 2);

        model.toggle(1);
        assert!(!model.is_selected(1));
        assert!(model.is_selected(3));
    }

    #[test]
    fn multi_select_extend_range() {
        let model = SelectionModel::new(SelectionMode::Multi);
        model.select(2); // anchor at 2
        model.extend_to(5); // extend from 2 to 5
        assert_eq!(model.selected_indices(), vec![2, 3, 4, 5]);
    }

    #[test]
    fn extend_backwards() {
        let model = SelectionModel::new(SelectionMode::Multi);
        model.select(5);
        model.extend_to(2);
        assert_eq!(model.selected_indices(), vec![2, 3, 4, 5]);
    }

    #[test]
    fn select_all() {
        let model = SelectionModel::new(SelectionMode::Multi);
        model.select_all(5);
        assert_eq!(model.selected_indices(), vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn select_indices_replaces_then_adds() {
        let model = SelectionModel::new(SelectionMode::Multi);
        model.select(1);
        // Non-additive replaces.
        model.select_indices([4, 5], false);
        assert_eq!(model.selected_indices(), vec![4, 5]);
        // Additive unions.
        model.select_indices([2], true);
        assert_eq!(model.selected_indices(), vec![2, 4, 5]);
    }

    #[test]
    fn clear() {
        let model = SelectionModel::new(SelectionMode::Multi);
        model.select_all(3);
        model.clear();
        assert_eq!(model.count(), 0);
    }

    #[test]
    fn none_mode_ignores_all() {
        let model = SelectionModel::new(SelectionMode::None);
        model.select(1);
        assert_eq!(model.count(), 0);
        model.toggle(2);
        assert_eq!(model.count(), 0);
        model.select_all(10);
        assert_eq!(model.count(), 0);
    }

    #[test]
    fn adjust_for_insert() {
        let model = SelectionModel::new(SelectionMode::Multi);
        model.toggle(1);
        model.toggle(3);
        // Insert 2 items at index 2
        model.adjust_for_insert(2, 2);
        // 1 stays, 3 shifts to 5
        assert_eq!(model.selected_indices(), vec![1, 5]);
    }

    #[test]
    fn adjust_for_remove() {
        let model = SelectionModel::new(SelectionMode::Multi);
        model.toggle(1);
        model.toggle(3);
        model.toggle(5);
        // Remove 1 item at index 3
        model.adjust_for_remove(3, 1);
        // 1 stays, 3 removed, 5 shifts to 4
        assert_eq!(model.selected_indices(), vec![1, 4]);
    }

    #[test]
    fn adjust_for_move_follows_the_moved_item() {
        // [A,B,C,D], select A(0). move A from 0 to 2 -> [B,C,A,D].
        let model = SelectionModel::new(SelectionMode::Multi);
        model.toggle(0);
        model.adjust_for_move(0, 2, 1);
        assert_eq!(model.selected_indices(), vec![2], "selection followed A");
    }

    #[test]
    fn adjust_for_move_shifts_a_bystander_selection() {
        // [A,B,C,D], select B(1). move A from 0 to 2 -> [B,C,A,D]; B is now 0.
        let model = SelectionModel::new(SelectionMode::Multi);
        model.toggle(1);
        model.adjust_for_move(0, 2, 1);
        assert_eq!(model.selected_indices(), vec![0], "B shifted down to 0");
    }

    #[test]
    fn adjust_for_move_backwards() {
        // [A,B,C,D], select D(3). move D from 3 to 1 -> [A,D,B,C].
        let model = SelectionModel::new(SelectionMode::Multi);
        model.toggle(3);
        model.adjust_for_move(3, 1, 1);
        assert_eq!(model.selected_indices(), vec![1]);
    }

    #[test]
    fn signal_reactivity() {
        use std::cell::Cell;
        use std::rc::Rc;

        let model = SelectionModel::new(SelectionMode::Single);
        let signal = model.selection_signal();
        let changed = Rc::new(Cell::new(false));
        let c = changed.clone();
        let _handle = signal.observe(move |_| c.set(true));

        model.select(3);
        assert!(changed.get());
    }

    #[test]
    fn single_mode_extend_acts_as_select() {
        let model = SelectionModel::new(SelectionMode::Single);
        model.select(1);
        model.extend_to(5);
        // In single mode, extend_to just selects
        assert_eq!(model.selected_indices(), vec![5]);
    }
}