rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Chart widget.
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::style::{MotionSlot, PropertyDriver};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// The chart styles [`ChartWidget`] can switch between at runtime.
///
/// # Scope, and why this is not the same enum as the other `ChartType`s
///
/// This is the **control layer**'s set: one widget that can render any of these
/// styles, so a `match` over it stays exhaustive in this widget. Two same-named
/// enums exist elsewhere and are deliberately kept separate (principle #49):
///
/// * [`crate::widget::display_widgets::mini_chart::ChartType`] — `MiniChart`'s
///   two styles (`Line`, `Bar`), since a mini chart has no pie or scatter form;
/// * `crate::widget::chart_widgets::types::ChartType` — the drawing engine's
///   set, which adds `Area`.
///
/// # Why these variants are one control rather than six (rule #80)
///
/// Every variant below reads the same `series: Vec<Vec<f64>>` plus the same
/// `labels`, and every one shares the same interaction (`hovered_index`,
/// `data_point_clicked`, `data_point_hovered`). Only the drawing geometry differs.
/// Six controls would repeat the axes, the labels, the hover hit-test and the
/// signal plumbing six times — which is the duplication rule #80 exists to
/// prevent.
///
/// The multi-value variants (`Candlestick`, `BoxPlot`) read their extra numbers
/// from consecutive entries of one series rather than from a second axis. That is
/// what `set_series` makes explicit: the grouping is a documented contract of the
/// variant, not an accident of how the vector happened to be filled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ChartType {
    /// Vertical bars, one per data point; the default.
    #[default]
    Bar,
    /// Polyline connecting the data points in order.
    Line,
    /// Filled area between the polyline and the baseline.
    Area,
    /// Pie/donut wedges whose angles are proportional to each point's share of
    /// the total; negative or zero-sum data draws nothing.
    Pie,
    /// Unconnected markers, one per data point.
    Scatter,
    /// Floating bars from each point to the running total, showing how each
    /// increment contributes to a cumulative value.
    Waterfall,
    /// Progressively narrowing bars against a shared left edge, one per stage.
    ///
    /// Reads the first `series` entry; further entries are ignored, because a
    /// funnel is one measure per stage by definition.
    Funnel,
    /// Open/high/low/close bars, read as **four consecutive values per bar**:
    /// `[open, high, low, close, open, high, low, close, …]`.
    ///
    /// A trailing partial group is ignored rather than padded, so a caller cannot
    /// get a bar drawn from an invented value.
    Candlestick,
    /// Five-number summaries, read as **five consecutive values per box**:
    /// `[min, q1, median, q3, max, …]`.
    ///
    /// Trailing partial groups are ignored, as for `Candlestick`.
    BoxPlot,
}

impl ChartType {
    /// The factory spelling of this variant, matching `CHART_PROPERTIES`.
    pub fn as_str(self) -> &'static str {
        match self {
            ChartType::Bar => "bar",
            ChartType::Line => "line",
            ChartType::Area => "area",
            ChartType::Pie => "pie",
            ChartType::Scatter => "scatter",
            ChartType::Waterfall => "waterfall",
            ChartType::Funnel => "funnel",
            ChartType::Candlestick => "candlestick",
            ChartType::BoxPlot => "box_plot",
        }
    }

    /// Parses a factory spelling into a variant.
    pub fn from_name(name: &str) -> Option<Self> {
        Some(match name {
            "bar" => ChartType::Bar,
            "line" => ChartType::Line,
            "area" => ChartType::Area,
            "pie" => ChartType::Pie,
            "scatter" => ChartType::Scatter,
            "waterfall" => ChartType::Waterfall,
            "funnel" => ChartType::Funnel,
            "candlestick" => ChartType::Candlestick,
            "box_plot" => ChartType::BoxPlot,
            _ => return None,
        })
    }

    /// How many consecutive values in a series one drawn mark consumes.
    ///
    /// One for the single-value styles, four for `Candlestick`, five for
    /// `BoxPlot`. Exposed so a caller can size its data and so the drawing code and
    /// the documentation cannot disagree about the grouping.
    pub fn values_per_point(self) -> usize {
        match self {
            ChartType::Candlestick => 4,
            ChartType::BoxPlot => 5,
            _ => 1,
        }
    }
}

