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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! `ChartSelection` — point-level selection state for chart widgets.
//!
//! [`ChartSelection`] manages which `(series, point index)` pairs are
//! selected across a [`crate::ChartModel`] — the chart counterpart of
//! [`crate::SelectionModel`] (flat lists) and
//! [`crate::KeyedSelectionModel`] (keyed collections). It is a
//! share-by-clone handle: pass a clone to each chart that should share
//! selection state. The current selection is exposed as a reactive
//! `Signal<HashSet<(SeriesId, usize)>>` so widgets can bind to it without
//! polling.
//!
//! `HashSet` (not `BTreeSet`) is used because [`SeriesId`] is intentionally
//! **not** `Ord` (it's an opaque SlotMap key, mirroring [`crate::NodeId`]) —
//! there is no natural ordering across series, only within one series'
//! point indices. This is the same rationale as
//! [`crate::KeyedSelectionModel`], which uses `HashSet<K>` for the same
//! reason.
//!
//! Three selection behaviours are available via
//! [`SelectionMode`]: `None`, `Single`, and `Multi`
//! (toggle + anchor-based range extension). [`ChartSelection::extend_to`]
//! only extends within the anchor's own series — a cross-series "range" has
//! no natural order, so it falls back to a single-point select.
//! [`ChartSelection::adjust`] keeps selected points consistent as the
//! source model mutates (series removed, points inserted/removed) — call it
//! from your own model observer, or skip the wiring entirely with
//! [`ChartSelection::attached`] (equivalently, [`ChartSelection::attach`] on
//! an existing selection), which subscribes internally and calls `adjust`
//! for you, the same way [`crate::ChartWindow`]/[`crate::ChartAggregate`]
//! self-wire in their own constructors. Forgetting to wire `adjust` up
//! manually otherwise leaves the selection silently stale after a mutation.
//!
//! ```rust
//! # use teksilo_data::{ChartModel, ChartSelection, SelectionMode};
//! let model: ChartModel<i32> = ChartModel::new();
//! let s = model.add_series("s");
//! for i in 0..5 {
//!     model.push_point(s, i, i as f32);
//! }
//!
//! let sel = ChartSelection::attached(SelectionMode::Multi, &model);
//! sel.select_point(s, 1);
//! sel.extend_to(s, 3);
//! assert_eq!(sel.count(), 3); // (s,1), (s,2), (s,3)
//!
//! model.remove_point(s, 0); // upstream mutation — no manual adjust() call
//! assert_eq!(sel.count(), 3); // (s,0), (s,1), (s,2) — shifted down
//!
//! sel.clear();
//! assert_eq!(sel.count(), 0);
//! ```

use std::cell::RefCell;
use std::collections::HashSet;
use std::rc::Rc;

use teksilo_core::ObserverHandle;
use teksilo_core::signal::Signal;

use crate::chart_change::{ChartChange, SeriesId};
use crate::chart_model::ChartModel;
use crate::selection_model::SelectionMode;

/// Point-level selection state for a chart, keyed by `(series, point
/// index)`. See module documentation for semantics.
pub struct ChartSelection {
    mode: SelectionMode,
    selection: Signal<HashSet<(SeriesId, usize)>>,
    /// Anchor point for range extension. Shared via `Rc` so clones see the
    /// same anchor state.
    anchor: Rc<RefCell<Option<(SeriesId, usize)>>>,
    /// Holder for an [`attach`](Self::attach)ed model subscription. Shared
    /// across clones (like `anchor`) so the subscription stays alive as
    /// long as any handle to this selection does, and re-attaching (or
    /// every clone dropping) tears down the previous one.
    attach_handle: Rc<RefCell<Option<ObserverHandle>>>,
    /// Strong holder for the debug-registry adapter. Shared across clones;
    /// once all `ChartSelection` 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 ChartSelection {
    /// Create a new chart selection with the given mode.
    pub fn new(mode: SelectionMode) -> Self {
        Self {
            mode,
            selection: Signal::new(HashSet::new()),
            anchor: Rc::new(RefCell::new(None)),
            attach_handle: Rc::new(RefCell::new(None)),
            #[cfg(debug_assertions)]
            debug_adapter_holder: Rc::new(RefCell::new(None)),
        }
    }

