Skip to main content

teksilo_data/
chart_window.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! `ChartWindow<T>` — a "last N points per series" streaming projection over
5//! a [`crate::ChartModel`].
6//!
7//! Wraps a [`ChartModel<T>`](crate::ChartModel) and exposes the tail
8//! `window_size` points of every series — the live-scrolling-strip-chart
9//! pattern (a sensor feed, a log-rate graph, a stock ticker). Unlike
10//! [`crate::ChartAggregate`], `ChartWindow` copies **no point data**: it
11//! tracks, per series, the source index of the window's first visible point
12//! (`starts`) and delegates every read straight through to the source. That
13//! means a `ChartWindow<T>` needs no `T: Clone` bound at all.
14//!
15//! ## Reactivity
16//!
17//! The upstream [`ChartChange`] stream is translated, not collapsed to a
18//! blanket `Reset` (unlike [`crate::SortFilterListModel`], where an
19//! arbitrary sort-key move makes fine-grained translation unsafe — a
20//! fixed-size tail window has no such hazard): a tail append into a full
21//! window becomes a `PointsRemoved` + `PointsInserted` pair (the window
22//! slides), a tail append into a still-growing window becomes a plain
23//! `PointsInserted`, and symmetrically a **tail removal** (trimming the
24//! series' own end — e.g. discarding a bad trailing reading) becomes the
25//! mirror-image `PointsRemoved` + `PointsInserted` pair: points beyond the
26//! new total drop out of the window, and if the window slid backward to
27//! stay full, the newly-uncovered prefix is revealed as an insertion.
28//! Anything that isn't a clean tail append/removal (a mid-series insert or
29//! removal) falls back to a per-series rebuild reported as
30//! `SeriesDataReplaced`.
31//!
32//! ```ignore
33//! use teksilo_data::{ChartModel, ChartWindow};
34//! let model: ChartModel<i32> = ChartModel::new();
35//! let s = model.add_series("sensor");
36//! for i in 0..100 {
37//!     model.push_point(s, i, i as f32);
38//! }
39//! let window = ChartWindow::new(model.clone(), 10);
40//! assert_eq!(window.point_count(s), 10); // last 10 points only
41//! ```
42
43use std::cell::Cell;
44use std::cell::RefCell;
45use std::collections::HashMap;
46use std::rc::Rc;
47
48use teksilo_core::color_prop::ColorProp;
49use teksilo_core::{ObserverHandle, Signal};
50
51use crate::chart_change::{ChartChange, SeriesId};
52use crate::chart_model::{ChartDatum, ChartModel, SeriesView};
53
54type SeriesIdsFn = Rc<dyn Fn() -> Vec<SeriesId>>;
55type PointCountFn = Rc<dyn Fn(SeriesId) -> usize>;
56type WithPointFn<T> = Rc<dyn Fn(SeriesId, usize, &dyn Fn(&ChartDatum<T>))>;
57type WithSeriesFn = Rc<dyn Fn(SeriesId, &dyn Fn(&str, Option<&ColorProp>, bool))>;
58type ObserveChartFn = Rc<dyn Fn(Box<dyn Fn(&ChartChange)>) -> ObserverHandle>;
59
60struct ObserverEntry {
61    id: u64,
62    callback: Rc<dyn Fn(&ChartChange)>,
63}
64
65struct ChartWindowInner<T: 'static> {
66    source: ChartModel<T>,
67    structure_version: Signal<u64>,
68    series_ids_fn: SeriesIdsFn,
69    point_count_fn: PointCountFn,
70    with_point_fn: WithPointFn<T>,
71    with_series_fn: WithSeriesFn,
72    window_size: usize,
73    /// Source index of window position 0, per series.
74    starts: HashMap<SeriesId, usize>,
75    /// First window-local index that may have changed, per series. See
76    /// [`ChartWindow::first_changed_index`].
77    divergence: HashMap<SeriesId, usize>,
78    observers: Vec<ObserverEntry>,
79    next_observer_id: u64,
80    _upstream_handle: Option<ObserverHandle>,
81}
82
83impl<T: 'static> ChartWindowInner<T> {
84    fn start_for(&self, series: SeriesId) -> usize {
85        let total = (self.point_count_fn)(series);
86        total.saturating_sub(self.window_size)
87    }
88
89    fn rebuild_series(&mut self, series: SeriesId) {
90        let start = self.start_for(series);
91        self.starts.insert(series, start);
92        self.divergence.insert(series, 0);
93    }
94
95    fn rebuild_all(&mut self) {
96        self.starts.clear();
97        self.divergence.clear();
98        for series in (self.series_ids_fn)() {
99            self.rebuild_series(series);
100        }
101    }
102
103    fn snapshot_callbacks(&self) -> Vec<Rc<dyn Fn(&ChartChange)>> {
104        self.observers.iter().map(|e| e.callback.clone()).collect()
105    }
106}
107
108/// A "last N points per series" streaming projection over a [`ChartModel<T>`].
109///
110/// See the module documentation for semantics.
111pub struct ChartWindow<T: 'static> {
112    inner: Rc<RefCell<ChartWindowInner<T>>>,
113}
114
115impl<T: 'static> ChartWindow<T> {
116    /// Wrap `source`, showing only the last `window_size` points of every
117    /// series.
118    pub fn new(source: ChartModel<T>, window_size: usize) -> Self {
119        let series_ids_fn: SeriesIdsFn = {
120            let m = source.clone();
121            Rc::new(move || m.series_ids())
122        };
123        let point_count_fn: PointCountFn = {
124            let m = source.clone();
125            Rc::new(move |series| m.point_count(series))
126        };
127        let with_point_fn: WithPointFn<T> = {
128            let m = source.clone();
129            Rc::new(move |series, idx, f| {
130                m.with_point(series, idx, |d| f(d));
131            })
132        };
133        let with_series_fn: WithSeriesFn = {
134            let m = source.clone();
135            Rc::new(move |series, f| {
136                m.with_series(series, |name, color, visible| f(name, color, visible));
137            })
138        };
139        let observe_fn: ObserveChartFn = {
140            let m = source.clone();
141            Rc::new(move |callback| m.observe_changes(move |change| callback(change)))
142        };
143
144        let inner = Rc::new(RefCell::new(ChartWindowInner {
145            source,
146            structure_version: Signal::new(0),
147            series_ids_fn,
148            point_count_fn,
149            with_point_fn,
150            with_series_fn,
151            window_size,
152            starts: HashMap::new(),
153            divergence: HashMap::new(),
154            observers: Vec::new(),
155            next_observer_id: 1,
156            _upstream_handle: None,
157        }));
158
159        inner.borrow_mut().rebuild_all();
160
161        let weak = Rc::downgrade(&inner);
162        let upstream_handle = (observe_fn)(Box::new(move |change| {
163            if let Some(strong) = weak.upgrade() {
164                translate_and_notify(&strong, change);
165            }
166        }));
167        inner.borrow_mut()._upstream_handle = Some(upstream_handle);
168
169        Self { inner }
170    }
171
172    /// The configured window size.
173    pub fn window_size(&self) -> usize {
174        self.inner.borrow().window_size
175    }
176
177    /// Change the window size, rebuilding every series and emitting
178    /// `ChartChange::Reset`.
179    pub fn set_window_size(&self, window_size: usize) {
180        let (callbacks, version) = {
181            let mut guard = self.inner.borrow_mut();
182            guard.window_size = window_size;
183            guard.rebuild_all();
184            (guard.snapshot_callbacks(), guard.structure_version.clone())
185        };
186        for cb in &callbacks {
187            cb(&ChartChange::Reset);
188        }
189        version.set(version.get().wrapping_add(1));
190    }
191
192    /// Access the source model. Visibility changes made by a legend are shared
193    /// with every other view of this model.
194    pub fn source(&self) -> ChartModel<T> {
195        self.inner.borrow().source.clone()
196    }
197
198    /// Reactive version for changes to the visible data or window size.
199    pub fn structure_version(&self) -> Signal<u64> {
200        self.inner.borrow().structure_version.clone()
201    }
202
203    /// Reactive version for source colors and patterns.
204    pub fn style_version(&self) -> Signal<u64> {
205        self.source().style_version()
206    }
207
208    /// Read windowed series as borrowed slices, without copying point data.
209    pub fn with_all_series<R>(&self, f: impl FnOnce(&[SeriesView<'_, T>]) -> R) -> R {
210        let source = self.source();
211        let size = self.window_size();
212        source.with_all_series(|views| {
213            let windowed: Vec<_> = views
214                .iter()
215                .map(|view| SeriesView {
216                    id: view.id,
217                    name: view.name,
218                    color: view.color,
219                    pattern: view.pattern,
220                    visible: view.visible,
221                    points: &view.points[view.points.len().saturating_sub(size)..],
222                })
223                .collect();
224            f(&windowed)
225        })
226    }
227
228    /// Read a single windowed series. Indices are relative to the window.
229    pub fn with_series_view<R>(
230        &self,
231        series: SeriesId,
232        f: impl FnOnce(SeriesView<'_, T>) -> R,
233    ) -> Option<R> {
234        let size = self.window_size();
235        self.source().with_series_view(series, |mut view| {
236            view.points = &view.points[view.points.len().saturating_sub(size)..];
237            f(view)
238        })
239    }
240
241    /// Number of series (same set as the source).
242    pub fn series_count(&self) -> usize {
243        (self.inner.borrow().series_ids_fn)().len()
244    }
245
246    /// The series ids, in the source's display order.
247    pub fn series_ids(&self) -> Vec<SeriesId> {
248        (self.inner.borrow().series_ids_fn)()
249    }
250
251    /// Number of points currently visible in the window for `series`.
252    pub fn point_count(&self, series: SeriesId) -> usize {
253        let guard = self.inner.borrow();
254        let total = (guard.point_count_fn)(series);
255        let start = guard
256            .starts
257            .get(&series)
258            .copied()
259            .unwrap_or_else(|| total.saturating_sub(guard.window_size));
260        total.saturating_sub(start)
261    }
262
263    /// Access a series' metadata (delegates straight through to the
264    /// source). Returns `None` if `series` is unknown.
265    pub fn with_series<R>(
266        &self,
267        series: SeriesId,
268        f: impl FnOnce(&str, Option<&ColorProp>, bool) -> R,
269    ) -> Option<R> {
270        let with_series_fn = self.inner.borrow().with_series_fn.clone();
271        let f_cell: Cell<Option<_>> = Cell::new(Some(f));
272        let slot: Cell<Option<R>> = Cell::new(None);
273        (with_series_fn)(series, &|name, color, visible| {
274            if let Some(f) = f_cell.take() {
275                slot.set(Some(f(name, color, visible)));
276            }
277        });
278        slot.into_inner()
279    }
280
281    /// Access the point at window-local `index` within `series`. Returns
282    /// `None` if `series` is unknown or `index` is outside the window.
283    pub fn with_point<R>(
284        &self,
285        series: SeriesId,
286        index: usize,
287        f: impl FnOnce(&ChartDatum<T>) -> R,
288    ) -> Option<R> {
289        let (with_point_fn, src_idx) = {
290            let guard = self.inner.borrow();
291            let total = (guard.point_count_fn)(series);
292            let start = guard
293                .starts
294                .get(&series)
295                .copied()
296                .unwrap_or_else(|| total.saturating_sub(guard.window_size));
297            let visible = total.saturating_sub(start);
298            // Bounds-check before computing `start + index` — `index` is
299            // caller-supplied and may be far out of range (e.g. usize::MAX),
300            // which would overflow the addition once the window has slid
301            // (start > 0).
302            if index >= visible {
303                return None;
304            }
305            (guard.with_point_fn.clone(), start + index)
306        };
307        let f_cell: Cell<Option<_>> = Cell::new(Some(f));
308        let slot: Cell<Option<R>> = Cell::new(None);
309        (with_point_fn)(series, src_idx, &|d: &ChartDatum<T>| {
310            if let Some(f) = f_cell.take() {
311                slot.set(Some(f(d)));
312            }
313        });
314        slot.into_inner()
315    }
316
317    /// Register an observer for translated window changes. Returns an
318    /// `ObserverHandle` — dropping it removes the callback.
319    pub fn observe_changes(&self, f: impl Fn(&ChartChange) + 'static) -> ObserverHandle {
320        let mut guard = self.inner.borrow_mut();
321        let id = guard.next_observer_id;
322        guard.next_observer_id += 1;
323        guard.observers.push(ObserverEntry {
324            id,
325            callback: Rc::new(f),
326        });
327        let inner = self.inner.clone();
328        ObserverHandle::new(
329            self.inner.clone(),
330            id,
331            Rc::new(move |observer_id| {
332                // A callback may own the last reference to another observer of
333                // this model: it is dropped only once the borrow is released.
334                let removed = {
335                    let mut guard = inner.borrow_mut();
336                    let index = guard.observers.iter().position(|e| e.id == observer_id);
337                    index.map(|i| guard.observers.remove(i))
338                };
339                drop(removed);
340            }),
341        )
342    }
343
344    /// First window-local index of `series` whose content may differ since
345    /// the latest translated change. Per-series (chart data is 2-level:
346    /// series, then points), unlike
347    /// [`SortFilterListModel::first_changed_index`](crate::SortFilterListModel::first_changed_index)'s
348    /// single flat value. `None` if `series` is unknown or unaffected yet.
349    pub fn first_changed_index(&self, series: SeriesId) -> Option<usize> {
350        self.inner.borrow().divergence.get(&series).copied()
351    }
352}
353
354/// Translate one upstream `ChartChange` into zero or more local changes,
355/// mutating `starts` / `divergence` as needed. See module docs.
356fn translate<T: 'static>(
357    inner: &mut ChartWindowInner<T>,
358    change: &ChartChange,
359) -> Vec<ChartChange> {
360    match change {
361        ChartChange::SeriesInserted { index, series } => {
362            let (index, series) = (*index, *series);
363            inner.starts.insert(series, 0);
364            inner.divergence.insert(series, 0);
365            vec![ChartChange::SeriesInserted { index, series }]
366        }
367        ChartChange::SeriesRemoved { series } => {
368            let series = *series;
369            inner.starts.remove(&series);
370            inner.divergence.remove(&series);
371            vec![ChartChange::SeriesRemoved { series }]
372        }
373        ChartChange::SeriesMoved { series, from, to } => vec![ChartChange::SeriesMoved {
374            series: *series,
375            from: *from,
376            to: *to,
377        }],
378        ChartChange::SeriesRenamed { series } => {
379            vec![ChartChange::SeriesRenamed { series: *series }]
380        }
381        ChartChange::SeriesColorChanged { series } => {
382            vec![ChartChange::SeriesColorChanged { series: *series }]
383        }
384        ChartChange::SeriesPatternChanged { series } => {
385            vec![ChartChange::SeriesPatternChanged { series: *series }]
386        }
387        ChartChange::SeriesVisibilityChanged { series } => {
388            vec![ChartChange::SeriesVisibilityChanged { series: *series }]
389        }
390        ChartChange::PointsInserted { series, range } => {
391            let series = *series;
392            let range = range.clone();
393            let window_size = inner.window_size;
394            let new_total = (inner.point_count_fn)(series);
395            let inserted = range.end - range.start;
396            let old_total = new_total - inserted;
397            let old_start = inner
398                .starts
399                .get(&series)
400                .copied()
401                .unwrap_or_else(|| old_total.saturating_sub(window_size));
402
403            if range.start != old_total {
404                // Not a tail append — a mid-series insert. Rebuild.
405                inner.rebuild_series(series);
406                return vec![ChartChange::SeriesDataReplaced { series }];
407            }
408
409            // Absolute recompute (mirrors `ChartAggregate::translate`'s
410            // `PointsInserted` branch): derive what the window shows from
411            // absolute source indices rather than assuming exactly one
412            // `shift`-sized block is evicted/appended. That assumption only
413            // holds once the window is already full — a multi-point tail
414            // append can take a not-yet-full window straight past full in
415            // one step, and treating that as a same-size slide emits an
416            // insertion range that's too short for the actual growth,
417            // landing past the end of a consumer's mirrored array.
418            let old_visible = old_total.saturating_sub(old_start);
419            let new_start = new_total.saturating_sub(window_size);
420            let new_visible = new_total.saturating_sub(new_start);
421            // Old-window entries below `new_start` are no longer in range;
422            // the rest (if any) survive as the new window's prefix.
423            let dropped = new_start.saturating_sub(old_start).min(old_visible);
424            let remaining = old_visible - dropped;
425
426            let mut out = Vec::new();
427            if dropped > 0 {
428                out.push(ChartChange::PointsRemoved {
429                    series,
430                    range: 0..dropped,
431                });
432            }
433            if new_visible > remaining {
434                out.push(ChartChange::PointsInserted {
435                    series,
436                    range: remaining..new_visible,
437                });
438            }
439            // A front-removal renumbers every surviving index, so the first
440            // index that may differ is 0; a pure append (no removal) leaves
441            // the old prefix untouched, so it's the position after it.
442            inner
443                .divergence
444                .insert(series, if dropped > 0 { 0 } else { remaining });
445            inner.starts.insert(series, new_start);
446            out
447        }
448        ChartChange::PointsRemoved { series, range } => {
449            let series = *series;
450            let range = range.clone();
451            let window_size = inner.window_size;
452            let new_total = (inner.point_count_fn)(series);
453            let removed = range.end - range.start;
454            let old_total = new_total + removed;
455            let old_start = inner
456                .starts
457                .get(&series)
458                .copied()
459                .unwrap_or_else(|| old_total.saturating_sub(window_size));
460
461            if range.end != old_total {
462                // Not a tail removal — a front/mid-series removal
463                // renumbers every point after it, including ones the
464                // window doesn't show. Rebuild.
465                inner.rebuild_series(series);
466                return vec![ChartChange::SeriesDataReplaced { series }];
467            }
468
469            // Tail-removal mirror of the `PointsInserted` tail-append
470            // branch above: absolute recompute from source indices rather
471            // than assuming a fixed-size slide. `new_start <= old_start`
472            // always holds here (removing points can only grow the window
473            // backward to keep it full, never shrink it forward) — the
474            // old window's front survives at a shifted local position, its
475            // tail (the removed points) is gone, and any newly-uncovered
476            // prefix below the old start is freshly revealed.
477            let old_visible = old_total.saturating_sub(old_start);
478            let new_start = new_total.saturating_sub(window_size);
479            let new_visible = new_total.saturating_sub(new_start);
480            // Old-window entries at or past `new_total` were removed; the
481            // rest (if any) survive as the front of the old window.
482            let survivors = new_total.saturating_sub(old_start).min(old_visible);
483            let removed_from_window = old_visible - survivors;
484            let revealed = old_start.saturating_sub(new_start);
485
486            let mut out = Vec::new();
487            if removed_from_window > 0 {
488                out.push(ChartChange::PointsRemoved {
489                    series,
490                    range: survivors..old_visible,
491                });
492            }
493            if revealed > 0 {
494                out.push(ChartChange::PointsInserted {
495                    series,
496                    range: 0..revealed,
497                });
498            }
499            // A revealed prefix renumbers every surviving index, so the
500            // first index that may differ is 0; otherwise the survivors
501            // (if any) are untouched and only the point past them changed.
502            inner.divergence.insert(
503                series,
504                if revealed > 0 {
505                    0
506                } else {
507                    survivors.min(new_visible)
508                },
509            );
510            inner.starts.insert(series, new_start);
511            out
512        }
513        ChartChange::PointUpdated { series, index } => {
514            let (series, index) = (*series, *index);
515            let start = inner.starts.get(&series).copied().unwrap_or(0);
516            if index >= start {
517                let local = index - start;
518                inner.divergence.insert(series, local);
519                vec![ChartChange::PointUpdated {
520                    series,
521                    index: local,
522                }]
523            } else {
524                vec![]
525            }
526        }
527        ChartChange::SeriesDataReplaced { series } => {
528            let series = *series;
529            inner.rebuild_series(series);
530            vec![ChartChange::SeriesDataReplaced { series }]
531        }
532        ChartChange::Reset => {
533            inner.rebuild_all();
534            vec![ChartChange::Reset]
535        }
536    }
537}
538
539fn translate_and_notify<T: 'static>(
540    inner: &Rc<RefCell<ChartWindowInner<T>>>,
541    change: &ChartChange,
542) {
543    let (changes, callbacks, version) = {
544        let mut guard = inner.borrow_mut();
545        let changes = translate(&mut guard, change);
546        (
547            changes,
548            guard.snapshot_callbacks(),
549            guard.structure_version.clone(),
550        )
551    };
552    for c in &changes {
553        for cb in &callbacks {
554            cb(c);
555        }
556    }
557    if changes.iter().any(|change| {
558        !matches!(
559            change,
560            ChartChange::SeriesColorChanged { .. } | ChartChange::SeriesPatternChanged { .. }
561        )
562    }) {
563        version.set(version.get().wrapping_add(1));
564    }
565}
566
567impl<T: 'static> Clone for ChartWindow<T> {
568    fn clone(&self) -> Self {
569        Self {
570            inner: self.inner.clone(),
571        }
572    }
573}
574
575impl<T: 'static> std::fmt::Debug for ChartWindow<T> {
576    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
577        let guard = self.inner.borrow();
578        f.debug_struct("ChartWindow")
579            .field("window_size", &guard.window_size)
580            .field("series_count", &(guard.series_ids_fn)().len())
581            .finish()
582    }
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588
589    fn one_series(n: usize) -> (ChartModel<i32>, SeriesId) {
590        let model: ChartModel<i32> = ChartModel::new();
591        let s = model.add_series("s");
592        for i in 0..n {
593            model.push_point(s, i as i32, i as f32);
594        }
595        (model, s)
596    }
597
598    fn track(window: &ChartWindow<i32>) -> (Rc<RefCell<Vec<ChartChange>>>, ObserverHandle) {
599        let log: Rc<RefCell<Vec<ChartChange>>> = Rc::new(RefCell::new(Vec::new()));
600        let l = log.clone();
601        let handle = window.observe_changes(move |c| l.borrow_mut().push(c.clone()));
602        (log, handle)
603    }
604
605    #[test]
606    fn initial_window_shows_only_the_tail() {
607        let (_model, s) = one_series(5);
608        let window = ChartWindow::new(_model, 3);
609        assert_eq!(window.point_count(s), 3);
610        let vals: Vec<f32> = (0..3)
611            .map(|i| window.with_point(s, i, |d| d.value).unwrap())
612            .collect();
613        assert_eq!(vals, vec![2.0, 3.0, 4.0]);
614    }
615
616    #[test]
617    fn with_point_out_of_range_returns_none_without_overflow() {
618        // Regression: `start + index` must be computed only after bounds-
619        // checking `index` — with a slid window (start > 0), an out-of-range
620        // `index` like `usize::MAX` would otherwise overflow the addition
621        // and panic (debug builds) instead of returning `None`.
622        let (model, s) = one_series(5);
623        let window = ChartWindow::new(model, 3); // window slid: start == 2
624        assert_eq!(window.with_point(s, usize::MAX, |d| d.value), None);
625    }
626
627    #[test]
628    fn full_window_shift_emits_removed_then_inserted() {
629        let (model, s) = one_series(3);
630        let window = ChartWindow::new(model.clone(), 3);
631        assert_eq!(window.point_count(s), 3);
632        let (log, _h) = track(&window);
633
634        model.push_point(s, 3, 3.0);
635
636        let entries = log.borrow();
637        assert_eq!(entries.len(), 2);
638        assert_eq!(
639            entries[0],
640            ChartChange::PointsRemoved {
641                series: s,
642                range: 0..1
643            }
644        );
645        assert_eq!(
646            entries[1],
647            ChartChange::PointsInserted {
648                series: s,
649                range: 2..3
650            }
651        );
652        drop(entries);
653
654        assert_eq!(window.point_count(s), 3);
655        let vals: Vec<f32> = (0..3)
656            .map(|i| window.with_point(s, i, |d| d.value).unwrap())
657            .collect();
658        assert_eq!(vals, vec![1.0, 2.0, 3.0]);
659    }
660
661    #[test]
662    fn partial_window_tail_append_emits_plain_inserted() {
663        let (model, s) = one_series(1);
664        let window = ChartWindow::new(model.clone(), 5);
665        let (log, _h) = track(&window);
666
667        model.push_point(s, 1, 1.0);
668
669        let entries = log.borrow();
670        assert_eq!(entries.len(), 1);
671        assert_eq!(
672            entries[0],
673            ChartChange::PointsInserted {
674                series: s,
675                range: 1..2
676            }
677        );
678        drop(entries);
679        assert_eq!(window.point_count(s), 2);
680    }
681
682    #[test]
683    fn mid_series_insert_falls_back_to_replace() {
684        let (model, s) = one_series(3);
685        let window = ChartWindow::new(model.clone(), 5);
686        let (log, _h) = track(&window);
687
688        model.insert_point(s, 1, 99, 99.0);
689
690        let entries = log.borrow();
691        assert_eq!(entries.len(), 1);
692        assert_eq!(entries[0], ChartChange::SeriesDataReplaced { series: s });
693        drop(entries);
694        assert_eq!(window.point_count(s), 4);
695    }
696
697    #[test]
698    fn front_removal_falls_back_to_replace() {
699        // Removing anything but the tail renumbers every later point,
700        // including ones the window doesn't show — must still rebuild.
701        let (model, s) = one_series(3);
702        let window = ChartWindow::new(model.clone(), 5);
703        let (log, _h) = track(&window);
704
705        model.remove_point(s, 0);
706
707        let entries = log.borrow();
708        assert_eq!(entries.len(), 1);
709        assert_eq!(entries[0], ChartChange::SeriesDataReplaced { series: s });
710        drop(entries);
711        assert_eq!(window.point_count(s), 2);
712    }
713
714    #[test]
715    fn partial_window_tail_removal_emits_plain_removed() {
716        // Window not full (5 points shown out of a 10-point capacity) —
717        // trimming the tail just shrinks it, nothing to reveal.
718        let (model, s) = one_series(5);
719        let window = ChartWindow::new(model.clone(), 10);
720        let (log, _h) = track(&window);
721
722        model.remove_point(s, 4); // the tail point
723
724        let entries = log.borrow();
725        assert_eq!(entries.len(), 1);
726        assert_eq!(
727            entries[0],
728            ChartChange::PointsRemoved {
729                series: s,
730                range: 4..5
731            }
732        );
733        drop(entries);
734        assert_eq!(window.point_count(s), 4);
735        let vals: Vec<f32> = (0..4)
736            .map(|i| window.with_point(s, i, |d| d.value).unwrap())
737            .collect();
738        assert_eq!(vals, vec![0.0, 1.0, 2.0, 3.0]);
739    }
740
741    #[test]
742    fn full_window_tail_removal_emits_removed_then_inserted() {
743        // Window full (shows the last 3 of 5) — trimming the tail slides it
744        // backward to reveal the point that just fell off the front.
745        let (model, s) = one_series(5); // window shows [2,3,4] -> [2.0,3.0,4.0]
746        let window = ChartWindow::new(model.clone(), 3);
747        assert_eq!(window.point_count(s), 3);
748        let (log, _h) = track(&window);
749
750        model.remove_point(s, 4); // remove the tail point (value 4.0)
751
752        let entries = log.borrow();
753        assert_eq!(entries.len(), 2);
754        assert_eq!(
755            entries[0],
756            ChartChange::PointsRemoved {
757                series: s,
758                range: 2..3
759            }
760        );
761        assert_eq!(
762            entries[1],
763            ChartChange::PointsInserted {
764                series: s,
765                range: 0..1
766            }
767        );
768        drop(entries);
769
770        assert_eq!(window.point_count(s), 3);
771        let vals: Vec<f32> = (0..3)
772            .map(|i| window.with_point(s, i, |d| d.value).unwrap())
773            .collect();
774        assert_eq!(vals, vec![1.0, 2.0, 3.0]);
775    }
776
777    #[test]
778    fn update_in_and_out_of_window() {
779        let (model, s) = one_series(5);
780        let window = ChartWindow::new(model.clone(), 2); // shows source indices 3,4
781        let (log, _h) = track(&window);
782
783        model.update_point(s, 4, 4, 40.0); // in window -> local index 1
784        model.update_point(s, 0, 0, 5.0); // out of window -> no emit
785
786        let entries = log.borrow();
787        assert_eq!(entries.len(), 1);
788        assert_eq!(
789            entries[0],
790            ChartChange::PointUpdated {
791                series: s,
792                index: 1
793            }
794        );
795        drop(entries);
796        assert_eq!(window.with_point(s, 1, |d| d.value), Some(40.0));
797    }
798
799    #[test]
800    fn reset_passes_through_and_rebuilds() {
801        let (model, s) = one_series(3);
802        let window = ChartWindow::new(model.clone(), 2);
803        let (log, _h) = track(&window);
804
805        model.clear();
806
807        assert_eq!(log.borrow().last(), Some(&ChartChange::Reset));
808        assert_eq!(window.point_count(s), 0);
809    }
810
811    #[test]
812    fn dropping_window_unregisters_upstream_observer() {
813        let model: ChartModel<i32> = ChartModel::new();
814        let before = model.observer_count();
815        let window = ChartWindow::new(model.clone(), 3);
816        assert_eq!(model.observer_count(), before + 1);
817        drop(window);
818        assert_eq!(model.observer_count(), before);
819    }
820
821    #[test]
822    fn set_window_size_rebuilds_and_emits_reset() {
823        let (model, s) = one_series(5);
824        let window = ChartWindow::new(model, 2);
825        assert_eq!(window.point_count(s), 2);
826        let (log, _h) = track(&window);
827
828        window.set_window_size(4);
829        assert_eq!(window.point_count(s), 4);
830        assert_eq!(log.borrow().last(), Some(&ChartChange::Reset));
831    }
832
833    #[test]
834    fn series_inserted_and_removed_pass_through() {
835        let model: ChartModel<i32> = ChartModel::new();
836        let window = ChartWindow::new(model.clone(), 3);
837        let (log, _h) = track(&window);
838
839        let s = model.add_series("new");
840        assert_eq!(
841            log.borrow().last(),
842            Some(&ChartChange::SeriesInserted {
843                index: 0,
844                series: s
845            })
846        );
847
848        model.remove_series(s);
849        assert_eq!(
850            log.borrow().last(),
851            Some(&ChartChange::SeriesRemoved { series: s })
852        );
853        assert_eq!(window.series_count(), 0);
854    }
855
856    #[test]
857    fn translate_multi_point_insert_not_full_to_overflow() {
858        // Regression: a bulk tail append (`range.len() > 1`) that takes a
859        // not-yet-full window straight past full must be handled by
860        // recomputing from absolute source indices, not by assuming exactly
861        // one fixed-size `shift` block is evicted/appended (that shortcut
862        // only holds once the window was already full). For this exact
863        // transition the old code emitted an insertion range too short for
864        // the actual growth, landing past the end of a consumer's mirrored
865        // array. `ChartModel` only ever emits length-1 `PointsInserted`
866        // ranges, so this builds a `ChartWindowInner` by hand (skipping
867        // `ChartWindow::new`'s auto-subscription, which would otherwise
868        // apply each push through the already-correct single-point path
869        // before there's a chance to test the batch one) and calls
870        // `translate` directly with a synthesized multi-point change.
871        let model: ChartModel<i32> = ChartModel::new();
872        let s = model.add_series("s");
873        model.push_point(s, 0, 0.0);
874        model.push_point(s, 1, 1.0); // model total: 2, window_size: 3 -> not full
875
876        let series_ids_fn: SeriesIdsFn = {
877            let m = model.clone();
878            Rc::new(move || m.series_ids())
879        };
880        let point_count_fn: PointCountFn = {
881            let m = model.clone();
882            Rc::new(move |series| m.point_count(series))
883        };
884        let with_point_fn: WithPointFn<i32> = {
885            let m = model.clone();
886            Rc::new(move |series, idx, f| {
887                m.with_point(series, idx, |d| f(d));
888            })
889        };
890        let with_series_fn: WithSeriesFn = {
891            let m = model.clone();
892            Rc::new(move |series, f| {
893                m.with_series(series, |name, color, visible| f(name, color, visible));
894            })
895        };
896
897        let mut inner = ChartWindowInner {
898            source: model.clone(),
899            structure_version: Signal::new(0),
900            series_ids_fn,
901            point_count_fn,
902            with_point_fn,
903            with_series_fn,
904            window_size: 3,
905            starts: HashMap::new(),
906            divergence: HashMap::new(),
907            observers: Vec::new(),
908            next_observer_id: 1,
909            _upstream_handle: None,
910        };
911        inner.rebuild_all(); // caches start == 0 for the not-yet-full 2-point window
912
913        // Bulk-append 2 more points directly to the model — `inner` isn't
914        // subscribed, so it still thinks the total is 2 while the model now
915        // reports 4, exactly what a batch-insert API would report as one
916        // `PointsInserted { range: 2..4 }`.
917        model.push_point(s, 2, 2.0);
918        model.push_point(s, 3, 3.0);
919
920        let changes = translate(
921            &mut inner,
922            &ChartChange::PointsInserted {
923                series: s,
924                range: 2..4,
925            },
926        );
927
928        // Old window [0,1] (len 2) -> new window [1,2,3] (len 3): drop the
929        // one element before the new start, then insert the two new ones
930        // after the one that survives — never a range past the mirror's end.
931        assert_eq!(
932            changes,
933            vec![
934                ChartChange::PointsRemoved {
935                    series: s,
936                    range: 0..1
937                },
938                ChartChange::PointsInserted {
939                    series: s,
940                    range: 1..3
941                },
942            ]
943        );
944    }
945
946    #[test]
947    fn translate_multi_point_tail_removal_from_full_to_not_full() {
948        // Mirror of `translate_multi_point_insert_not_full_to_overflow` for
949        // removal: a bulk tail trim (`range.len() > 1`) that takes a full
950        // window back below capacity must be handled by the same absolute
951        // recompute, not a fixed-size `shift` assumption (which only holds
952        // for a single-point removal). `ChartModel::remove_point` only ever
953        // emits length-1 `PointsRemoved` ranges, so this builds a
954        // `ChartWindowInner` by hand and calls `translate` directly with a
955        // synthesized multi-point change, exactly like the insert-side
956        // regression test above.
957        let model: ChartModel<i32> = ChartModel::new();
958        let s = model.add_series("s");
959        for i in 0..5 {
960            model.push_point(s, i, i as f32);
961        }
962
963        let series_ids_fn: SeriesIdsFn = {
964            let m = model.clone();
965            Rc::new(move || m.series_ids())
966        };
967        let point_count_fn: PointCountFn = {
968            let m = model.clone();
969            Rc::new(move |series| m.point_count(series))
970        };
971        let with_point_fn: WithPointFn<i32> = {
972            let m = model.clone();
973            Rc::new(move |series, idx, f| {
974                m.with_point(series, idx, |d| f(d));
975            })
976        };
977        let with_series_fn: WithSeriesFn = {
978            let m = model.clone();
979            Rc::new(move |series, f| {
980                m.with_series(series, |name, color, visible| f(name, color, visible));
981            })
982        };
983
984        let mut inner = ChartWindowInner {
985            source: model.clone(),
986            structure_version: Signal::new(0),
987            series_ids_fn,
988            point_count_fn,
989            with_point_fn,
990            with_series_fn,
991            window_size: 3,
992            starts: HashMap::new(),
993            divergence: HashMap::new(),
994            observers: Vec::new(),
995            next_observer_id: 1,
996            _upstream_handle: None,
997        };
998        inner.rebuild_all(); // caches start == 2 for the full 5-point window: [2,3,4]
999
1000        // Bulk-remove the last 3 points directly from the model — `inner`
1001        // isn't subscribed, so it still thinks the total is 5 while the
1002        // model now reports 2, exactly what a batch-remove API would
1003        // report as one `PointsRemoved { range: 2..5 }`.
1004        model.remove_point(s, 4);
1005        model.remove_point(s, 3);
1006        model.remove_point(s, 2);
1007
1008        let changes = translate(
1009            &mut inner,
1010            &ChartChange::PointsRemoved {
1011                series: s,
1012                range: 2..5,
1013            },
1014        );
1015
1016        // Old window [2,3,4] (len 3) -> new window [0,1] (len 2): every old
1017        // entry is gone (none survive below the new total of 2), and both
1018        // remaining source points are freshly revealed at the front.
1019        assert_eq!(
1020            changes,
1021            vec![
1022                ChartChange::PointsRemoved {
1023                    series: s,
1024                    range: 0..3
1025                },
1026                ChartChange::PointsInserted {
1027                    series: s,
1028                    range: 0..2
1029                },
1030            ]
1031        );
1032    }
1033}