/// Chart widget for data visualization.
pub struct ChartWidget {
    base: BaseWidget,
    chart_type: ChartType,
    /// The drawn series.
    ///
    /// Always the storage; `data()` is series zero. Kept as a vector-of-vectors
    /// rather than a `Vec<f64>` plus an optional second vector so that "one
    /// series" and "many series" are the same code path — the previous
    /// `Vec<f64>`-only model could not express the multi-value variants above
    /// without a grouping convention embedded in the drawing code.
    series: Vec<Vec<f64>>,
    labels: Vec<String>,
    hovered_index: Option<usize>,
    /// How far the marks have grown from the baseline: `0.0` flat, `1.0` at their values.
    ///
    /// # Why this is a 0..=1 fraction and not a value
    ///
    /// [`PropertyDriver`] interpolates between `0.0` and `1.0` and **clamps its target**, so a
    /// driver aimed at a datum would silently sit at `1.0` for every bar whose value is below one --
    /// a chart that looks right for small integers and wrong for everything else, with no error.
    /// The driver therefore carries the *progress* and each mark maps it onto its own span (see
    /// [`Self::grown_from_baseline`]), which is also what makes one driver able to animate marks
    /// with different heights, signs and magnitudes at once.
    ///
    /// It rests at `1.0`: a chart is shown at its values the moment it is built, so it must not
    /// animate a seeded series into place on first paint.
    reveal: PropertyDriver,
    /// Emitted when a data point is clicked.
    pub data_point_clicked: Signal1<usize>,
    /// Emitted when pointer hover enters a data point bucket.
    pub data_point_hovered: Signal1<usize>,
    /// Emitted with the index hover is *leaving*.
    ///
    /// Carries the index that stopped being hovered rather than the one entered, so a
    /// subscriber can keep its own highlight in step without remembering the previous index
    /// itself. The sibling charts carry the same signal under their own naming
    /// (`bar_unhovered` on `candlestick_chart`); `ChartWidget` published only the enter half,
    /// so a hover highlight could be turned on and never off.
    pub data_point_unhovered: Signal1<usize>,
}
impl ChartWidget {
    /// Creates a new chart widget.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Chart, geometry, "ChartWidget"),
            chart_type: ChartType::default(),
            series: Vec::new(),
            labels: Vec::new(),
            hovered_index: None,
            // At rest grown: a chart is shown at its values the moment it is built.
            reveal: PropertyDriver::at(1.0, MotionSlot::Normal),
            data_point_clicked: Signal1::new(),
            data_point_hovered: Signal1::new(),
            data_point_unhovered: Signal1::new(),
        }
    }

    /// Returns the chart type.
    pub fn chart_type(&self) -> ChartType {
        self.chart_type
    }

    /// Returns the first series' values.
    ///
    /// The single-series spelling of [`Self::series`], kept because it was the
    /// whole API before multi-series existed and every non-multi-series style
    /// still has exactly one.
    pub fn data(&self) -> &[f64] {
        self.series.first().map_or(&[], |series| series.as_slice())
    }

    /// Returns every series.
    pub fn series(&self) -> &[Vec<f64>] {
        &self.series
    }

    /// Returns the chart data labels.
    pub fn labels(&self) -> &[String] {
        &self.labels
    }

    /// Returns the index of the hovered data point, if any.
    ///
    /// This is the accessor the module doc promises when it says every variant "shares the
    /// same interaction (`hovered_index`, ...)": the field was written by `handle_event` and
    /// read by nothing, so the hover state existed only as a local comparison and a caller had
    /// no way to observe it. The sibling charts (`candlestick_chart`, `volume_chart`,
    /// `indicator_chart`, `quote_board`, `order_book`) all expose this.
    pub fn hovered_index(&self) -> Option<usize> {
        self.hovered_index
    }

    /// The data value at the hovered index, if the index still names a point.
    pub fn hovered_value(&self) -> Option<f64> {
        let index = self.hovered_index?;
        self.data().get(index).copied()
    }

    /// Sets the chart type.
    pub fn set_chart_type(&mut self, chart_type: ChartType) {
        self.chart_type = chart_type;
        self.base.request_redraw();
    }

    /// Sets the chart data as a single series.
    pub fn set_data(&mut self, data: Vec<f64>) {
        self.series = if data.is_empty() { Vec::new() } else { vec![data] };
        self.restart_reveal();
        self.revalidate_hover();
        self.base.request_redraw();
    }

    /// Sets the chart data as multiple series.
    ///
    /// Series zero is what [`Self::data`] reports, so the two setters agree about
    /// which values are "the data". An empty input clears the chart, matching
    /// `set_data`.
    pub fn set_series(&mut self, series: Vec<Vec<f64>>) {
        self.series = series;
        self.restart_reveal();
        self.revalidate_hover();
        self.base.request_redraw();
    }

    /// Sets the chart data labels.
    pub fn set_labels(&mut self, labels: Vec<String>) {
        self.labels = labels;
        self.base.request_redraw();
    }

    /// Drops a hover index that the new data no longer has a point for.
    ///
    /// Replacing a 40-point series with a 5-point one left `hovered_index` naming index 30 —
    /// an index the chart cannot render and `data_point_hovered` will never emit again. The
    /// sibling charts re-validate on `set_series` for the same reason; `ChartWidget` did not.
    fn revalidate_hover(&mut self) {
        let points = self.data().len();
        if self.hovered_index.is_some_and(|index| index >= points) {
            self.hovered_index = None;
            self.data_point_unhovered.emit(0);
        }
    }

    /// Maps a pointer position to the index of the point under it.
    ///
    /// The bucket is computed from `data().len()`, so the hit area follows the
    /// marks the `x`-sequenced styles actually draw.
    fn data_index_at(&self, pos: Point) -> Option<usize> {
        let point_count = point_count_for(self.chart_type, self.data().len());
        if point_count == 0 {
            return None;
        }
        let rect = self.base.geometry();
        if !rect.contains_point(pos) || rect.width == 0 {
            return None;
        }
        let local_x = (pos.x - rect.x).max(0) as u32;
        let width = rect.width.max(1);
        let mut idx = ((local_x as u64) * (point_count as u64) / (width as u64)) as usize;
        if idx >= point_count {
            idx = point_count - 1;
        }
        Some(idx)
    }

    /// Restarts the value reveal, for a newly supplied series.
    ///
    /// Both data setters call this, so a caller that replaces the whole series and one that replaces
    /// a single series animate identically -- the two-places-to-remember defect this crate keeps
    /// recording. `jump_to` rather than `set_target`, so a second replacement restarts from flat
    /// instead of continuing from wherever the first reveal had reached.
    fn restart_reveal(&mut self) {
        self.reveal.jump_to(0.0);
        self.reveal.set_target(1.0);
    }

    /// How far the marks have grown from the baseline: `0.0` flat, `1.0` at their values.
    ///
    /// The value the draw measures with. It is `1.0` except in the frames right after a data set.
    pub fn reveal_progress(&self) -> f32 {
        self.reveal.value()
    }

    /// Maps the reveal onto one mark's own span: `baseline` at progress 0 and `value` at 1.
    ///
    /// # Why the mapping is here and not in the driver
    ///
    /// [`PropertyDriver`] carries a `0.0..=1.0` *fraction* and clamps its target. One driver drives
    /// every mark on the chart, and those marks have different values, different signs and different
    /// magnitudes -- so the driver cannot carry any of them. Each mark asks this question instead:
    /// "given how far along the whole reveal is, where is *my* top edge?".
    ///
    /// `baseline` is the value each mark starts from, which is the axis minimum for a bar (a bar
    /// grows up the axis) -- a mark that started from zero on an axis spanning `-50..50` would grow
    /// *downward* through the axis and cross every other mark on the way.
    fn grown_from_baseline(&self, value: f64, baseline: f64) -> f64 {
        let progress = self.reveal.value() as f64;
        if progress >= 1.0 {
            // The identity path: a settled chart is untouched to the last bit, so the resting
            // snapshot and every value assertion are exactly what they were before this existed.
            return value;
        }
        baseline + (value - baseline) * progress
    }

    /// The `(x, y)` extremes across every series, for the styles that share one
    /// value axis.
    ///
    /// Computed over all series rather than only series zero, so a multi-series
    /// line chart does not clip the taller series out of the plot area.
    fn value_range(&self) -> Option<(f64, f64)> {
        let mut min = f64::INFINITY;
        let mut max = f64::NEG_INFINITY;
        for value in self.series.iter().flatten() {
            if value.is_finite() {
                min = min.min(*value);
                max = max.max(*value);
            }
        }
        if !min.is_finite() || !max.is_finite() {
            return None;
        }
        Some((min, max))
    }
}

/// How many drawn points a series of `len` values produces under `chart_type`.
///
/// For the grouped styles this is the number of *complete* groups, so a trailing
/// partial group is neither drawn nor hoverable — there is no mark for it.
fn point_count_for(chart_type: ChartType, len: usize) -> usize {
    let per_point = chart_type.values_per_point();
    if per_point <= 1 {
        len
    } else {
        len / per_point
    }
}
impl Widget for ChartWidget {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(400, 300)
    }

    /// Advances the value reveal by `delta_ms`; `true` while the marks are still growing.
    fn tick(&mut self, delta_ms: u32) -> bool {
        self.reveal.tick(delta_ms)
    }

    fn is_animating(&self) -> bool {
        self.reveal.is_moving()
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `ChartWidget`'s property contract, published under the `Chart` kind.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch.
///
/// `WidgetKind::Chart` is the kind the capability layer pairs with `GanttWidget`,
/// so `task_count` / `selected_id` / `viewport_*` / `zoom_level` belong to that
/// control. `chart_capability` publishes no properties for this control, so this
/// contract inherits the shared four and owns nothing beyond them.
impl WidgetProperties for ChartWidget {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "chart_type" => {
                Ok(CapabilityValue::String(chart_type_to_str(self.chart_type()).to_string()))
            }
            "point_count" => Ok(CapabilityValue::UInt(point_count_for(
                self.chart_type,
                self.data().len(),
            ) as u64)),
            "label_count" => Ok(CapabilityValue::UInt(self.labels().len() as u64)),
            "series_count" => Ok(CapabilityValue::UInt(self.series().len() as u64)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "chart_type" => {
                self.set_chart_type(expect_chart_type(value)?);
                Ok(())
            }
            // Both counts are derived from the series the caller supplied through
            // `set_data` / `set_series` / `set_labels`.
            "point_count" | "label_count" | "series_count" => {
                Err(CapabilityAccessError::ReadOnlyProperty)
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "chart_type",
            "point_count",
            "label_count",
            "series_count",
            BASE_PROPERTY_NAMES
        ]
    }
}

/// Publishes `ChartType` as the shared lower-case token.
fn chart_type_to_str(chart_type: ChartType) -> &'static str {
    chart_type.as_str()
}

/// Parses the shared lower-case token back, rejecting anything else.
fn expect_chart_type(value: CapabilityValue) -> Result<ChartType, CapabilityAccessError> {
    match value {
        CapabilityValue::String(token) => {
            ChartType::from_name(&token).ok_or(CapabilityAccessError::TypeMismatch)
        }
        _ => Err(CapabilityAccessError::TypeMismatch),
    }
}

impl Draw for ChartWidget {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.base.geometry();
        use crate::core::Font;
        // The plot panel is a surface, so it resolves like every other control's: the
        // caller's style first, then the theme's resolved style for this control, then a
        // literal. It used to be a fixed `rgb(255,255,255)` for the fill and `rgb(200,200,200)`
        // for the border, which made a dark-appearance chart a white slab — and, worse,
        // `draw_truncated_label` *did* read the theme, so on the dark appearance it painted the
        // dark theme's ink onto that white slab: `rgb(163,163,163)` on white, 2.52:1. The panel
        // and its chrome now come from one derivation, so they cannot disagree.
        let style = self.base.style().clone();
        let (surface, ink) = Self::panel_colors_with(Some(&style));
        let plot = PlotArea::of(rect);
        let border = style
            .border_color
            .or_else(|| crate::style::resolved_theme_style("chart").and_then(|t| t.border_color))
            .unwrap_or_else(|| surface.blend(&ink, 0.2));
        // Draw chart background
        context.fill_rect(rect, surface);
        // Draw border to make chart area visible
        context.draw_rect(rect, border);

