1use std::cell::RefCell;
45use std::rc::Rc;
46
47use slotmap::SlotMap;
48
49use teksilo_core::ObserverHandle;
50use teksilo_core::color_prop::ColorProp;
51use teksilo_core::signal::Signal;
52
53use crate::chart_change::{ChartChange, SeriesId};
54use crate::series_pattern::SeriesPattern;
55
56#[derive(Debug, Clone)]
59pub struct ChartDatum<T> {
60 pub category: T,
61 pub value: f32,
62 pub color: Option<ColorProp>,
63}
64
65impl<T> ChartDatum<T> {
66 pub fn new(category: T, value: f32) -> Self {
67 Self {
68 category,
69 value,
70 color: None,
71 }
72 }
73
74 pub fn with_color(mut self, color: impl Into<ColorProp>) -> Self {
77 self.color = Some(color.into());
78 self
79 }
80}
81
82pub struct ChartSeries<T> {
89 pub name: String,
90 pub color: Option<ColorProp>,
91 pub pattern: Option<SeriesPattern>,
98 pub visible: bool,
99 pub points: Vec<ChartDatum<T>>,
100}
101
102impl<T> std::fmt::Debug for ChartSeries<T>
103where
104 T: std::fmt::Debug,
105{
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.debug_struct("ChartSeries")
108 .field("name", &self.name)
109 .field("pattern", &self.pattern)
110 .field("visible", &self.visible)
111 .field("len", &self.points.len())
112 .finish()
113 }
114}
115
116impl<T> Clone for ChartSeries<T>
117where
118 T: Clone,
119{
120 fn clone(&self) -> Self {
121 Self {
122 name: self.name.clone(),
123 color: self.color.clone(),
124 pattern: self.pattern,
125 visible: self.visible,
126 points: self.points.clone(),
127 }
128 }
129}
130
131impl<T> ChartSeries<T> {
132 pub fn new(name: impl Into<String>) -> Self {
133 Self {
134 name: name.into(),
135 color: None,
136 pattern: None,
137 visible: true,
138 points: Vec::new(),
139 }
140 }
141
142 pub fn color(mut self, color: impl Into<ColorProp>) -> Self {
143 self.color = Some(color.into());
144 self
145 }
146
147 pub fn pattern(mut self, pattern: SeriesPattern) -> Self {
150 self.pattern = Some(pattern);
151 self
152 }
153
154 pub fn visibility(mut self, visible: bool) -> Self {
155 self.visible = visible;
156 self
157 }
158
159 pub fn push(&mut self, category: T, value: f32) {
160 self.points.push(ChartDatum::new(category, value));
161 }
162
163 pub fn data(mut self, points: Vec<ChartDatum<T>>) -> Self {
164 self.points = points;
165 self
166 }
167}
168
169pub struct SeriesView<'a, T> {
172 pub id: SeriesId,
173 pub name: &'a str,
174 pub color: Option<&'a ColorProp>,
175 pub pattern: Option<SeriesPattern>,
178 pub visible: bool,
179 pub points: &'a [ChartDatum<T>],
180}
181
182struct SeriesEntry<T> {
183 name: String,
184 color: Option<ColorProp>,
185 pattern: Option<SeriesPattern>,
186 visible: bool,
187 points: Vec<ChartDatum<T>>,
188}
189
190struct ObserverEntry {
191 id: u64,
192 callback: Rc<dyn Fn(&ChartChange)>,
193}
194
195fn color_prop_eq(a: &ColorProp, b: &ColorProp) -> bool {
203 match (a, b) {
204 (ColorProp::Static(x), ColorProp::Static(y)) => x == y,
205 (ColorProp::Bound(x), ColorProp::Bound(y)) => Signal::same(x, y),
206 (ColorProp::TextRole(x), ColorProp::TextRole(y)) => x == y,
207 (ColorProp::SurfaceRole(x), ColorProp::SurfaceRole(y)) => x == y,
208 (ColorProp::BorderRole(x), ColorProp::BorderRole(y)) => x == y,
209 (ColorProp::DynamicTextRole(x), ColorProp::DynamicTextRole(y)) => Signal::same(x, y),
210 (ColorProp::DynamicSurfaceRole(x), ColorProp::DynamicSurfaceRole(y)) => Signal::same(x, y),
211 (ColorProp::DynamicBorderRole(x), ColorProp::DynamicBorderRole(y)) => Signal::same(x, y),
212 _ => false,
213 }
214}
215
216struct ChartModelInner<T> {
217 arena: SlotMap<slotmap::DefaultKey, SeriesEntry<T>>,
218 order: Vec<SeriesId>,
219 observers: Vec<ObserverEntry>,
220 next_observer_id: u64,
221 structure_version: Signal<u64>,
224 style_version: Signal<u64>,
227 #[cfg(debug_assertions)]
233 debug_adapter: Option<Rc<dyn crate::debug_registry::ModelDebug>>,
234}
235
236pub struct ChartModel<T: 'static> {
242 inner: Rc<RefCell<ChartModelInner<T>>>,
243}
244
245impl<T: 'static> ChartModel<T> {
246 pub fn new() -> Self {
248 Self {
249 inner: Rc::new(RefCell::new(ChartModelInner {
250 arena: SlotMap::new(),
251 order: Vec::new(),
252 observers: Vec::new(),
253 next_observer_id: 1,
254 structure_version: Signal::new(0),
255 style_version: Signal::new(0),
256 #[cfg(debug_assertions)]
257 debug_adapter: None,
258 })),
259 }
260 }
261
262 pub fn from_series_vec(series: Vec<ChartSeries<T>>) -> Self {
266 let model = Self::new();
267 {
268 let mut guard = model.inner.borrow_mut();
269 for s in series {
270 let key = guard.arena.insert(SeriesEntry {
271 name: s.name,
272 color: s.color,
273 pattern: s.pattern,
274 visible: s.visible,
275 points: s.points,
276 });
277 let id = SeriesId::from_key(key);
278 guard.order.push(id);
279 }
280 }
281 model
282 }
283
284 pub fn from_points(points: Vec<ChartDatum<T>>) -> Self {
288 Self::from_series_vec(vec![ChartSeries::new(String::new()).data(points)])
289 }
290
291 pub fn only_series(&self) -> Option<SeriesId> {
293 let guard = self.inner.borrow();
294 if guard.order.len() == 1 {
295 Some(guard.order[0])
296 } else {
297 None
298 }
299 }
300
301 pub fn add_series(&self, name: impl Into<String>) -> SeriesId {
305 let (id, index) = {
306 let mut guard = self.inner.borrow_mut();
307 let key = guard.arena.insert(SeriesEntry {
308 name: name.into(),
309 color: None,
310 pattern: None,
311 visible: true,
312 points: Vec::new(),
313 });
314 let id = SeriesId::from_key(key);
315 let index = guard.order.len();
316 guard.order.push(id);
317 (id, index)
318 };
319 self.notify(ChartChange::SeriesInserted { index, series: id });
320 self.bump_structure();
321 id
322 }
323
324 pub fn insert_series(&self, index: usize, name: impl Into<String>) -> SeriesId {
329 let id = {
330 let mut guard = self.inner.borrow_mut();
331 let key = guard.arena.insert(SeriesEntry {
332 name: name.into(),
333 color: None,
334 pattern: None,
335 visible: true,
336 points: Vec::new(),
337 });
338 let id = SeriesId::from_key(key);
339 guard.order.insert(index, id);
340 id
341 };
342 self.notify(ChartChange::SeriesInserted { index, series: id });
343 self.bump_structure();
344 id
345 }
346
347 pub fn remove_series(&self, series: SeriesId) {
352 {
353 let mut guard = self.inner.borrow_mut();
354 guard.arena.remove(series.key()).expect("unknown SeriesId");
355 guard.order.retain(|&id| id != series);
356 }
357 self.notify(ChartChange::SeriesRemoved { series });
358 self.bump_structure();
359 }
360
361 pub fn rename_series(&self, series: SeriesId, name: impl Into<String>) {
367 let name = name.into();
368 let changed = {
369 let mut guard = self.inner.borrow_mut();
370 let entry = &mut guard.arena[series.key()];
371 if entry.name == name {
372 false
373 } else {
374 entry.name = name;
375 true
376 }
377 };
378 if !changed {
379 return;
380 }
381 self.notify(ChartChange::SeriesRenamed { series });
382 self.bump_structure();
383 }
384
385 pub fn set_series_color(&self, series: SeriesId, color: impl Into<ColorProp>) {
393 let color = color.into();
394 let changed = {
395 let mut guard = self.inner.borrow_mut();
396 let entry = &mut guard.arena[series.key()];
397 if entry
398 .color
399 .as_ref()
400 .is_some_and(|c| color_prop_eq(c, &color))
401 {
402 false
403 } else {
404 entry.color = Some(color);
405 true
406 }
407 };
408 if !changed {
409 return;
410 }
411 self.notify(ChartChange::SeriesColorChanged { series });
412 self.bump_style();
413 }
414
415 pub fn clear_series_color(&self, series: SeriesId) {
422 let changed = {
423 let mut guard = self.inner.borrow_mut();
424 let entry = &mut guard.arena[series.key()];
425 if entry.color.is_none() {
426 false
427 } else {
428 entry.color = None;
429 true
430 }
431 };
432 if !changed {
433 return;
434 }
435 self.notify(ChartChange::SeriesColorChanged { series });
436 self.bump_style();
437 }
438
439 pub fn set_series_pattern(&self, series: SeriesId, pattern: SeriesPattern) {
446 let changed = {
447 let mut guard = self.inner.borrow_mut();
448 let entry = &mut guard.arena[series.key()];
449 if entry.pattern == Some(pattern) {
450 false
451 } else {
452 entry.pattern = Some(pattern);
453 true
454 }
455 };
456 if !changed {
457 return;
458 }
459 self.notify(ChartChange::SeriesPatternChanged { series });
460 self.bump_style();
461 }
462
463 pub fn clear_series_pattern(&self, series: SeriesId) {
469 let changed = {
470 let mut guard = self.inner.borrow_mut();
471 let entry = &mut guard.arena[series.key()];
472 if entry.pattern.is_none() {
473 false
474 } else {
475 entry.pattern = None;
476 true
477 }
478 };
479 if !changed {
480 return;
481 }
482 self.notify(ChartChange::SeriesPatternChanged { series });
483 self.bump_style();
484 }
485
486 pub fn set_series_visible(&self, series: SeriesId, visible: bool) {
492 let changed = {
493 let mut guard = self.inner.borrow_mut();
494 let entry = &mut guard.arena[series.key()];
495 if entry.visible == visible {
496 false
497 } else {
498 entry.visible = visible;
499 true
500 }
501 };
502 if !changed {
503 return;
504 }
505 self.notify(ChartChange::SeriesVisibilityChanged { series });
506 self.bump_structure();
507 }
508
509 pub fn move_series(&self, series: SeriesId, to: usize) {
515 let from = {
516 let guard = self.inner.borrow();
517 guard
518 .order
519 .iter()
520 .position(|&id| id == series)
521 .expect("unknown SeriesId")
522 };
523 if from == to {
524 return;
525 }
526 {
527 let mut guard = self.inner.borrow_mut();
528 let id = guard.order.remove(from);
529 guard.order.insert(to, id);
530 }
531 self.notify(ChartChange::SeriesMoved { series, from, to });
532 self.bump_structure();
533 }
534
535 pub fn clear(&self) {
537 {
538 let mut guard = self.inner.borrow_mut();
539 guard.arena.clear();
540 guard.order.clear();
541 }
542 self.notify(ChartChange::Reset);
543 self.bump_structure();
544 }
545
546 pub fn push_point(&self, series: SeriesId, category: T, value: f32) {
553 let index = {
554 let mut guard = self.inner.borrow_mut();
555 let entry = &mut guard.arena[series.key()];
556 let index = entry.points.len();
557 entry.points.push(ChartDatum::new(category, value));
558 index
559 };
560 self.notify(ChartChange::PointsInserted {
561 series,
562 range: index..index + 1,
563 });
564 self.bump_structure();
565 }
566
567 pub fn insert_point(&self, series: SeriesId, index: usize, category: T, value: f32) {
572 {
573 let mut guard = self.inner.borrow_mut();
574 guard.arena[series.key()]
575 .points
576 .insert(index, ChartDatum::new(category, value));
577 }
578 self.notify(ChartChange::PointsInserted {
579 series,
580 range: index..index + 1,
581 });
582 self.bump_structure();
583 }
584
585 pub fn remove_point(&self, series: SeriesId, index: usize) -> ChartDatum<T> {
590 let datum = {
591 let mut guard = self.inner.borrow_mut();
592 guard.arena[series.key()].points.remove(index)
593 };
594 self.notify(ChartChange::PointsRemoved {
595 series,
596 range: index..index + 1,
597 });
598 self.bump_structure();
599 datum
600 }
601
602 pub fn update_point(&self, series: SeriesId, index: usize, category: T, value: f32) {
607 {
608 let mut guard = self.inner.borrow_mut();
609 guard.arena[series.key()].points[index] = ChartDatum::new(category, value);
610 }
611 self.notify(ChartChange::PointUpdated { series, index });
612 self.bump_structure();
613 }
614
615 pub fn replace_series_data(&self, series: SeriesId, points: Vec<ChartDatum<T>>) {
620 {
621 let mut guard = self.inner.borrow_mut();
622 guard.arena[series.key()].points = points;
623 }
624 self.notify(ChartChange::SeriesDataReplaced { series });
625 self.bump_structure();
626 }
627
628 pub fn series_count(&self) -> usize {
632 self.inner.borrow().order.len()
633 }
634
635 pub fn series_ids(&self) -> Vec<SeriesId> {
637 self.inner.borrow().order.clone()
638 }
639
640 pub fn series_id_at(&self, index: usize) -> Option<SeriesId> {
642 self.inner.borrow().order.get(index).copied()
643 }
644
645 pub fn series_index_of(&self, series: SeriesId) -> Option<usize> {
647 self.inner
648 .borrow()
649 .order
650 .iter()
651 .position(|&id| id == series)
652 }
653
654 pub fn point_count(&self, series: SeriesId) -> usize {
656 self.inner
657 .borrow()
658 .arena
659 .get(series.key())
660 .map(|e| e.points.len())
661 .unwrap_or(0)
662 }
663
664 pub fn with_series<R>(
667 &self,
668 series: SeriesId,
669 f: impl FnOnce(&str, Option<&ColorProp>, bool) -> R,
670 ) -> Option<R> {
671 let guard = self.inner.borrow();
672 guard
673 .arena
674 .get(series.key())
675 .map(|e| f(&e.name, e.color.as_ref(), e.visible))
676 }
677
678 pub fn with_point<R>(
681 &self,
682 series: SeriesId,
683 index: usize,
684 f: impl FnOnce(&ChartDatum<T>) -> R,
685 ) -> Option<R> {
686 let guard = self.inner.borrow();
687 guard
688 .arena
689 .get(series.key())
690 .and_then(|e| e.points.get(index))
691 .map(f)
692 }
693
694 pub fn with_series_view<R>(
697 &self,
698 series: SeriesId,
699 f: impl FnOnce(SeriesView<'_, T>) -> R,
700 ) -> Option<R> {
701 let guard = self.inner.borrow();
702 guard.arena.get(series.key()).map(|e| {
703 f(SeriesView {
704 id: series,
705 name: &e.name,
706 color: e.color.as_ref(),
707 pattern: e.pattern,
708 visible: e.visible,
709 points: &e.points,
710 })
711 })
712 }
713
714 pub fn with_all_series<R>(&self, f: impl FnOnce(&[SeriesView<'_, T>]) -> R) -> R {
716 let guard = self.inner.borrow();
717 let views: Vec<SeriesView<'_, T>> = guard
718 .order
719 .iter()
720 .filter_map(|&id| {
721 guard.arena.get(id.key()).map(|e| SeriesView {
722 id,
723 name: &e.name,
724 color: e.color.as_ref(),
725 pattern: e.pattern,
726 visible: e.visible,
727 points: &e.points,
728 })
729 })
730 .collect();
731 f(&views)
732 }
733
734 pub fn structure_version(&self) -> Signal<u64> {
745 self.inner.borrow().structure_version.clone()
746 }
747
748 pub fn style_version(&self) -> Signal<u64> {
753 self.inner.borrow().style_version.clone()
754 }
755
756 pub fn observe_changes(&self, f: impl Fn(&ChartChange) + 'static) -> ObserverHandle {
776 let mut guard = self.inner.borrow_mut();
777 let id = guard.next_observer_id;
778 guard.next_observer_id += 1;
779 guard.observers.push(ObserverEntry {
780 id,
781 callback: Rc::new(f),
782 });
783 let inner = self.inner.clone();
784 ObserverHandle::new(
785 self.inner.clone(),
786 id,
787 Rc::new(move |observer_id| {
788 let removed = {
791 let mut guard = inner.borrow_mut();
792 let index = guard.observers.iter().position(|e| e.id == observer_id);
793 index.map(|i| guard.observers.remove(i))
794 };
795 drop(removed);
796 }),
797 )
798 }
799
800 fn notify(&self, change: ChartChange) {
801 let callbacks: Vec<Rc<dyn Fn(&ChartChange)>> = self
802 .inner
803 .borrow()
804 .observers
805 .iter()
806 .map(|e| e.callback.clone())
807 .collect();
808 for cb in &callbacks {
809 cb(&change);
810 }
811 }
812
813 fn bump_structure(&self) {
818 let sig = self.inner.borrow().structure_version.clone();
819 sig.set(sig.get().wrapping_add(1));
820 }
821
822 fn bump_style(&self) {
825 let sig = self.inner.borrow().style_version.clone();
826 sig.set(sig.get().wrapping_add(1));
827 }
828}
829
830impl<T: std::fmt::Debug + 'static> ChartModel<T> {
831 pub fn debug_named(self, _name: impl Into<String>) -> Self {
839 #[cfg(debug_assertions)]
840 {
841 let weak = Rc::downgrade(&self.inner);
842 let adapter: Rc<dyn crate::debug_registry::ModelDebug> =
843 Rc::new(ChartModelDebug::<T> { weak });
844 let name = _name.into();
845 crate::debug_registry::register(name, Rc::downgrade(&adapter));
846 self.inner.borrow_mut().debug_adapter = Some(adapter);
847 }
848 self
849 }
850}
851
852#[cfg(debug_assertions)]
853struct ChartModelDebug<T> {
854 weak: std::rc::Weak<RefCell<ChartModelInner<T>>>,
855}
856
857#[cfg(debug_assertions)]
858impl<T: std::fmt::Debug + 'static> crate::debug_registry::ModelDebug for ChartModelDebug<T> {
859 fn kind(&self) -> &'static str {
860 "ChartModel"
861 }
862 fn len(&self) -> usize {
863 self.weak
864 .upgrade()
865 .map(|inner| inner.borrow().arena.values().map(|e| e.points.len()).sum())
866 .unwrap_or(0)
867 }
868 fn debug_dump(&self, out: &mut dyn std::fmt::Write) {
869 let Some(inner) = self.weak.upgrade() else {
870 return;
871 };
872 let guard = inner.borrow();
873 for (i, &id) in guard.order.iter().enumerate() {
874 if let Some(e) = guard.arena.get(id.key()) {
875 let _ = writeln!(
876 out,
877 "[{}] {:?} ({} pts, visible={})",
878 i,
879 e.name,
880 e.points.len(),
881 e.visible
882 );
883 }
884 }
885 }
886}
887
888impl<T: 'static> Default for ChartModel<T> {
889 fn default() -> Self {
890 Self::new()
891 }
892}
893
894impl<T: 'static> Clone for ChartModel<T> {
895 fn clone(&self) -> Self {
896 Self {
897 inner: self.inner.clone(),
898 }
899 }
900}
901
902impl<T: std::fmt::Debug + 'static> std::fmt::Debug for ChartModel<T> {
903 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
904 let guard = self.inner.borrow();
905 f.debug_struct("ChartModel")
906 .field("series_count", &guard.order.len())
907 .finish()
908 }
909}
910
911#[cfg(test)]
912impl<T: 'static> ChartModel<T> {
913 pub(crate) fn observer_count(&self) -> usize {
916 self.inner.borrow().observers.len()
917 }
918}
919
920#[cfg(test)]
921mod tests {
922 use std::cell::Cell;
923
924 use super::*;
925
926 #[test]
927 fn datum_with_color_sets_a_per_point_override() {
928 use teksilo_core::color_prop::ColorProp;
929 use teksilo_tokens::SurfaceRole;
930 let plain = ChartDatum::new("Q1".to_string(), 5.0);
931 assert!(plain.color.is_none(), "a plain datum has no color override");
932 let colored = ChartDatum::new("Q1".to_string(), 5.0).with_color(SurfaceRole::StatusError);
933 assert!(matches!(
934 colored.color,
935 Some(ColorProp::SurfaceRole(SurfaceRole::StatusError))
936 ));
937 let _ = ChartDatum::new("Q2".to_string(), 1.0);
939 }
940
941 fn sample() -> (ChartModel<String>, SeriesId, SeriesId) {
942 let model = ChartModel::from_series_vec(vec![
943 ChartSeries::new("Revenue").data(vec![
944 ChartDatum::new("Q1".to_string(), 10.0),
945 ChartDatum::new("Q2".to_string(), 20.0),
946 ]),
947 ChartSeries::new("Costs").data(vec![ChartDatum::new("Q1".to_string(), 5.0)]),
948 ]);
949 let a = model.series_id_at(0).unwrap();
950 let b = model.series_id_at(1).unwrap();
951 (model, a, b)
952 }
953
954 #[test]
955 fn from_series_vec_builds_correctly() {
956 let (model, a, b) = sample();
957 assert_eq!(model.series_count(), 2);
958 assert_eq!(model.point_count(a), 2);
959 assert_eq!(model.point_count(b), 1);
960 assert_eq!(
961 model.with_series(a, |name, _, visible| (name.to_string(), visible)),
962 Some(("Revenue".to_string(), true))
963 );
964 }
965
966 #[test]
967 fn new_is_empty() {
968 let model: ChartModel<String> = ChartModel::new();
969 assert_eq!(model.series_count(), 0);
970 assert_eq!(model.only_series(), None);
971 }
972
973 #[test]
974 fn only_series_some_iff_exactly_one() {
975 let model: ChartModel<String> = ChartModel::new();
976 assert_eq!(model.only_series(), None);
977 let a = model.add_series("A");
978 assert_eq!(model.only_series(), Some(a));
979 model.add_series("B");
980 assert_eq!(model.only_series(), None);
981 }
982
983 #[test]
984 fn from_points_builds_single_anonymous_series() {
985 let model = ChartModel::from_points(vec![
986 ChartDatum::new("a".to_string(), 1.0),
987 ChartDatum::new("b".to_string(), 2.0),
988 ]);
989 assert_eq!(model.series_count(), 1);
990 let s = model.only_series().unwrap();
991 assert_eq!(model.point_count(s), 2);
992 assert_eq!(model.with_series(s, |_, _, visible| visible), Some(true));
993 }
994
995 fn track_changes(
996 model: &ChartModel<String>,
997 ) -> (Rc<RefCell<Vec<ChartChange>>>, ObserverHandle) {
998 let log: Rc<RefCell<Vec<ChartChange>>> = Rc::new(RefCell::new(Vec::new()));
999 let l = log.clone();
1000 let handle = model.observe_changes(move |c| l.borrow_mut().push(c.clone()));
1001 (log, handle)
1002 }
1003
1004 #[test]
1005 fn add_series_emits_inserted_and_bumps_structure() {
1006 let model: ChartModel<String> = ChartModel::new();
1007 let structure = model.structure_version();
1008 let style = model.style_version();
1009 let (log, _handle) = track_changes(&model);
1010
1011 let s = model.add_series("A");
1012 assert_eq!(log.borrow().len(), 1);
1013 assert_eq!(
1014 log.borrow()[0],
1015 ChartChange::SeriesInserted {
1016 index: 0,
1017 series: s
1018 }
1019 );
1020 assert_eq!(structure.get(), 1);
1021 assert_eq!(style.get(), 0);
1022 }
1023
1024 #[test]
1025 fn observer_sees_pre_bump_structure_version_during_notify() {
1026 let model: ChartModel<String> = ChartModel::new();
1027 let structure = model.structure_version();
1028 let seen_during_callback: Rc<Cell<Option<u64>>> = Rc::new(Cell::new(None));
1029 let seen = seen_during_callback.clone();
1030 let sig = structure.clone();
1031 let _handle = model.observe_changes(move |_| seen.set(Some(sig.get())));
1032
1033 let before = structure.get();
1034 model.add_series("A");
1035 let after = structure.get();
1036
1037 assert_eq!(after, before + 1, "the mutation did bump the signal");
1038 assert_eq!(
1039 seen_during_callback.get(),
1040 Some(before),
1041 "notify runs before the version bump, so a ChartChange observer \
1042 reading structure_version() synchronously sees the pre-bump value"
1043 );
1044 }
1045
1046 #[test]
1047 fn observer_sees_pre_bump_style_version_during_notify() {
1048 let (model, a, _b) = sample();
1049 let style = model.style_version();
1050 let seen_during_callback: Rc<Cell<Option<u64>>> = Rc::new(Cell::new(None));
1051 let seen = seen_during_callback.clone();
1052 let sig = style.clone();
1053 let _handle = model.observe_changes(move |_| seen.set(Some(sig.get())));
1054
1055 let before = style.get();
1056 model.set_series_color(a, test_color());
1057 let after = style.get();
1058
1059 assert_eq!(after, before + 1);
1060 assert_eq!(seen_during_callback.get(), Some(before));
1061 }
1062
1063 #[test]
1064 fn insert_series_at_index() {
1065 let (model, a, b) = sample();
1066 let c = model.insert_series(1, "Middle");
1067 assert_eq!(model.series_ids(), vec![a, c, b]);
1068 }
1069
1070 #[test]
1071 fn remove_series_emits_removed_and_bumps_structure() {
1072 let (model, a, _b) = sample();
1073 let structure_before = model.structure_version().get();
1074 let (log, _handle) = track_changes(&model);
1075
1076 model.remove_series(a);
1077 assert_eq!(log.borrow().len(), 1);
1078 assert_eq!(log.borrow()[0], ChartChange::SeriesRemoved { series: a });
1079 assert_eq!(model.series_count(), 1);
1080 assert!(model.structure_version().get() > structure_before);
1081 }
1082
1083 #[test]
1084 fn rename_series_emits_renamed_and_bumps_structure() {
1085 let (model, a, _b) = sample();
1086 let style_before = model.style_version().get();
1087 let (log, _handle) = track_changes(&model);
1088
1089 model.rename_series(a, "New Name");
1090 assert_eq!(log.borrow().len(), 1);
1091 assert_eq!(log.borrow()[0], ChartChange::SeriesRenamed { series: a });
1092 assert_eq!(
1093 model.with_series(a, |name, _, _| name.to_string()),
1094 Some("New Name".to_string())
1095 );
1096 assert_eq!(
1097 model.style_version().get(),
1098 style_before,
1099 "renaming is not a style change"
1100 );
1101 }
1102
1103 #[test]
1104 fn rename_series_noop_does_not_notify() {
1105 let (model, a, _b) = sample();
1106 let structure_before = model.structure_version().get();
1107 let (log, _handle) = track_changes(&model);
1108
1109 model.rename_series(a, "Revenue"); assert_eq!(log.borrow().len(), 0);
1111 assert_eq!(model.structure_version().get(), structure_before);
1112 }
1113
1114 #[test]
1115 fn set_series_color_bumps_style_not_structure() {
1116 let (model, a, _b) = sample();
1117 let structure_before = model.structure_version().get();
1118 let style_before = model.style_version().get();
1119 let (log, _handle) = track_changes(&model);
1120
1121 model.set_series_color(a, test_color());
1122 assert_eq!(log.borrow().len(), 1);
1123 assert_eq!(
1124 log.borrow()[0],
1125 ChartChange::SeriesColorChanged { series: a }
1126 );
1127 assert_eq!(
1128 model.structure_version().get(),
1129 structure_before,
1130 "color change must not bump structure_version"
1131 );
1132 assert!(model.style_version().get() > style_before);
1133 assert!(model.with_series(a, |_, color, _| color.is_some()).unwrap());
1134 }
1135
1136 #[test]
1137 fn set_series_color_noop_does_not_notify() {
1138 let (model, a, _b) = sample();
1139 model.set_series_color(a, test_color());
1140 let structure_before = model.structure_version().get();
1141 let style_before = model.style_version().get();
1142 let (log, _handle) = track_changes(&model);
1143
1144 model.set_series_color(a, test_color()); assert_eq!(log.borrow().len(), 0);
1146 assert_eq!(model.structure_version().get(), structure_before);
1147 assert_eq!(model.style_version().get(), style_before);
1148 }
1149
1150 #[test]
1151 fn clear_series_color_bumps_style_and_clears() {
1152 let (model, a, _b) = sample();
1153 model.set_series_color(a, test_color());
1154 let style_before = model.style_version().get();
1155 let (log, _handle) = track_changes(&model);
1156
1157 model.clear_series_color(a);
1158 assert_eq!(log.borrow().len(), 1);
1159 assert_eq!(
1160 log.borrow()[0],
1161 ChartChange::SeriesColorChanged { series: a }
1162 );
1163 assert!(model.style_version().get() > style_before);
1164 assert!(!model.with_series(a, |_, color, _| color.is_some()).unwrap());
1165 }
1166
1167 #[test]
1168 fn clear_series_color_noop_does_not_notify_when_already_none() {
1169 let (model, a, _b) = sample();
1170 let structure_before = model.structure_version().get();
1172 let style_before = model.style_version().get();
1173 let (log, _handle) = track_changes(&model);
1174
1175 model.clear_series_color(a);
1176 assert_eq!(log.borrow().len(), 0);
1177 assert_eq!(model.structure_version().get(), structure_before);
1178 assert_eq!(model.style_version().get(), style_before);
1179 }
1180
1181 #[test]
1182 fn set_series_visible_bumps_structure() {
1183 let (model, a, _b) = sample();
1184 let structure_before = model.structure_version().get();
1185 let (log, _handle) = track_changes(&model);
1186
1187 model.set_series_visible(a, false);
1188 assert_eq!(log.borrow().len(), 1);
1189 assert_eq!(
1190 log.borrow()[0],
1191 ChartChange::SeriesVisibilityChanged { series: a }
1192 );
1193 assert!(model.structure_version().get() > structure_before);
1194 assert_eq!(model.with_series(a, |_, _, visible| visible), Some(false));
1195 }
1196
1197 #[test]
1198 fn set_series_visible_noop_does_not_notify() {
1199 let (model, a, _b) = sample();
1200 let structure_before = model.structure_version().get();
1201 let (log, _handle) = track_changes(&model);
1202
1203 model.set_series_visible(a, true); assert_eq!(log.borrow().len(), 0);
1205 assert_eq!(model.structure_version().get(), structure_before);
1206 }
1207
1208 #[test]
1209 fn move_series_emits_moved_and_bumps_structure() {
1210 let (model, a, b) = sample();
1211 let structure_before = model.structure_version().get();
1212 let (log, _handle) = track_changes(&model);
1213
1214 model.move_series(a, 1);
1215 assert_eq!(model.series_ids(), vec![b, a]);
1216 assert_eq!(log.borrow().len(), 1);
1217 assert_eq!(
1218 log.borrow()[0],
1219 ChartChange::SeriesMoved {
1220 series: a,
1221 from: 0,
1222 to: 1
1223 }
1224 );
1225 assert!(model.structure_version().get() > structure_before);
1226 }
1227
1228 #[test]
1229 fn move_series_noop_does_not_notify() {
1230 let (model, a, _b) = sample();
1231 let structure_before = model.structure_version().get();
1232 let (log, _handle) = track_changes(&model);
1233
1234 model.move_series(a, 0); assert_eq!(log.borrow().len(), 0);
1236 assert_eq!(model.structure_version().get(), structure_before);
1237 }
1238
1239 #[test]
1240 fn push_point_emits_inserted_and_bumps_structure() {
1241 let (model, a, _b) = sample();
1242 let structure_before = model.structure_version().get();
1243 let (log, _handle) = track_changes(&model);
1244
1245 model.push_point(a, "Q3".to_string(), 30.0);
1246 assert_eq!(model.point_count(a), 3);
1247 assert_eq!(log.borrow().len(), 1);
1248 assert_eq!(
1249 log.borrow()[0],
1250 ChartChange::PointsInserted {
1251 series: a,
1252 range: 2..3
1253 }
1254 );
1255 assert!(model.structure_version().get() > structure_before);
1256 }
1257
1258 #[test]
1259 fn insert_point_at_index() {
1260 let (model, a, _b) = sample();
1261 model.insert_point(a, 1, "Q1.5".to_string(), 15.0);
1262 assert_eq!(model.point_count(a), 3);
1263 assert_eq!(
1264 model.with_point(a, 1, |d| d.category.clone()),
1265 Some("Q1.5".to_string())
1266 );
1267 }
1268
1269 #[test]
1270 fn remove_point_emits_removed_and_returns_datum() {
1271 let (model, a, _b) = sample();
1272 let (log, _handle) = track_changes(&model);
1273
1274 let removed = model.remove_point(a, 0);
1275 assert_eq!(removed.category, "Q1");
1276 assert_eq!(model.point_count(a), 1);
1277 assert_eq!(log.borrow().len(), 1);
1278 assert_eq!(
1279 log.borrow()[0],
1280 ChartChange::PointsRemoved {
1281 series: a,
1282 range: 0..1
1283 }
1284 );
1285 }
1286
1287 #[test]
1288 fn update_point_bumps_structure_not_style() {
1289 let (model, a, _b) = sample();
1290 let structure_before = model.structure_version().get();
1291 let style_before = model.style_version().get();
1292 let (log, _handle) = track_changes(&model);
1293
1294 model.update_point(a, 0, "Q1-revised".to_string(), 99.0);
1295 assert_eq!(log.borrow().len(), 1);
1296 assert_eq!(
1297 log.borrow()[0],
1298 ChartChange::PointUpdated {
1299 series: a,
1300 index: 0
1301 }
1302 );
1303 assert!(model.structure_version().get() > structure_before);
1304 assert_eq!(model.style_version().get(), style_before);
1305 assert_eq!(model.with_point(a, 0, |d| d.value), Some(99.0));
1306 }
1307
1308 #[test]
1309 fn replace_series_data_emits_replaced() {
1310 let (model, a, _b) = sample();
1311 let (log, _handle) = track_changes(&model);
1312
1313 model.replace_series_data(a, vec![ChartDatum::new("X".to_string(), 1.0)]);
1314 assert_eq!(model.point_count(a), 1);
1315 assert_eq!(log.borrow().len(), 1);
1316 assert_eq!(
1317 log.borrow()[0],
1318 ChartChange::SeriesDataReplaced { series: a }
1319 );
1320 }
1321
1322 #[test]
1323 fn clear_emits_reset() {
1324 let (model, _a, _b) = sample();
1325 let (log, _handle) = track_changes(&model);
1326
1327 model.clear();
1328 assert_eq!(model.series_count(), 0);
1329 assert_eq!(log.borrow().len(), 1);
1330 assert_eq!(log.borrow()[0], ChartChange::Reset);
1331 }
1332
1333 #[test]
1334 fn observer_removed_on_handle_drop() {
1335 let model: ChartModel<String> = ChartModel::new();
1336 let count = Rc::new(Cell::new(0));
1337 let c = count.clone();
1338 let handle = model.observe_changes(move |_| c.set(c.get() + 1));
1339
1340 model.add_series("A");
1341 assert_eq!(count.get(), 1);
1342
1343 drop(handle);
1344 model.add_series("B");
1345 assert_eq!(count.get(), 1);
1346 }
1347
1348 #[test]
1349 fn multiple_observers() {
1350 let model: ChartModel<String> = ChartModel::new();
1351 let count = Rc::new(Cell::new(0));
1352 let c1 = count.clone();
1353 let c2 = count.clone();
1354 let _h1 = model.observe_changes(move |_| c1.set(c1.get() + 1));
1355 let _h2 = model.observe_changes(move |_| c2.set(c2.get() + 1));
1356
1357 model.add_series("A");
1358 assert_eq!(count.get(), 2);
1359 }
1360
1361 #[test]
1362 fn clone_shares_data_and_observers() {
1363 let (model, _a, _b) = sample();
1364 let clone = model.clone();
1365 let count = Rc::new(Cell::new(0));
1366 let c = count.clone();
1367 let _handle = model.observe_changes(move |_| c.set(c.get() + 1));
1368
1369 clone.add_series("New");
1370 assert_eq!(model.series_count(), 3);
1371 assert_eq!(count.get(), 1);
1372 }
1373
1374 #[test]
1375 fn with_all_series_returns_views_in_order() {
1376 let (model, a, b) = sample();
1377 let ids: Vec<SeriesId> =
1378 model.with_all_series(|views| views.iter().map(|v| v.id).collect());
1379 assert_eq!(ids, vec![a, b]);
1380 let names: Vec<String> =
1381 model.with_all_series(|views| views.iter().map(|v| v.name.to_string()).collect());
1382 assert_eq!(names, vec!["Revenue".to_string(), "Costs".to_string()]);
1383 }
1384
1385 #[test]
1386 fn with_point_out_of_bounds_returns_none() {
1387 let (model, a, _b) = sample();
1388 assert_eq!(model.with_point(a, 99, |d| d.value), None);
1389 }
1390
1391 fn stale_id(model: &ChartModel<String>) -> SeriesId {
1398 let ghost = model.add_series("Ghost");
1399 model.remove_series(ghost);
1400 ghost
1401 }
1402
1403 #[test]
1404 fn with_series_unknown_id_returns_none() {
1405 let (model, _a, _b) = sample();
1406 let ghost = stale_id(&model);
1407 assert_eq!(model.with_series(ghost, |_, _, _| ()), None);
1408 assert_eq!(model.with_point(ghost, 0, |d| d.value), None);
1409 }
1410
1411 #[test]
1412 #[should_panic(expected = "unknown SeriesId")]
1413 fn remove_series_unknown_id_panics() {
1414 let (model, _a, _b) = sample();
1415 let ghost = stale_id(&model);
1416 model.remove_series(ghost);
1417 }
1418
1419 #[test]
1420 #[should_panic]
1421 fn rename_series_unknown_id_panics() {
1422 let (model, _a, _b) = sample();
1423 let ghost = stale_id(&model);
1424 model.rename_series(ghost, "X");
1425 }
1426
1427 #[test]
1428 #[should_panic]
1429 fn push_point_unknown_series_panics() {
1430 let (model, _a, _b) = sample();
1431 let ghost = stale_id(&model);
1432 model.push_point(ghost, "X".to_string(), 1.0);
1433 }
1434
1435 #[test]
1436 #[should_panic(expected = "unknown SeriesId")]
1437 fn move_series_unknown_id_panics() {
1438 let (model, _a, _b) = sample();
1439 let ghost = stale_id(&model);
1440 model.move_series(ghost, 0);
1441 }
1442
1443 fn test_color() -> teksilo_tokens::Color {
1447 teksilo_tokens::Color::from_hex("#FF0000")
1448 }
1449}