    /// Create a selection that self-wires to `model`: every [`ChartChange`]
    /// the model emits is automatically routed through [`Self::adjust`], so
    /// a point removed or shifted upstream never leaves a stale selected
    /// index behind. Equivalent to `ChartSelection::new(mode)` plus
    /// `model.observe_changes(|c| sel.adjust(c))`, minus the easy-to-forget
    /// wiring — mirrors how [`crate::ChartWindow`] and
    /// [`crate::ChartAggregate`] self-wire in their own constructors. The
    /// manual [`Self::adjust`] path still works — call it yourself instead
    /// if you'd rather relay through a custom change pipeline.
    pub fn attached<T: 'static>(mode: SelectionMode, model: &ChartModel<T>) -> Self {
        let sel = Self::new(mode);
        sel.attach(model);
        sel
    }

    /// Subscribe this selection to `model`'s changes, applying
    /// [`Self::adjust`] on every [`ChartChange`]. The subscription is held
    /// internally (shared across clones — see [`Clone`]), so it stays alive
    /// as long as any handle to this selection does; calling `attach`
    /// again (on this handle or any clone) drops the previous subscription
    /// and installs the new one.
    ///
    /// The subscription closure captures only `selection` + `anchor`, not a
    /// full `Self` — capturing `Self` would pull in `attach_handle` too,
    /// which holds this very `ObserverHandle`, forming an `Rc` cycle that
    /// would leak the subscription instead of tearing down when every
    /// `ChartSelection` handle drops.
    pub fn attach<T: 'static>(&self, model: &ChartModel<T>) {
        let selection = self.selection.clone();
        let anchor = self.anchor.clone();
        let handle = model.observe_changes(move |change| {
            Self::adjust_state(&selection, &anchor, change);
        });
        *self.attach_handle.borrow_mut() = Some(handle);
    }

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

    /// A clone of the selection signal for reactive binding.
    pub fn selection_signal(&self) -> Signal<HashSet<(SeriesId, usize)>> {
        self.selection.clone()
    }

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

    /// The currently selected points (unordered snapshot).
    pub fn selected_points(&self) -> Vec<(SeriesId, usize)> {
        self.selection.get().into_iter().collect()
    }

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

    /// Select a single point, clearing the previous selection and setting
    /// the anchor.
    pub fn select_point(&self, series: SeriesId, index: usize) {
        if self.mode == SelectionMode::None {
            return;
        }
        let mut set = HashSet::new();
        set.insert((series, index));
        self.selection.set(set);
        *self.anchor.borrow_mut() = Some((series, index));
    }

    /// Toggle a point (Ctrl+click in Multi mode; acts as `select_point` in
    /// Single mode).
    pub fn toggle_point(&self, series: SeriesId, index: usize) {
        match self.mode {
            SelectionMode::None => {}
            SelectionMode::Single => self.select_point(series, index),
            SelectionMode::Multi => {
                let key = (series, index);
                let mut set = self.selection.get();
                if set.contains(&key) {
                    set.remove(&key);
                } else {
                    set.insert(key);
                }
                self.selection.set(set);
                *self.anchor.borrow_mut() = Some(key);
            }
        }
    }

    /// Extend the selection from the anchor to `(series, target)` (for
    /// Shift+click). Only extends **within the anchor's own series** — if
    /// the anchor is unset or belongs to a different series, falls back to
    /// a single-point select of `(series, target)`.
    pub fn extend_to(&self, series: SeriesId, target: usize) {
        match self.mode {
            SelectionMode::None => {}
            SelectionMode::Single => self.select_point(series, target),
            SelectionMode::Multi => {
                let anchor = *self.anchor.borrow();
                let Some((a_series, a_index)) = anchor else {
                    self.select_point(series, target);
                    return;
                };
                if a_series != series {
                    self.select_point(series, target);
                    return;
                }
                let start = a_index.min(target);
                let end = a_index.max(target);
                let mut set = self.selection.get();
                for i in start..=end {
                    set.insert((series, i));
                }
                self.selection.set(set);
                // Anchor stays put.
            }
        }
    }

    /// Replace the selection with `points` (or, when `additive`, union
    /// them into the current selection). Used by rubber-band / marquee
    /// selection. In `Single` mode an arbitrary one wins; `None` mode is a
    /// no-op.
    pub fn select_points(
        &self,
        points: impl IntoIterator<Item = (SeriesId, usize)>,
        additive: bool,
    ) {
        if self.mode == SelectionMode::None {
            return;
        }
        let mut set = if additive {
            self.selection.get()
        } else {
            HashSet::new()
        };
        set.extend(points);
        if self.mode == SelectionMode::Single && set.len() > 1 {
            let keep = set.iter().next().copied();
            set = keep.into_iter().collect();
        }
        self.selection.set(set);
    }

    /// Clear the selection and anchor.
    pub fn clear(&self) {
        self.selection.set(HashSet::new());
        *self.anchor.borrow_mut() = None;
    }

    /// React to an upstream [`ChartChange`], keeping selection consistent
    /// with the model: a removed or wholesale-replaced series drops its
    /// selected points (and the anchor, if it pointed there); point
    /// insertions/removals shift or drop indices within their series.
    /// Series metadata changes (rename/recolor/visibility/move/insert) and
    /// in-place point updates never affect which points are selected.
    pub fn adjust(&self, change: &ChartChange) {
        Self::adjust_state(&self.selection, &self.anchor, change);
    }

    /// The body of [`Self::adjust`], taking `selection`/`anchor` directly
    /// rather than `&self` — used by [`Self::attach`]'s subscription
    /// closure, which must **not** capture a full `Self` (that would
    /// capture `attach_handle` too, which holds the very `ObserverHandle`
    /// the closure lives inside: an `Rc` cycle that would leak the
    /// subscription forever instead of tearing down when every
    /// `ChartSelection` handle drops).
    fn adjust_state(
        selection: &Signal<HashSet<(SeriesId, usize)>>,
        anchor: &Rc<RefCell<Option<(SeriesId, usize)>>>,
        change: &ChartChange,
    ) {
        match change {
            ChartChange::SeriesRemoved { series } | ChartChange::SeriesDataReplaced { series } => {
                let series = *series;
                let old = selection.get();
                let new: HashSet<(SeriesId, usize)> =
                    old.iter().filter(|(s, _)| *s != series).copied().collect();
                if new.len() != old.len() {
                    selection.set(new);
                }
                let drop_anchor = anchor.borrow().as_ref().is_some_and(|(s, _)| *s == series);
                if drop_anchor {
                    *anchor.borrow_mut() = None;
                }
            }
            ChartChange::PointsInserted { series, range } => {
                let series = *series;
                let start = range.start;
                let count = range.end - range.start;
                let old = selection.get();
                let new: HashSet<(SeriesId, usize)> = old
                    .iter()
                    .map(|&(s, i)| {
                        if s == series && i >= start {
                            (s, i + count)
                        } else {
                            (s, i)
                        }
                    })
                    .collect();
                if new != old {
                    selection.set(new);
                }
                let mut anchor = anchor.borrow_mut();
                if let Some((s, i)) = *anchor
                    && s == series
                    && i >= start
                {
                    *anchor = Some((s, i + count));
                }
            }
            ChartChange::PointsRemoved { series, range } => {
                let series = *series;
                let start = range.start;
                let end = range.end;
                let count = range.end - range.start;
                let old = selection.get();
                let new: HashSet<(SeriesId, usize)> = old
                    .iter()
                    .filter_map(|&(s, i)| {
                        if s != series {
                            return Some((s, i));
                        }
                        if i < start {
                            Some((s, i))
                        } else if i >= end {
                            Some((s, i - count))
                        } else {
                            None
                        }
                    })
                    .collect();
                if new != old {
                    selection.set(new);
                }
                let mut anchor = anchor.borrow_mut();
                if let Some((s, i)) = *anchor
                    && s == series
                {
                    if i >= end {
                        *anchor = Some((s, i - count));
                    } else if i >= start {
                        *anchor = None;
                    }
                }
            }
            ChartChange::Reset => {
                selection.set(HashSet::new());
                *anchor.borrow_mut() = None;
            }
            // Series metadata and in-place point updates don't change
            // which points are selected.
            ChartChange::SeriesInserted { .. }
            | ChartChange::SeriesMoved { .. }
            | ChartChange::SeriesRenamed { .. }
            | ChartChange::SeriesColorChanged { .. }
            | ChartChange::SeriesPatternChanged { .. }
            | ChartChange::SeriesVisibilityChanged { .. }
            | ChartChange::PointUpdated { .. } => {}
        }
    }

    /// Drop any selected point for which `exists` returns false.
    pub fn prune(&self, exists: impl Fn(SeriesId, usize) -> bool) {
        let old = self.selection.get();
        let new: HashSet<(SeriesId, usize)> = old
            .iter()
            .filter(|(s, i)| exists(*s, *i))
            .copied()
            .collect();
        if new.len() != old.len() {
            self.selection.set(new);
        }
        let drop_anchor = self
            .anchor
            .borrow()
            .as_ref()
            .is_some_and(|(s, i)| !exists(*s, *i));
        if drop_anchor {
            *self.anchor.borrow_mut() = None;
        }
    }
}

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