        if self.series.is_empty() {
            // Empty state: axis chrome plus a message, centred on the panel.
            //
            // The control used to paint only its own rectangle and return, leaving a bare
            // slab — no axes, no gridline, nothing that says "this is a chart with no data"
            // rather than "this is a rectangle". Drawing the frame it will use once data
            // arrives is what makes the two states read as the same control, and it is what
            // every charting toolkit does: the axes belong to the chart, not to a series.
            self.draw_value_axis(context, &plot, ink, surface);
            let font = Font::simple("Sans", 12.0);
            let line = context.text_line(rect, &font);
            context.draw_text_fitted(
                line,
                "No data",
                &font,
                ink.legible_on(surface, 4.5).with_alpha(160),
                HorizontalAlignment::Center,
            );
            return;
        }

        match self.chart_type {
            // The multi-series styles iterate every series, so a second series is
            // drawn beside the first rather than being ignored. The single-series
            // callers pass `0` and stop.
            ChartType::Bar => {
                self.draw_value_axis(context, &plot, ink, surface);
                for index in 0..self.series.len() {
                    self.draw_bar_chart(context, rect, index);
                }
            }
            ChartType::Line => {
                for index in 0..self.series.len() {
                    self.draw_line_chart(context, rect, index);
                }
            }
            ChartType::Area => {
                for index in 0..self.series.len() {
                    self.draw_area_chart(context, rect, index);
                }
            }
            ChartType::Scatter => {
                for index in 0..self.series.len() {
                    self.draw_scatter_chart(context, rect, index);
                }
            }
            ChartType::Pie => self.draw_pie_chart(context, rect),
            ChartType::Waterfall => self.draw_waterfall_chart(context, rect),
            ChartType::Funnel => self.draw_funnel_chart(context, rect),
            ChartType::Candlestick => self.draw_candlestick_chart(context, rect),
            ChartType::BoxPlot => self.draw_box_plot_chart(context, rect),
        }
    }
}

/// The plot area shared by the `x`-sequenced styles.
///
/// The four margins are named so that every renderer agrees on where the baseline
/// and the top of the plot are; deriving them per-renderer is how the axes drifted
/// apart in the first place.
struct PlotArea {
    /// Left edge of the plotting region.
    left: i32,
    /// Right edge (exclusive in arithmetic, inclusive visually).
    right: i32,
    /// Bottom edge, where value `min` is drawn.
    baseline_y: i32,
    /// Top edge, where value `max` is drawn.
    top_y: i32,
    /// Left edge of the control. The strip between this and [`Self::left`] is the value-axis
    /// label column, and naming it here is what lets the axis draw its labels without
    /// re-deriving the control's rectangle — the two would otherwise be free to disagree.
    outer_left: i32,
}

/// Distance from the plot baseline down to the top of the axis label row.
const LABEL_ROW_TOP: i32 = 12;
/// Line-box height of an axis label, in pixels. The label font is 10 pt, and the renderer's
/// line box is one em, so the two agree by construction.
const LABEL_ROW_HEIGHT: i32 = 10;

/// The margin between the axis label row's bottom edge and the control's own edge: 1 px.
///
/// The row's height is the line box, so without this the label's last pixel lands exactly on
/// the border stroke — visible in `chart.svg` as the category names sitting on the frame.
const LABEL_ROW_BOTTOM_GUARD: i32 = 1;

/// Width of the value-axis label column, in pixels.
///
/// Wide enough for a four-character label at the axis font plus the tick gap: `1000`,
/// `-250`, `0.75` all fit. It is a **reservation**, not a measurement, because the column has
/// to be the same width for every tick — a column sized to the widest tick would shift the
/// whole plot area every time the data range crossed a digit boundary, which reads as the
/// chart jumping when a value updates.
const AXIS_LABEL_COLUMN: i32 = 34;

impl PlotArea {
    /// Derives the plot area from the control's rectangle.
    fn of(rect: Rect) -> Self {
        const PADDING: i32 = 8;
        // The bottom margin has to cover the axis label row, which starts 12 px below the
        // baseline and is one 10 px line box tall, **plus** the one pixel that keeps the row's
        // last pixel inside the control. It was 20, so the row's bottom edge landed exactly on
        // the control's last pixel and any extra (a taller font, a scaled DPI) pushed it past.
        // It was then `12 + 10`, which put the row's bottom pixel *on* the frame's own stroke:
        // `chart.svg` drew the `A B C D` category labels at y=110..120 in a 120 px box, i.e.
        // flush with the border. `LABEL_ROW_BOTTOM_GUARD` states the reservation in the same
        // units the label uses and leaves the one pixel the border needs.
        const BOTTOM_MARGIN: i32 = LABEL_ROW_TOP + LABEL_ROW_HEIGHT + LABEL_ROW_BOTTOM_GUARD;
        // The left margin is the value-axis label column, not just the panel padding: the axis
        // draws its tick values in this strip, so the plot region has to start after them. It
        // was `PADDING` alone, which left no room for a label and is why the axis could not be
        // drawn at all before it was widened.
        let left = rect.x.saturating_add(AXIS_LABEL_COLUMN);
        let right = rect.x.saturating_add(rect.width as i32).saturating_sub(PADDING);
        let baseline_y = rect.y.saturating_add(rect.height as i32).saturating_sub(BOTTOM_MARGIN);
        let top_y = rect.y.saturating_add(PADDING);
        Self { left, right, baseline_y, top_y, outer_left: rect.x }
    }

    /// Left edge of the strip the value-axis labels are drawn in.
    fn axis_margin_left(&self) -> i32 {
        self.outer_left + 2
    }

    /// The height available to a mark, never zero (a zero height draws nothing and
    /// also divides by zero in the ratio, so the floor is load-bearing).
    fn height_range(&self) -> f64 {
        (self.baseline_y.saturating_sub(self.top_y)).max(1) as f64
    }

    /// Maps `value` to a y coordinate, given the series' extremes.
    ///
    /// Uses `min` as well as `max` so a series with negative values or a narrow
    /// range around a large offset is drawn at its true scale rather than being
    /// pinned to the baseline.
    fn y_for(&self, value: f64, min: f64, max: f64) -> i32 {
        let span = max - min;
        if !span.is_finite() || span <= 0.0 {
            return self.baseline_y;
        }
        let ratio = (value - min) / span;
        self.baseline_y - (ratio * self.height_range()) as i32
    }

    /// The x coordinate of point `index` out of `count`, spread across the area.
    fn x_for(&self, index: usize, count: usize, inset: i32) -> i32 {
        if count <= 1 {
            return self.left + (self.right - self.left) / 2;
        }
        let span = (self.right - self.left).saturating_sub(inset * 2).max(1);
        self.left + inset + (index as i32 * span) / (count as i32 - 1).max(1)
    }
}

/// Formats one value-axis tick label.
///
/// Rounding is deliberate rather than `{:?}`-style: a tick is a *reading*, and the extra
/// precision of the underlying `f64` is noise on a 10 px label (`0.30000000000000004`).
/// Integers print without a decimal point, which is the common case for this control's data,
/// and fractional ticks keep one decimal — enough to tell two adjacent ticks apart, and short
/// enough to fit [`AXIS_LABEL_COLUMN`].
fn format_axis_value(value: f64) -> String {
    if !value.is_finite() {
        return "—".to_string();
    }
    if (value - value.round()).abs() < 1e-9 {
        format!("{}", value.round() as i64)
    } else {
        format!("{value:.1}")
    }
}

/// Draws a label under `x`, truncated to a fixed budget so a long label cannot
/// run into its neighbour. The truncation marker is part of the visible text, so
/// it is counted in the budget rather than appended past it.
///
/// `right_bound` is the widget's own right edge: the label is centred on its tick, so a
/// tick near the edge would otherwise start inside and finish outside. Clamping the origin
/// is what keeps the axis row inside the control at any width.
fn draw_truncated_label(
    context: &mut RenderContext,
    x: i32,
    baseline_y: i32,
    label: &str,
    right_bound: i32,
) {
    use crate::core::Font;
    const BUDGET: usize = 6;
    if label.is_empty() {
        return;
    }
    let text = if label.chars().count() > BUDGET {
        let kept: String = label.chars().take(BUDGET - 2).collect();
        format!("{kept}..")
    } else {
        label.to_string()
    };
    let font = Font::simple("Sans", 10.0);
    let width = context.measure_text(&text, &font).width as i32;
    let origin_x = (x - width / 2).min(right_bound - width).max(0);
    // Axis chrome, derived from the **panel the label is painted on**. The literal `80,80,80`
    // is a light chart's label colour and rendered at 1.8:1 on the dark appearance — the
    // category names were effectively invisible while the chart itself looked correct.
    //
    // This used to read `theme.colors.background`, which is the *window* colour, while the
    // panel was a hardcoded white: on the dark appearance the label therefore used the dark
    // theme's ink on a white slab. Both now come from `ChartWidget::panel_colors`, so the
    // label cannot disagree with the panel it sits on.
    let (surface, ink) = ChartWidget::panel_colors();
    context.draw_text(
        crate::core::Point { x: origin_x, y: baseline_y + LABEL_ROW_TOP },
        &text,
        &font,
        ink.legible_on(surface, 4.5).with_alpha(191),
        HorizontalAlignment::Left,
    );
}

impl ChartWidget {
    /// The plot panel's surface and its ink, resolved the same way for every renderer.
    ///
    /// The caller's style wins, then the theme's resolved style for `chart`, then a literal.
    /// Factored out because the panel fill and the axis labels are painted in two different
    /// functions: when each derived its own colour they drifted, and on the dark appearance
    /// the labels used the theme's ink while the panel stayed hardcoded white.
    ///
    /// `style` is the caller's override for this widget, when the caller is the paint path
    /// that has one; the axis labels pass `None` and take the theme's own answer, because
    /// they are reading a panel the caller already decided the colour of.
    pub(crate) fn panel_colors_with(
        style: Option<&crate::style::WidgetStyle>,
    ) -> (crate::core::Color, crate::core::Color) {
        let theme = crate::style::resolved_theme_style("chart");
        let surface = style
            .and_then(|s| s.background_color)
            .or_else(|| theme.as_ref().and_then(|t| t.background_color))
            .unwrap_or(crate::core::Color::rgb(255, 255, 255));
        let ink = style
            .and_then(|s| s.text_color)
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or_else(|| surface.contrast_color());
        (surface, ink)
    }

    /// The plot panel's surface and ink when no caller override is in hand.
    pub(crate) fn panel_colors() -> (crate::core::Color, crate::core::Color) {
        Self::panel_colors_with(None)
    }

    /// The palette every renderer draws from.
    ///
    /// Shared rather than repeated so a bar and the line beside it cannot be
    /// different colours for the same series.
    const PALETTE: [crate::core::Color; 6] = [
        crate::core::Color::rgb(66, 133, 244),
        crate::core::Color::rgb(219, 68, 55),
        crate::core::Color::rgb(244, 180, 0),
        crate::core::Color::rgb(15, 157, 88),
        crate::core::Color::rgb(171, 71, 188),
        crate::core::Color::rgb(0, 172, 193),
    ];

    /// The colour of series `index`, cycling through [`Self::PALETTE`].
    fn series_color(index: usize) -> crate::core::Color {
        Self::PALETTE[index % Self::PALETTE.len()]
    }

    /// The value range the shared-axis styles plot against.
    ///
    /// Falls back to `(0, 1)` when the series is empty or entirely non-finite, so
    /// the callers never divide by a zero span. Bars and areas need a zero
    /// baseline to be readable, so the minimum is clamped to zero when every value
    /// is non-negative — otherwise a series of `[98, 99, 100]` would be drawn with
    /// its smallest bar at the baseline and look like zero.
    fn plot_range(&self) -> (f64, f64) {
        let Some((min, max)) = self.value_range() else {
            return (0.0, 1.0);
        };
        if min >= 0.0 {
            (0.0, if max > 0.0 { max } else { 1.0 })
        } else {
            (min, max)
        }
    }

    /// Draws the **value axis**: a tick column down the left of the plot area with four
    /// rounded value labels, plus the gridlines they belong to.
    ///
    /// # Why this exists
    ///
    /// This control published a `y_axis_label` property and its module documentation described
    /// a y axis, but `draw` had no left margin and no value labels at all: the highest bar
    /// simply reached `rect.y + PADDING`, with nothing on screen saying what value that was.
    /// A chart with no measurable scale is a picture, not a chart — every other toolkit (the
    /// shared design-system table, `fl_chart`'s `leftTitles`, SwiftUI's default `AxisMarks`) draws one by
    /// default. The axis is chrome, so it reads the same `ink`/`surface` pair the panel and the
    /// category labels use and cannot disagree with them about the appearance.
    ///
    /// # Tick values
    ///
    /// Four evenly spaced steps include both extremes, so the top label is exactly the value
    /// the tallest mark reaches and the bottom one is the axis minimum. They come from the same
    /// [`Self::plot_range`] the marks are mapped through, which is what keeps a label and the
    /// bar it labels on the same scale.
    fn draw_value_axis(
        &self,
        context: &mut RenderContext,
        area: &PlotArea,
        ink: Color,
        surface: Color,
    ) {
        const TICKS: i32 = 4;
        let (min, max) = self.plot_range();
        let axis_ink = ink.legible_on(surface, 4.5).with_alpha(190);
        let grid_ink = surface.blend(&axis_ink, 0.18);
        let font = Font::simple("Sans", 10.0);

        for step in 0..TICKS {
            let fraction = step as f64 / (TICKS - 1) as f64;
            let value = min + (max - min) * fraction;
            let y = area.y_for(value, min, max);
            // The axis line and its ticks are one hairline; the gridline runs from the axis to
            // the right edge of the plot so a bar can be read against it.
            context.draw_line(Point::new(area.left, y), Point::new(area.right, y), grid_ink);
            // The label sits in the margin the plot area reserved, vertically centred on its
            // tick. `text_line` is given a one-line-tall band around the tick's own row so a
            // tick at the top or bottom of the axis keeps its label inside the panel.
            let band = Rect {
                x: area.axis_margin_left(),
                y: y - LABEL_ROW_HEIGHT / 2,
                width: (area.left - area.axis_margin_left()).max(0) as u32,
                height: LABEL_ROW_HEIGHT as u32,
            };
            let line = context.text_line(band, &font);
            context.draw_text_fitted(
                line,
                &format_axis_value(value),
                &font,
                axis_ink,
                HorizontalAlignment::Right,
            );
        }
    }

    /// Draws vertical bars for series `series_index`.
    ///
    /// When the widget holds several series they are drawn side by side within
    /// each point's slot, which is the grouped-bar reading; with one series the
    /// slot arithmetic reduces to the full slot width.
    fn draw_bar_chart(&self, context: &mut RenderContext, rect: Rect, series_index: usize) {
        let data = match self.series.get(series_index) {
            Some(data) if !data.is_empty() => data,
            _ => return,
        };
        let area = PlotArea::of(rect);
        let (min, max) = self.plot_range();
        let series_total = self.series.len().max(1);
        let slot = (area.right - area.left).max(1) / data.len() as i32;
        let bar_width = (slot / series_total as i32).max(1);
        let gap = if series_total > 1 { 1 } else { 2 };

        for (i, &val) in data.iter().enumerate() {
            let slot_x = area.left + (i as i32) * slot;
            let x = slot_x + (series_index as i32) * bar_width;
            // The bar grows from the **baseline** toward its value, which is the one
            // interpolation a value chart can express: the axis does not move, only the mark
            // climbs it. `grown_from_baseline` maps the 0..=1 progress onto this bar's own
            // `min..val` span, so the driver never has to know the data range -- it clamps to
            // 0..=1, and handing it a raw value would have it snap to 0.0 for every bar below 1.
            let val = self.grown_from_baseline(val, min);
            let top = area.y_for(val, min, max);
            let color = Self::series_color(series_index);
            context.fill_rect(
                Rect {
                    x,
                    y: top,
                    width: bar_width.saturating_sub(gap).max(1) as u32,
                    height: area.baseline_y.saturating_sub(top).max(1) as u32,
                },
                color,
            );
            // Only the first series labels the axis: repeating the same labels once
            // per series draws them on top of each other.
            if series_index == 0 {
                if let Some(label) = self.labels.get(i) {
                    let label_x = slot_x + slot / 2;
                    draw_truncated_label(
                        context,
                        label_x,
                        area.baseline_y,
                        label,
                        rect.x + rect.width as i32,
                    );
                }
            }
        }
    }