impl ChartSelection {
    /// Register this selection 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 `ChartSelection`
    /// 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(ChartSelectionDebug {
                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 ChartSelectionDebug {
    selection: Signal<HashSet<(SeriesId, usize)>>,
    mode: SelectionMode,
}

#[cfg(debug_assertions)]
impl crate::debug_registry::ModelDebug for ChartSelectionDebug {
    fn kind(&self) -> &'static str {
        "ChartSelection"
    }
    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 (s, i) in sel.iter() {
            let _ = writeln!(out, "{:?}[{}]", s, i);
        }
    }
}

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

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

    fn two_series() -> (SeriesId, SeriesId) {
        let model: ChartModel<i32> = ChartModel::new();
        let a = model.add_series("a");
        let b = model.add_series("b");
        (a, b)
    }

    fn set(points: impl IntoIterator<Item = (SeriesId, usize)>) -> HashSet<(SeriesId, usize)> {
        points.into_iter().collect()
    }

    #[test]
    fn select_toggle_extend_within_series() {
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_point(a, 2);
        sel.extend_to(a, 5);
        assert_eq!(
            sel.selection_signal().get(),
            set([(a, 2), (a, 3), (a, 4), (a, 5)])
        );
    }

    #[test]
    fn toggle_deselects() {
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.toggle_point(a, 1);
        assert!(sel.is_selected(a, 1));
        sel.toggle_point(a, 1);
        assert!(!sel.is_selected(a, 1));
    }

    #[test]
    fn extend_backwards_within_series() {
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_point(a, 5);
        sel.extend_to(a, 2);
        assert_eq!(
            sel.selection_signal().get(),
            set([(a, 2), (a, 3), (a, 4), (a, 5)])
        );
    }

    #[test]
    fn cross_series_extend_falls_back_to_single_select() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_point(a, 2); // anchor (a, 2)
        sel.extend_to(b, 3);
        assert_eq!(sel.selection_signal().get(), set([(b, 3)]));
    }

    #[test]
    fn select_points_additive_and_replace() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_points([(a, 0), (a, 1)], false);
        assert_eq!(sel.count(), 2);
        sel.select_points([(b, 0)], true);
        assert_eq!(sel.selection_signal().get(), set([(a, 0), (a, 1), (b, 0)]));
        sel.select_points([(b, 1)], false);
        assert_eq!(sel.selection_signal().get(), set([(b, 1)]));
    }

    #[test]
    fn none_mode_ignores_all() {
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::None);
        sel.select_point(a, 0);
        sel.toggle_point(a, 1);
        sel.select_points([(a, 2)], false);
        assert_eq!(sel.count(), 0);
    }

    #[test]
    fn single_mode_extend_acts_as_select() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Single);
        sel.select_point(a, 1);
        sel.extend_to(b, 5);
        assert_eq!(sel.selection_signal().get(), set([(b, 5)]));
    }

    #[test]
    fn adjust_drops_on_series_removed() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_points([(a, 0), (a, 1), (b, 0)], false);
        sel.adjust(&ChartChange::SeriesRemoved { series: a });
        assert_eq!(sel.selection_signal().get(), set([(b, 0)]));
    }

    #[test]
    fn adjust_drops_anchor_on_series_removed() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_point(a, 0); // anchor = (a, 0)
        sel.adjust(&ChartChange::SeriesRemoved { series: a });
        // Anchor was dropped; extend_to now falls back to a single select.
        sel.extend_to(b, 3);
        assert_eq!(sel.selection_signal().get(), set([(b, 3)]));
    }

    #[test]
    fn adjust_drops_on_series_data_replaced() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_points([(a, 0), (b, 0)], false);
        sel.adjust(&ChartChange::SeriesDataReplaced { series: a });
        assert_eq!(sel.selection_signal().get(), set([(b, 0)]));
    }

    #[test]
    fn adjust_clears_on_reset() {
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_point(a, 0);
        sel.adjust(&ChartChange::Reset);
        assert_eq!(sel.count(), 0);
    }

    #[test]
    fn adjust_shifts_on_points_inserted() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_points([(a, 1), (a, 3), (b, 1)], false);
        sel.adjust(&ChartChange::PointsInserted {
            series: a,
            range: 2..4,
        });
        assert_eq!(sel.selection_signal().get(), set([(a, 1), (a, 5), (b, 1)]));
    }

    #[test]
    fn adjust_shifts_and_drops_on_points_removed() {
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_points([(a, 1), (a, 3), (a, 5)], false);
        sel.adjust(&ChartChange::PointsRemoved {
            series: a,
            range: 2..4,
        });
        // index 1 stays; index 3 dropped (inside the removed range); index 5 shifts to 3.
        assert_eq!(sel.selection_signal().get(), set([(a, 1), (a, 3)]));
    }

    #[test]
    fn adjust_ignores_metadata_and_point_updated() {
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_point(a, 2);
        sel.adjust(&ChartChange::SeriesInserted {
            index: 0,
            series: a,
        });
        sel.adjust(&ChartChange::SeriesMoved {
            series: a,
            from: 0,
            to: 1,
        });
        sel.adjust(&ChartChange::SeriesRenamed { series: a });
        sel.adjust(&ChartChange::SeriesColorChanged { series: a });
        sel.adjust(&ChartChange::SeriesVisibilityChanged { series: a });
        sel.adjust(&ChartChange::PointUpdated {
            series: a,
            index: 2,
        });
        assert_eq!(sel.selection_signal().get(), set([(a, 2)]));
    }

    #[test]
    fn prune_drops_missing_points() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_points([(a, 0), (a, 1), (b, 0)], false);
        sel.prune(|s, i| !(s == a && i == 1));
        assert_eq!(sel.selection_signal().get(), set([(a, 0), (b, 0)]));
    }

    #[test]
    fn prune_drops_anchor_when_missing() {
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_point(a, 3); // anchor = (a, 3)
        sel.prune(|_, _| false);
        sel.extend_to(a, 9);
        // Anchor was pruned -> extend_to falls back to single-select.
        assert_eq!(sel.selection_signal().get(), set([(a, 9)]));
    }

    #[test]
    fn signal_reactivity() {
        use std::cell::Cell;
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Single);
        let signal = sel.selection_signal();
        let changed = Rc::new(Cell::new(false));
        let c = changed.clone();
        let _handle = signal.observe(move |_| c.set(true));
        sel.select_point(a, 0);
        assert!(changed.get());
    }

    #[test]
    fn clone_shares_selection_and_anchor() {
        let (a, b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        let clone = sel.clone();
        sel.select_point(a, 1);
        assert!(clone.is_selected(a, 1));
        clone.extend_to(a, 3); // uses the shared anchor from `sel`
        assert_eq!(sel.selection_signal().get(), set([(a, 1), (a, 2), (a, 3)]));
        let _ = b;
    }

    // ── attach / attached ───────────────────────────────────────────────

    #[test]
    fn attached_shifts_selection_on_point_removed_before_it() {
        let model: ChartModel<i32> = ChartModel::new();
        let s = model.add_series("s");
        for i in 0..5 {
            model.push_point(s, i, i as f32);
        }
        let sel = ChartSelection::attached(SelectionMode::Multi, &model);
        sel.select_point(s, 3);
        assert!(sel.is_selected(s, 3));

        // Remove the two points before index 3 — it must auto-shift to 1,
        // with no manual `sel.adjust(...)` call from the test.
        model.remove_point(s, 0);
        model.remove_point(s, 0);

        assert!(!sel.is_selected(s, 3));
        assert!(sel.is_selected(s, 1));
    }

    #[test]
    fn attach_on_a_manually_constructed_selection_wires_it_up() {
        let model: ChartModel<i32> = ChartModel::new();
        let s = model.add_series("s");
        model.push_point(s, 0, 0.0);
        model.push_point(s, 1, 1.0);

        let sel = ChartSelection::new(SelectionMode::Single);
        sel.select_point(s, 1);
        sel.attach(&model); // not attached at construction time

        model.remove_point(s, 0);
        assert!(sel.is_selected(s, 0), "index 1 shifted down to 0");
    }

    #[test]
    fn manual_adjust_still_works_without_attach() {
        // The pre-existing manual wiring path keeps working — attach is
        // additive sugar, not a replacement.
        let (a, _b) = two_series();
        let sel = ChartSelection::new(SelectionMode::Multi);
        sel.select_point(a, 3);
        sel.adjust(&ChartChange::PointsRemoved {
            series: a,
            range: 0..2,
        });
        assert!(sel.is_selected(a, 1));
    }

    #[test]
    fn attach_does_not_leak_the_subscription_via_a_reference_cycle() {
        let model: ChartModel<i32> = ChartModel::new();
        let sel = ChartSelection::attached(SelectionMode::Multi, &model);
        let weak_anchor = Rc::downgrade(&sel.anchor);
        let weak_attach_handle = Rc::downgrade(&sel.attach_handle);

        drop(sel);

        assert!(
            weak_anchor.upgrade().is_none(),
            "anchor must not be kept alive by the subscription closure"
        );
        assert!(
            weak_attach_handle.upgrade().is_none(),
            "attach_handle must not be kept alive by its own subscription"
        );
    }
}