    /// Draws a polyline for series `series_index`.
    fn draw_line_chart(&self, context: &mut RenderContext, rect: Rect, series_index: usize) {
        let data = match self.series.get(series_index) {
            Some(data) if data.len() >= 2 => data,
            _ => return,
        };
        let area = PlotArea::of(rect);
        let (min, max) = self.plot_range();
        let color = Self::series_color(series_index);
        let points: Vec<Point> = data
            .iter()
            .enumerate()
            .map(|(i, &val)| Point {
                x: area.x_for(i, data.len(), 0),
                // Same reveal as the bars: every vertex climbs from the **axis minimum**, so a line
                // grows out of the baseline instead of sliding in from wherever the series happened
                // to start. A series that starts away from `min` would otherwise drop a flat segment
                // onto the axis on the first frame and lift it off again.
                y: area.y_for(self.grown_from_baseline(val, min), min, max),
            })
            .collect();

        for pair in points.windows(2) {
            context.draw_line_stroke(pair[0], pair[1], color, 2);
        }
        for (i, point) in points.iter().enumerate() {
            context.fill_circle(*point, 3, color);
            if series_index == 0 {
                if let Some(label) = self.labels.get(i) {
                    draw_truncated_label(
                        context,
                        point.x,
                        area.baseline_y,
                        label,
                        rect.x + rect.width as i32,
                    );
                }
            }
        }
    }

    /// Draws a filled area between the polyline and the baseline.
    ///
    /// # Why this is a variant rather than a second widget
    ///
    /// The drawing engine already had an `AreaChart`, but the control layer never
    /// exposed it — so the style existed and could not be asked for. It shares the
    /// line chart's data model and hit-test exactly, which is the condition rule
    /// #80 sets for extending rather than adding.
    fn draw_area_chart(&self, context: &mut RenderContext, rect: Rect, series_index: usize) {
        let data = match self.series.get(series_index) {
            Some(data) if data.len() >= 2 => data,
            _ => return,
        };
        let area = PlotArea::of(rect);
        let (min, max) = self.plot_range();
        let color = Self::series_color(series_index);
        let points: Vec<Point> = data
            .iter()
            .enumerate()
            .map(|(i, &val)| Point {
                x: area.x_for(i, data.len(), 0),
                // Same reveal as the line: the fill tracks the polyline, so the two share the
                // mapping rather than each computing its own height.
                y: area.y_for(self.grown_from_baseline(val, min), min, max),
            })
            .collect();

        // Fill with columns rather than a polygon: the render context has no
        // filled-polygon primitive, and a one-pixel column per x is exactly the
        // area under the piecewise-linear curve. The vertical extent is taken from
        // the segment the column falls in, so the fill tracks the line instead of
        // stair-stepping at each point.
        for column in points.windows(2) {
            let (from, to) = (column[0], column[1]);
            let span = (to.x - from.x).max(1);
            for step in 0..=span {
                let x = from.x + step;
                let ratio = step as f64 / span as f64;
                let y = (from.y as f64 + (to.y as f64 - from.y as f64) * ratio) as i32;
                context.fill_rect(
                    Rect {
                        x,
                        y,
                        width: 1,
                        height: area.baseline_y.saturating_sub(y).max(1) as u32,
                    },
                    color,
                );
            }
        }
        for pair in points.windows(2) {
            context.draw_line_stroke(pair[0], pair[1], color, 2);
        }
        if series_index == 0 {
            for (i, point) in points.iter().enumerate() {
                if let Some(label) = self.labels.get(i) {
                    draw_truncated_label(
                        context,
                        point.x,
                        area.baseline_y,
                        label,
                        rect.x + rect.width as i32,
                    );
                }
            }
        }
    }

    /// Draws floating bars from each point to the running total.
    ///
    /// Each bar spans `previous_total` to `previous_total + value`, so a negative
    /// increment draws downward from the running total — which is what makes a
    /// waterfall readable rather than a set of bars at the wrong heights.
    fn draw_waterfall_chart(&self, context: &mut RenderContext, rect: Rect) {
        let data = match self.series.first() {
            Some(data) if !data.is_empty() => data,
            _ => return,
        };
        let area = PlotArea::of(rect);
        let mut cumulative = 0.0f64;
        let totals: Vec<(f64, f64)> = data
            .iter()
            .map(|&value| {
                let from = cumulative;
                cumulative += value;
                (from, cumulative)
            })
            .collect();

        // The range covers the running totals, which can exceed any single value.
        let mut min = 0.0f64;
        let mut max = 0.0f64;
        for (from, to) in &totals {
            min = min.min(*from).min(*to);
            max = max.max(*from).max(*to);
        }
        let span = max - min;
        if !span.is_finite() || span <= 0.0 {
            return;
        }

        let slot = (area.right - area.left).max(1) / data.len() as i32;
        let bar_width = slot.saturating_sub(2).max(1);
        for (i, &(from, to)) in totals.iter().enumerate() {
            let x = area.left + (i as i32) * slot;
            let y_from = area.baseline_y - (((from - min) / span) * area.height_range()) as i32;
            let y_to = area.baseline_y - (((to - min) / span) * area.height_range()) as i32;
            let top = y_from.min(y_to);
            let height = (y_from - y_to).unsigned_abs().max(1);
            // A rise and a fall get different colours, so the sign of each
            // increment is visible without reading the numbers.
            let color = if to >= from { Self::series_color(3) } else { Self::series_color(1) };
            context.fill_rect(Rect { x, y: top, width: bar_width as u32, height }, color);
            // A connector from this bar's top to the next bar's start, so the
            // running total is traceable across the chart.
            if i + 1 < totals.len() {
                let connector_y = y_to;
                context.draw_line_stroke(
                    Point { x: x + bar_width, y: connector_y },
                    Point { x: area.left + ((i + 1) as i32) * slot, y: connector_y },
                    crate::core::Color::rgb(150, 150, 150),
                    1,
                );
            }
            if let Some(label) = self.labels.get(i) {
                draw_truncated_label(
                    context,
                    x + bar_width / 2,
                    area.baseline_y,
                    label,
                    rect.x + rect.width as i32,
                );
            }
        }
    }

    /// Draws progressively narrowing bars against a shared left edge.
    ///
    /// The width is proportional to the value's share of the largest value, so the
    /// silhouette narrows exactly when the numbers fall.
    fn draw_funnel_chart(&self, context: &mut RenderContext, rect: Rect) {
        let data = match self.series.first() {
            Some(data) if !data.is_empty() => data,
            _ => return,
        };
        let max = data.iter().copied().fold(f64::NEG_INFINITY, f64::max);
        if !max.is_finite() || max <= 0.0 {
            return;
        }
        let area = PlotArea::of(rect);
        let available_height = area.baseline_y.saturating_sub(area.top_y).max(1);
        let stage_height = (available_height / data.len() as i32).max(1);
        let available_width = (area.right - area.left).max(1);

        for (i, &value) in data.iter().enumerate() {
            let ratio = (value / max).clamp(0.0, 1.0);
            let width = ((ratio * available_width as f64).round() as i32).max(1);
            let y = area.top_y + (i as i32) * stage_height;
            // Centred, so the narrowing reads as a funnel rather than a left-aligned
            // bar chart.
            let x = area.left + (available_width - width) / 2;
            context.fill_rect(
                Rect {
                    x,
                    y,
                    width: width as u32,
                    height: stage_height.saturating_sub(2).max(1) as u32,
                },
                Self::series_color(i),
            );
            if let Some(label) = self.labels.get(i) {
                // The label sits at the stage's left edge, which for a narrow stage
                // is inside the bar; centred text would be unreadable there.
                draw_truncated_label(
                    context,
                    x + 2,
                    y + stage_height - 4,
                    label,
                    rect.x + rect.width as i32,
                );
            }
        }
    }

    /// Draws open/high/low/close bars.
    ///
    /// Reads four consecutive values per mark: the body spans open→close and the
    /// wick spans low→high. A rising bar is drawn in the "up" colour and a falling
    /// one in the "down" colour, which is the convention that makes a candlestick
    /// readable at a glance. A trailing group with fewer than four values is
    /// ignored, because there is no bar to draw from it.
    fn draw_candlestick_chart(&self, context: &mut RenderContext, rect: Rect) {
        const VALUES_PER_BAR: usize = 4;
        let data = match self.series.first() {
            Some(data) => data,
            _ => return,
        };
        let bar_count = data.len() / VALUES_PER_BAR;
        if bar_count == 0 {
            return;
        }
        let area = PlotArea::of(rect);
        let mut min = f64::INFINITY;
        let mut max = f64::NEG_INFINITY;
        for bar in data.chunks_exact(VALUES_PER_BAR).take(bar_count) {
            for value in bar {
                if value.is_finite() {
                    min = min.min(*value);
                    max = max.max(*value);
                }
            }
        }
        if !min.is_finite() || !max.is_finite() || max <= min {
            return;
        }

        let slot = (area.right - area.left).max(1) / bar_count as i32;
        let body_width = slot.saturating_sub(2).max(3);
        let wick_x_offset = body_width / 2;
        for (i, bar) in data.chunks_exact(VALUES_PER_BAR).take(bar_count).enumerate() {
            let (open, high, low, close) = (bar[0], bar[1], bar[2], bar[3]);
            let x = area.left + (i as i32) * slot;
            let y_open = area.y_for(open, min, max);
            let y_close = area.y_for(close, min, max);
            let y_high = area.y_for(high, min, max);
            let y_low = area.y_for(low, min, max);
            let rising = close >= open;
            let color = if rising { Self::series_color(3) } else { Self::series_color(1) };

            // Wick: the high/low extremes, drawn first so the body covers its middle.
            let wick_x = x + wick_x_offset;
            context.draw_line_stroke(
                Point { x: wick_x, y: y_high },
                Point { x: wick_x, y: y_low },
                color,
                1,
            );
            let body_top = y_open.min(y_close);
            context.fill_rect(
                Rect {
                    x,
                    y: body_top,
                    width: body_width as u32,
                    // A doji (open == close) has no height; one pixel keeps it visible.
                    height: (y_open - y_close).unsigned_abs().max(1),
                },
                color,
            );
        }
        // One label per bar, placed under every fourth value's slot.
        for i in 0..bar_count {
            if let Some(label) = self.labels.get(i) {
                let x = area.left + (i as i32) * slot + slot / 2;
                draw_truncated_label(
                    context,
                    x,
                    area.baseline_y,
                    label,
                    rect.x + rect.width as i32,
                );
            }
        }
    }

    /// Draws five-number summary boxes.
    ///
    /// Reads five consecutive values per box — `min`, `q1`, `median`, `q3`, `max` —
    /// draws the box between `q1` and `q3`, the median line through it, and the
    /// whiskers out to `min` and `max`. A trailing partial group is ignored.
    fn draw_box_plot_chart(&self, context: &mut RenderContext, rect: Rect) {
        const VALUES_PER_BOX: usize = 5;
        let data = match self.series.first() {
            Some(data) => data,
            _ => return,
        };
        let box_count = data.len() / VALUES_PER_BOX;
        if box_count == 0 {
            return;
        }
        let area = PlotArea::of(rect);
        let mut min = f64::INFINITY;
        let mut max = f64::NEG_INFINITY;
        for group in data.chunks_exact(VALUES_PER_BOX).take(box_count) {
            for value in group {
                if value.is_finite() {
                    min = min.min(*value);
                    max = max.max(*value);
                }
            }
        }
        if !min.is_finite() || !max.is_finite() || max <= min {
            return;
        }

        let slot = (area.right - area.left).max(1) / box_count as i32;
        let box_width = slot.saturating_sub(4).max(4);
        let center_offset = box_width / 2;
        let color = Self::series_color(0);
        for (i, group) in data.chunks_exact(VALUES_PER_BOX).take(box_count).enumerate() {
            let (low, q1, median, q3, high) = (group[0], group[1], group[2], group[3], group[4]);
            let x = area.left + (i as i32) * slot + 2;
            let cx = x + center_offset;
            let y_low = area.y_for(low, min, max);
            let y_high = area.y_for(high, min, max);
            let y_q1 = area.y_for(q1, min, max);
            let y_q3 = area.y_for(q3, min, max);

            // Whiskers first, so the box covers their inner ends.
            context.draw_line_stroke(
                Point { x: cx, y: y_high },
                Point { x: cx, y: y_low },
                color,
                1,
            );
            let box_top = y_q1.min(y_q3);
            context.fill_rect(
                Rect {
                    x,
                    y: box_top,
                    width: box_width as u32,
                    height: (y_q1 - y_q3).unsigned_abs().max(1),
                },
                color,
            );
            // Median: drawn in the background colour so it reads as a line *through*
            // the box rather than another filled band.
            let y_median = area.y_for(median, min, max);
            context.fill_rect(
                Rect { x, y: y_median, width: box_width as u32, height: 2 },
                crate::core::Color::rgb(255, 255, 255),
            );
            if let Some(label) = self.labels.get(i) {
                draw_truncated_label(
                    context,
                    cx,
                    area.baseline_y,
                    label,
                    rect.x + rect.width as i32,
                );
            }
        }
    }

    fn draw_pie_chart(&self, context: &mut RenderContext, rect: Rect) {
        let data = match self.series.first() {
            Some(data) if !data.is_empty() => data,
            _ => return,
        };
        let total: f64 = data.iter().filter(|value| **value > 0.0).sum();
        if total <= 0.0 {
            return;
        }
        let cx = rect.x + rect.width as i32 / 2;
        let cy = rect.y + rect.height as i32 / 2;
        let radius = (rect.width.min(rect.height) as i32 / 2).saturating_sub(10).max(10);
        let mut start_angle = -std::f64::consts::FRAC_PI_2;
        for (i, &val) in data.iter().enumerate() {
            // A non-positive wedge has no angle; skipping it keeps the angle sum
            // equal to the sum of the positive values the total was taken over.
            if val <= 0.0 {
                continue;
            }
            let slice_angle = 2.0 * std::f64::consts::PI * (val / total);
            let mid_angle = start_angle + slice_angle / 2.0;
            let end_angle = start_angle + slice_angle;
            let color = Self::series_color(i);
            // Segment count scales with the arc length so a thin wedge is not drawn
            // with more spokes than its angle needs.
            let segments = ((radius as f64 * slice_angle * 0.4).ceil() as i32).clamp(1, 120);
            for s in 0..segments {
                let t = start_angle + slice_angle * (s as f64 + 0.5) / segments as f64;
                let ex = cx + (radius as f64 * t.cos()) as i32;
                let ey = cy + (radius as f64 * t.sin()) as i32;
                context.draw_line(Point { x: cx, y: cy }, Point { x: ex, y: ey }, color);
            }
            if let Some(label) = self.labels.get(i) {
                let label_radius = radius.saturating_add(14) as f64;
                let lx = cx + (label_radius * mid_angle.cos()) as i32;
                let ly = cy + (label_radius * mid_angle.sin()) as i32;
                let pct = val / total * 100.0;
                let text = if pct >= 1.0 {
                    format!("{label}:{pct:.0}%")
                } else {
                    format!("{label}:{pct:.1}%")
                };
                context.draw_text(
                    Point { x: lx, y: ly },
                    &text,
                    &crate::core::Font::simple("Sans", 9.0),
                    crate::core::Color::rgb(60, 60, 60),
                    HorizontalAlignment::Left,
                );
            }
            start_angle = end_angle;
        }
    }

    /// Draws unconnected markers for series `series_index`.
    fn draw_scatter_chart(&self, context: &mut RenderContext, rect: Rect, series_index: usize) {
        let data = match self.series.get(series_index) {
            Some(data) if !data.is_empty() => data,
            _ => return,
        };
        let area = PlotArea::of(rect);
        let (min, max) = self.plot_range();
        let color = Self::series_color(series_index);
        let slot = (area.right - area.left).max(1) / data.len() as i32;
        for (i, &val) in data.iter().enumerate() {
            // Scatter uses the slot centre, since unconnected markers have no
            // line to sit on.
            let x = area.left + (i as i32) * slot + slot / 2;
            let y = area.y_for(val, min, max);
            context.fill_circle(Point { x, y }, 3, color);
            if series_index == 0 {
                if let Some(label) = self.labels.get(i) {
                    draw_truncated_label(
                        context,
                        x,
                        area.baseline_y,
                        label,
                        rect.x + rect.width as i32,
                    );
                }
            }
        }
    }
}
impl EventHandler for ChartWidget {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MouseMove { pos } => {
                // Entering a *different* bucket must also leave the previous one, or a
                // subscriber that highlights on `data_point_hovered` accumulates highlights.
                let next = self.data_index_at(*pos);
                if next != self.hovered_index {
                    if let Some(previous) = self.hovered_index {
                        self.data_point_unhovered.emit(previous);
                    }
                    if let Some(index) = next {
                        self.hovered_index = Some(index);
                        self.data_point_hovered.emit(index);
                    } else {
                        // Moved off the plot area: no bucket is under the pointer.
                        self.hovered_index = None;
                    }
                    self.base.request_redraw();
                }
            }
            Event::MouseLeave { .. } => {
                // Without this arm `hovered_index` was only ever set, never cleared — the
                // chart kept reporting a hover after the pointer left, and the stale index
                // survived a `set_series` that shrank the data. Every sibling chart clears
                // on leave; this one now does too.
                if let Some(previous) = self.hovered_index.take() {
                    self.data_point_unhovered.emit(previous);
                    self.base.request_redraw();
                }
            }
            Event::MousePress { pos, button } if *button == 1 => {
                self.base.set_mouse_pressed(true);
                if let Some(index) = self.data_index_at(*pos) {
                    self.base.clicked.emit();
                    self.data_point_clicked.emit(index);
                }
            }
            Event::MouseRelease { pos: _, button } if *button == 1 => {
                self.base.set_mouse_pressed(false);
            }
            _ => { /* Other events are not relevant */ }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    #[test]
    fn chart_mouse_interaction_emits_data_index_signals() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
        chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);

        let clicked = Arc::new(Mutex::new(Vec::<usize>::new()));
        let hovered = Arc::new(Mutex::new(Vec::<usize>::new()));

        let clicked_sink = clicked.clone();
        chart.data_point_clicked.connect(move |index| {
            if let Ok(mut guard) = clicked_sink.lock() {
                guard.push(*index);
            }
        });

        let hovered_sink = hovered.clone();
        chart.data_point_hovered.connect(move |index| {
            if let Ok(mut guard) = hovered_sink.lock() {
                guard.push(*index);
            }
        });

        chart.handle_event(&Event::mouse_move(120, 50));
        chart.handle_event(&Event::mouse_press(120, 50, 1));

        let clicked_values = clicked.lock().expect("clicked lock poisoned").clone();
        let hovered_values = hovered.lock().expect("hovered lock poisoned").clone();

        assert_eq!(hovered_values, vec![2]);
        assert_eq!(clicked_values, vec![2]);
    }

    /// Renders the chart into a software frame and returns the pixels.
    fn render(chart: &mut ChartWidget, width: u32, height: u32) -> Vec<u8> {
        use crate::core::{Color, Size};
        use crate::render::{PaintBackend, SoftwarePaintBackend};
        let mut backend = SoftwarePaintBackend::new(Size::new(width, height), 1.0);
        backend.begin_frame(Color::WHITE);
        let mut context = RenderContext::new(&mut backend);
        chart.draw(&mut context);
        backend.end_frame();
        backend.frame_rgba().to_vec()
    }

    /// Counts pixels that are neither the white background nor the grey border.
    ///
    /// A renderer that silently draws nothing leaves the frame at background, so
    /// this is the discriminating measure for "the new variant actually painted".
    fn painted_pixels(rgba: &[u8]) -> usize {
        rgba.chunks_exact(4)
            .filter(|px| {
                let (r, g, b) = (px[0], px[1], px[2]);
                // Skip pure white (background) and the grey border family.
                !((r == 255 && g == 255 && b == 255) || (r == 200 && g == 200 && b == 200))
            })
            .count()
    }

    // ── Multi-series data model (C-1) ───────────────────────────────────────

    #[test]
    fn chart_set_data_populates_series_zero() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
        chart.set_data(vec![1.0, 2.0, 3.0]);
        assert_eq!(chart.data(), &[1.0, 2.0, 3.0]);
        assert_eq!(chart.series().len(), 1);
        assert_eq!(chart.get("series_count").unwrap(), CapabilityValue::UInt(1));
    }

    #[test]
    fn chart_set_data_empty_clears_series() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
        chart.set_data(vec![1.0]);
        chart.set_data(Vec::new());
        // An empty input must not leave a phantom series of length zero, which
        // would make `series_count` report 1 for a chart with nothing in it.
        assert!(chart.series().is_empty());
        assert_eq!(chart.get("series_count").unwrap(), CapabilityValue::UInt(0));
    }

    #[test]
    fn chart_set_series_keeps_every_series_and_agrees_with_data() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
        chart.set_series(vec![vec![1.0, 2.0], vec![3.0, 4.0, 5.0]]);
        assert_eq!(chart.series().len(), 2);
        assert_eq!(chart.data(), &[1.0, 2.0], "data() reports series zero");
        assert_eq!(chart.get("series_count").unwrap(), CapabilityValue::UInt(2));
    }

    // ── C-2: the new variants ───────────────────────────────────────────────

    #[test]
    fn chart_every_variant_paints_something() {
        for variant in [
            ChartType::Bar,
            ChartType::Line,
            ChartType::Area,
            ChartType::Pie,
            ChartType::Scatter,
            ChartType::Waterfall,
            ChartType::Funnel,
            ChartType::Candlestick,
            ChartType::BoxPlot,
        ] {
            let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
            chart.set_chart_type(variant);
            // Enough values for every variant, including the four- and five-value
            // groupings.
            chart.set_data(vec![
                10.0, 30.0, 20.0, 40.0, 25.0, 35.0, 15.0, 45.0, 30.0, 50.0, 40.0, 60.0, 45.0, 55.0,
                50.0, 70.0, 60.0, 80.0, 65.0, 75.0,
            ]);
            let rgba = render(&mut chart, 200, 120);
            assert!(
                painted_pixels(&rgba) > 0,
                "{variant:?} painted nothing; a variant that cannot draw is a name without a control"
            );
        }
    }

    #[test]
    fn chart_grouped_variants_ignore_trailing_partial_group() {
        // Seven values: one complete candlestick (4) plus three stragglers, and
        // one complete box (5) plus two stragglers.
        let mut candle = ChartWidget::new(Rect::new(0, 0, 200, 120));
        candle.set_chart_type(ChartType::Candlestick);
        candle.set_data(vec![10.0, 30.0, 5.0, 20.0, 99.0, 99.0, 99.0]);
        assert_eq!(
            candle.get("point_count").unwrap(),
            CapabilityValue::UInt(1),
            "three trailing values do not make a second candlestick"
        );

        let mut boxes = ChartWidget::new(Rect::new(0, 0, 200, 120));
        boxes.set_chart_type(ChartType::BoxPlot);
        boxes.set_data(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
        assert_eq!(
            boxes.get("point_count").unwrap(),
            CapabilityValue::UInt(1),
            "one trailing value does not make a second box"
        );
    }

    #[test]
    fn chart_values_per_point_matches_the_documented_grouping() {
        assert_eq!(ChartType::Candlestick.values_per_point(), 4);
        assert_eq!(ChartType::BoxPlot.values_per_point(), 5);
        for variant in [
            ChartType::Bar,
            ChartType::Line,
            ChartType::Area,
            ChartType::Pie,
            ChartType::Scatter,
            ChartType::Waterfall,
            ChartType::Funnel,
        ] {
            assert_eq!(variant.values_per_point(), 1);
        }
    }

    #[test]
    fn chart_hover_index_follows_the_grouping() {
        // With two candlesticks in a 200px wide chart, a pointer at x=150 is in the
        // second bucket, not the fourth value's bucket.
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        chart.set_chart_type(ChartType::Candlestick);
        chart.set_data(vec![10.0, 30.0, 5.0, 20.0, 15.0, 40.0, 10.0, 35.0]);

        let hovered = Arc::new(Mutex::new(Vec::<usize>::new()));
        let sink = hovered.clone();
        chart.data_point_hovered.connect(move |index| {
            if let Ok(mut guard) = sink.lock() {
                guard.push(*index);
            }
        });
        chart.handle_event(&Event::mouse_move(150, 50));

        assert_eq!(
            *hovered.lock().expect("hover lock poisoned"),
            vec![1],
            "the hit bucket counts bars, not raw values"
        );
    }

    // ── C-5: the tokens round-trip (rule #82) ───────────────────────────────

    #[test]
    fn chart_type_token_round_trips_for_every_variant() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        for variant in [
            ChartType::Bar,
            ChartType::Line,
            ChartType::Area,
            ChartType::Pie,
            ChartType::Scatter,
            ChartType::Waterfall,
            ChartType::Funnel,
            ChartType::Candlestick,
            ChartType::BoxPlot,
        ] {
            chart
                .set("chart_type", CapabilityValue::String(variant.as_str().to_string()))
                .expect("every published token must be writable");
            assert_eq!(chart.chart_type(), variant);
            assert_eq!(
                chart.get("chart_type").unwrap(),
                CapabilityValue::String(variant.as_str().to_string())
            );
            // `from_name` and `as_str` must agree, or a token could be published
            // that the parser rejects.
            assert_eq!(ChartType::from_name(variant.as_str()), Some(variant));
        }
        assert!(chart
            .set("chart_type", CapabilityValue::String("candlestick_chart".to_string()))
            .is_err());
    }

    #[test]
    fn chart_series_count_is_read_only() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        assert_eq!(
            chart.set("series_count", CapabilityValue::UInt(5)),
            Err(CapabilityAccessError::ReadOnlyProperty)
        );
    }

    #[test]
    fn chart_renders_negative_values_below_the_baseline() {
        // A series crossing zero must use a range that includes it, or the negative
        // bars would be drawn at a positive height.
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        chart.set_chart_type(ChartType::Bar);
        chart.set_data(vec![-10.0, 20.0, -5.0]);
        let rgba = render(&mut chart, 200, 120);
        assert!(painted_pixels(&rgba) > 0);
        assert_eq!(chart.chart_type(), ChartType::Bar);
    }

    /// Counts pixels drawn in the **first series' colour**, which is the data ink and nothing else.
    ///
    /// [`painted_pixels`] answers "did the control draw at all", and it counts the panel fill -- so
    /// it saturates at the panel's own area and cannot see a mark change height. A test about a mark's
    /// size has to count the mark, which means naming its colour: the series palette is the one part
    /// of this control that is deliberately data rather than chrome.
    fn series_pixels(rgba: &[u8], series: usize) -> usize {
        let color = ChartWidget::series_color(series);
        rgba.chunks_exact(4)
            .filter(|px| px[0] == color.r && px[1] == color.g && px[2] == color.b)
            .count()
    }

    /// Setting data makes the marks **grow** from the baseline rather than appearing at their
    /// heights between two frames.
    ///
    /// # The defect this pins
    ///
    /// Every style drew its marks at their final positions on the first frame after a `set_data`,
    /// so a chart whose values changed looked identical to one whose values had always been there --
    /// the reader had no way to tell an update from a repaint. The assertions are in three parts,
    /// because a driver nothing reads is not an animation: the progress must take an interior value,
    /// the *painted* frame must differ at that moment, and the pixels must be **shorter** (a chart
    /// that merely redrew at a different moment would satisfy "differs").
    ///
    /// The height comparison is the half that cannot be faked: with the reveal at `1.0` the mapping
    /// is the identity, so a settled chart paints exactly what it always did, and every pixel
    /// assertion in this module keeps its previous meaning.
    #[test]
    fn setting_data_grows_the_marks_from_the_baseline() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        chart.set_chart_type(ChartType::Bar);
        chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);
        assert!(chart.is_animating(), "freshly set data owes frames");

        assert!(chart.tick(20), "still growing after one step");
        let mid = chart.reveal_progress();
        assert!(mid > 0.0 && mid < 1.0, "it passes through an interior value (got {mid})");
        let mid_pixels = series_pixels(&render(&mut chart, 200, 120), 0);

        while chart.tick(1000) {}
        assert_eq!(chart.reveal_progress(), 1.0, "and settles fully grown");
        assert!(!chart.is_animating(), "owing no further frames");
        let settled_pixels = series_pixels(&render(&mut chart, 200, 120), 0);

        assert!(
            mid_pixels > 0 && mid_pixels < settled_pixels,
            "a half-grown chart must paint fewer pixels than a settled one: \
             mid={mid_pixels} settled={settled_pixels}"
        );

        // A second set restarts the growth rather than continuing from the settled end.
        chart.set_data(vec![5.0, 5.0, 5.0, 5.0]);
        assert!(
            chart.reveal_progress() < 1.0,
            "replacing the data restarts the reveal: {}",
            chart.reveal_progress()
        );
    }
    /// Hover is observable through the accessor the module doc promises.
    ///
    /// `hovered_index` was written by `handle_event` and read by nothing, and had no
    /// accessor at all — so the "shared interaction (`hovered_index`, ...)" the module doc
    /// describes was not reachable by a caller.
    #[test]
    fn chart_hovered_index_is_observable() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);
        assert_eq!(chart.hovered_index(), None, "nothing is hovered initially");

        chart.handle_event(&Event::mouse_move(120, 50));
        assert_eq!(chart.hovered_index(), Some(2));
        assert_eq!(chart.hovered_value(), Some(30.0));
    }

    /// Leaving the chart clears the hover, and says which point was left.
    ///
    /// There was no `MouseLeave` arm, so `hovered_index` was only ever set: the chart kept
    /// reporting a hover after the pointer left, and a highlight driven by
    /// `data_point_hovered` could be turned on but never off. The accessor reports the index
    /// that stopped being hovered, matching the sibling charts' `*_unhovered` signals.
    #[test]
    fn chart_mouse_leave_clears_hover_and_reports_it() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);

        let unhovered = Arc::new(Mutex::new(Vec::<usize>::new()));
        let sink = unhovered.clone();
        chart.data_point_unhovered.connect(move |index| {
            if let Ok(mut guard) = sink.lock() {
                guard.push(*index);
            }
        });

        chart.handle_event(&Event::mouse_move(120, 50));
        assert_eq!(chart.hovered_index(), Some(2));

        chart.handle_event(&Event::mouse_leave(120, 50));
        assert_eq!(chart.hovered_index(), None, "leave must clear the hover");
        assert_eq!(
            unhovered.lock().expect("lock poisoned").clone(),
            vec![2],
            "leave must report the point it left"
        );

        // A second leave with nothing hovered must not emit again.
        chart.handle_event(&Event::mouse_leave(120, 50));
        assert_eq!(unhovered.lock().expect("lock poisoned").len(), 1);
    }

    /// Moving between buckets leaves the previous one before entering the next.
    #[test]
    fn chart_moving_between_buckets_unhovers_the_previous() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);

        let events = Arc::new(Mutex::new(Vec::<String>::new()));
        let hover_sink = events.clone();
        chart.data_point_hovered.connect(move |index| {
            if let Ok(mut guard) = hover_sink.lock() {
                guard.push(format!("enter {index}"));
            }
        });
        let unhover_sink = events.clone();
        chart.data_point_unhovered.connect(move |index| {
            if let Ok(mut guard) = unhover_sink.lock() {
                guard.push(format!("leave {index}"));
            }
        });

        chart.handle_event(&Event::mouse_move(30, 50));
        chart.handle_event(&Event::mouse_move(120, 50));

        assert_eq!(
            events.lock().expect("lock poisoned").clone(),
            vec!["enter 0".to_string(), "leave 0".to_string(), "enter 2".to_string()],
            "a bucket change must leave the old bucket before entering the new one"
        );
    }

    /// Replacing the data drops a hover that no longer names a point.
    ///
    /// The sibling charts re-validate on `set_series`. `ChartWidget` kept a stale index, so
    /// `hovered_index()` reported a point the chart cannot draw and `data_point_hovered`
    /// would never fire for again.
    #[test]
    fn chart_replacing_data_drops_a_stale_hover() {
        let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
        chart.set_data(vec![1.0; 40]);
        chart.handle_event(&Event::mouse_move(150, 50));
        let index = chart.hovered_index().expect("the pointer is over a point");
        assert!(index >= 5, "expected a high index for a 40-point series, got {index}");

        // Shrink the series below the hovered index.
        chart.set_data(vec![1.0; 5]);
        assert_eq!(chart.hovered_index(), None, "the stale index must be dropped");
        assert_eq!(chart.hovered_value(), None);

        // A hover that *is* still in range survives the replacement.
        chart.handle_event(&Event::mouse_move(30, 50));
        let in_range = chart.hovered_index().expect("pointer over a point");
        assert!(in_range < 5);
        chart.set_data(vec![1.0; 8]);
        assert_eq!(chart.hovered_index(), Some(in_range), "an in-range hover is kept");
    }
}