ratatui/widgets/
barchart.rs

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
use crate::{
    buffer::Buffer,
    layout::{Direction, Rect},
    style::{Style, Styled},
    symbols::{self},
    text::Line,
    widgets::{block::BlockExt, Block, Widget, WidgetRef},
};

mod bar;
mod bar_group;

pub use bar::Bar;
pub use bar_group::BarGroup;

/// A chart showing values as [bars](Bar).
///
/// Here is a possible `BarChart` output.
/// ```plain
/// ┌─────────────────────────────────┐
/// │                             ████│
/// │                        ▅▅▅▅ ████│
/// │            ▇▇▇▇        ████ ████│
/// │     ▄▄▄▄   ████ ████   ████ ████│
/// │▆10▆ █20█   █50█ █40█   █60█ █90█│
/// │ B1   B2     B1   B2     B1   B2 │
/// │ Group1      Group2      Group3  │
/// └─────────────────────────────────┘
/// ```
///
/// A `BarChart` is composed of a set of [`Bar`] which can be set via [`BarChart::data`].
/// Bars can be styled globally ([`BarChart::bar_style`]) or individually ([`Bar::style`]).
/// There are other methods available to style even more precisely. See [`Bar`] to find out about
/// each bar component.
///
/// The `BarChart` widget can also show groups of bars via [`BarGroup`].
/// A [`BarGroup`] is a set of [`Bar`], multiple can be added to a `BarChart` using
/// [`BarChart::data`] multiple time as demonstrated in the example below.
///
/// The chart can have a [`Direction`] (by default the bars are [`Vertical`](Direction::Vertical)).
/// This is set using [`BarChart::direction`].
///
/// Note: this is the only widget that doesn't implement `Widget` for `&T` because the current
/// implementation modifies the internal state of self. This will be fixed in the future.
///
/// # Examples
///
/// The following example creates a `BarChart` with two groups of bars.
/// The first group is added by an array slice (`&[(&str, u64)]`).
/// The second group is added by a [`BarGroup`] instance.
/// ```
/// use ratatui::{
///     style::{Style, Stylize},
///     widgets::{Bar, BarChart, BarGroup, Block},
/// };
///
/// BarChart::default()
///     .block(Block::bordered().title("BarChart"))
///     .bar_width(3)
///     .bar_gap(1)
///     .group_gap(3)
///     .bar_style(Style::new().yellow().on_red())
///     .value_style(Style::new().red().bold())
///     .label_style(Style::new().white())
///     .data(&[("B0", 0), ("B1", 2), ("B2", 4), ("B3", 3)])
///     .data(BarGroup::default().bars(&[Bar::default().value(10), Bar::default().value(20)]))
///     .max(4);
/// ```
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct BarChart<'a> {
    /// Block to wrap the widget in
    block: Option<Block<'a>>,
    /// The width of each bar
    bar_width: u16,
    /// The gap between each bar
    bar_gap: u16,
    /// The gap between each group
    group_gap: u16,
    /// Set of symbols used to display the data
    bar_set: symbols::bar::Set,
    /// Style of the bars
    bar_style: Style,
    /// Style of the values printed at the bottom of each bar
    value_style: Style,
    /// Style of the labels printed under each bar
    label_style: Style,
    /// Style for the widget
    style: Style,
    /// vector of groups containing bars
    data: Vec<BarGroup<'a>>,
    /// Value necessary for a bar to reach the maximum height (if no value is specified,
    /// the maximum value in the data is taken as reference)
    max: Option<u64>,
    /// direction of the bars
    direction: Direction,
}

impl<'a> Default for BarChart<'a> {
    fn default() -> Self {
        Self {
            block: None,
            max: None,
            data: Vec::new(),
            bar_style: Style::default(),
            bar_width: 1,
            bar_gap: 1,
            value_style: Style::default(),
            label_style: Style::default(),
            group_gap: 0,
            bar_set: symbols::bar::NINE_LEVELS,
            style: Style::default(),
            direction: Direction::Vertical,
        }
    }
}

impl<'a> BarChart<'a> {
    /// Add group of bars to the `BarChart`
    ///
    /// # Examples
    ///
    /// The following example creates a `BarChart` with two groups of bars.
    /// The first group is added by an array slice (`&[(&str, u64)]`).
    /// The second group is added by a [`BarGroup`] instance.
    /// ```
    /// use ratatui::widgets::{Bar, BarChart, BarGroup};
    ///
    /// BarChart::default()
    ///     .data(&[("B0", 0), ("B1", 2), ("B2", 4), ("B3", 3)])
    ///     .data(BarGroup::default().bars(&[Bar::default().value(10), Bar::default().value(20)]));
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub fn data(mut self, data: impl Into<BarGroup<'a>>) -> Self {
        let group: BarGroup = data.into();
        if !group.bars.is_empty() {
            self.data.push(group);
        }
        self
    }

    /// Surround the [`BarChart`] with a [`Block`].
    #[must_use = "method moves the value of self and returns the modified value"]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Set the value necessary for a [`Bar`] to reach the maximum height.
    ///
    /// If not set, the maximum value in the data is taken as reference.
    ///
    /// # Examples
    ///
    /// This example shows the default behavior when `max` is not set.
    /// The maximum value in the dataset is taken (here, `100`).
    /// ```
    /// use ratatui::widgets::BarChart;
    /// BarChart::default().data(&[("foo", 1), ("bar", 2), ("baz", 100)]);
    /// // Renders
    /// //     █
    /// //     █
    /// // f b b
    /// ```
    ///
    /// This example shows a custom max value.
    /// The maximum height being `2`, `bar` & `baz` render as the max.
    /// ```
    /// use ratatui::widgets::BarChart;
    ///
    /// BarChart::default()
    ///     .data(&[("foo", 1), ("bar", 2), ("baz", 100)])
    ///     .max(2);
    /// // Renders
    /// //   █ █
    /// // █ █ █
    /// // f b b
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn max(mut self, max: u64) -> Self {
        self.max = Some(max);
        self
    }

    /// Set the default style of the bar.
    ///
    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
    /// your own type that implements [`Into<Style>`]).
    ///
    /// It is also possible to set individually the style of each [`Bar`].
    /// In this case the default style will be patched by the individual style
    ///
    /// [`Color`]: crate::style::Color
    #[must_use = "method moves the value of self and returns the modified value"]
    pub fn bar_style<S: Into<Style>>(mut self, style: S) -> Self {
        self.bar_style = style.into();
        self
    }

    /// Set the width of the displayed bars.
    ///
    /// For [`Horizontal`](crate::layout::Direction::Horizontal) bars this becomes the height of
    /// the bar.
    ///
    /// If not set, this defaults to `1`.
    /// The bar label also uses this value as its width.
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn bar_width(mut self, width: u16) -> Self {
        self.bar_width = width;
        self
    }

    /// Set the gap between each bar.
    ///
    /// If not set, this defaults to `1`.
    /// The bar label will never be larger than the bar itself, even if the gap is sufficient.
    ///
    /// # Example
    ///
    /// This shows two bars with a gap of `3`. Notice the labels will always stay under the bar.
    /// ```
    /// use ratatui::widgets::BarChart;
    ///
    /// BarChart::default()
    ///     .data(&[("foo", 1), ("bar", 2)])
    ///     .bar_gap(3);
    /// // Renders
    /// //     █
    /// // █   █
    /// // f   b
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn bar_gap(mut self, gap: u16) -> Self {
        self.bar_gap = gap;
        self
    }

    /// The [`bar::Set`](crate::symbols::bar::Set) to use for displaying the bars.
    ///
    /// If not set, the default is [`bar::NINE_LEVELS`](crate::symbols::bar::NINE_LEVELS).
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn bar_set(mut self, bar_set: symbols::bar::Set) -> Self {
        self.bar_set = bar_set;
        self
    }

    /// Set the default value style of the bar.
    ///
    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
    /// your own type that implements [`Into<Style>`]).
    ///
    /// It is also possible to set individually the value style of each [`Bar`].
    /// In this case the default value style will be patched by the individual value style
    ///
    /// # See also
    ///
    /// [`Bar::value_style`] to set the value style individually.
    ///
    /// [`Color`]: crate::style::Color
    #[must_use = "method moves the value of self and returns the modified value"]
    pub fn value_style<S: Into<Style>>(mut self, style: S) -> Self {
        self.value_style = style.into();
        self
    }

    /// Set the default label style of the groups and bars.
    ///
    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
    /// your own type that implements [`Into<Style>`]).
    ///
    /// It is also possible to set individually the label style of each [`Bar`] or [`BarGroup`].
    /// In this case the default label style will be patched by the individual label style
    ///
    /// # See also
    ///
    /// [`Bar::label`] to set the label style individually.
    ///
    /// [`Color`]: crate::style::Color
    #[must_use = "method moves the value of self and returns the modified value"]
    pub fn label_style<S: Into<Style>>(mut self, style: S) -> Self {
        self.label_style = style.into();
        self
    }

    /// Set the gap between [`BarGroup`].
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn group_gap(mut self, gap: u16) -> Self {
        self.group_gap = gap;
        self
    }

    /// Set the style of the entire chart.
    ///
    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
    /// your own type that implements [`Into<Style>`]).
    ///
    /// The style will be applied to everything that isn't styled (borders, bars, labels, ...).
    ///
    /// [`Color`]: crate::style::Color
    #[must_use = "method moves the value of self and returns the modified value"]
    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
        self.style = style.into();
        self
    }

    /// Set the direction of the bars.
    ///
    /// [`Vertical`](crate::layout::Direction::Vertical) bars are the default.
    ///
    /// # Examples
    ///
    /// Vertical bars
    /// ```plain
    ///   █
    /// █ █
    /// f b
    /// ```
    ///
    /// Horizontal bars
    /// ```plain
    /// █foo██
    ///
    /// █bar██
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn direction(mut self, direction: Direction) -> Self {
        self.direction = direction;
        self
    }
}

#[derive(Clone, Copy)]
struct LabelInfo {
    group_label_visible: bool,
    bar_label_visible: bool,
    height: u16,
}

impl BarChart<'_> {
    /// Returns the visible bars length in ticks. A cell contains 8 ticks.
    /// `available_space` used to calculate how many bars can fit in the space
    /// `bar_max_length` is the maximal length a bar can take.
    fn group_ticks(&self, available_space: u16, bar_max_length: u16) -> Vec<Vec<u64>> {
        let max: u64 = self.maximum_data_value();
        self.data
            .iter()
            .scan(available_space, |space, group| {
                if *space == 0 {
                    return None;
                }
                let n_bars = group.bars.len() as u16;
                let group_width = n_bars * self.bar_width + n_bars.saturating_sub(1) * self.bar_gap;

                let n_bars = if *space > group_width {
                    *space = space.saturating_sub(group_width + self.group_gap + self.bar_gap);
                    Some(n_bars)
                } else {
                    let max_bars = (*space + self.bar_gap) / (self.bar_width + self.bar_gap);
                    if max_bars > 0 {
                        *space = 0;
                        Some(max_bars)
                    } else {
                        None
                    }
                };

                n_bars.map(|n| {
                    group
                        .bars
                        .iter()
                        .take(n as usize)
                        .map(|bar| bar.value * u64::from(bar_max_length) * 8 / max)
                        .collect()
                })
            })
            .collect()
    }

    /// Get label information.
    ///
    /// height is the number of lines, which depends on whether we need to print the bar
    /// labels and/or the group labels.
    /// - If there are no labels, height is 0.
    /// - If there are only bar labels, height is 1.
    /// - If there are only group labels, height is 1.
    /// - If there are both bar and group labels, height is 2.
    fn label_info(&self, available_height: u16) -> LabelInfo {
        if available_height == 0 {
            return LabelInfo {
                group_label_visible: false,
                bar_label_visible: false,
                height: 0,
            };
        }

        let bar_label_visible = self
            .data
            .iter()
            .any(|e| e.bars.iter().any(|e| e.label.is_some()));

        if available_height == 1 && bar_label_visible {
            return LabelInfo {
                group_label_visible: false,
                bar_label_visible: true,
                height: 1,
            };
        }

        let group_label_visible = self.data.iter().any(|e| e.label.is_some());
        LabelInfo {
            group_label_visible,
            bar_label_visible,
            // convert true to 1 and false to 0 and add the two values
            height: u16::from(group_label_visible) + u16::from(bar_label_visible),
        }
    }

    fn render_horizontal(&self, buf: &mut Buffer, area: Rect) {
        // get the longest label
        let label_size = self
            .data
            .iter()
            .flat_map(|group| group.bars.iter().map(|bar| &bar.label))
            .flatten() // bar.label is an Option<Line>
            .map(Line::width)
            .max()
            .unwrap_or(0) as u16;

        let label_x = area.x;
        let bars_area = {
            let margin = u16::from(label_size != 0);
            Rect {
                x: area.x + label_size + margin,
                width: area.width - label_size - margin,
                ..area
            }
        };

        let group_ticks = self.group_ticks(bars_area.height, bars_area.width);

        // print all visible bars, label and values
        let mut bar_y = bars_area.top();
        for (ticks_vec, group) in group_ticks.into_iter().zip(self.data.iter()) {
            for (ticks, bar) in ticks_vec.into_iter().zip(group.bars.iter()) {
                let bar_length = (ticks / 8) as u16;
                let bar_style = self.bar_style.patch(bar.style);

                for y in 0..self.bar_width {
                    let bar_y = bar_y + y;
                    for x in 0..bars_area.width {
                        let symbol = if x < bar_length {
                            self.bar_set.full
                        } else {
                            self.bar_set.empty
                        };
                        buf[(bars_area.left() + x, bar_y)]
                            .set_symbol(symbol)
                            .set_style(bar_style);
                    }
                }

                let bar_value_area = Rect {
                    y: bar_y + (self.bar_width >> 1),
                    ..bars_area
                };

                // label
                if let Some(label) = &bar.label {
                    buf.set_line(label_x, bar_value_area.top(), label, label_size);
                }

                bar.render_value_with_different_styles(
                    buf,
                    bar_value_area,
                    bar_length as usize,
                    self.value_style,
                    self.bar_style,
                );

                bar_y += self.bar_gap + self.bar_width;
            }

            // if group_gap is zero, then there is no place to print the group label
            // check also if the group label is still inside the visible area
            let label_y = bar_y - self.bar_gap;
            if self.group_gap > 0 && label_y < bars_area.bottom() {
                let label_rect = Rect {
                    y: label_y,
                    ..bars_area
                };
                group.render_label(buf, label_rect, self.label_style);
                bar_y += self.group_gap;
            }
        }
    }

    fn render_vertical(&self, buf: &mut Buffer, area: Rect) {
        let label_info = self.label_info(area.height - 1);

        let bars_area = Rect {
            height: area.height - label_info.height,
            ..area
        };

        let group_ticks = self.group_ticks(bars_area.width, bars_area.height);
        self.render_vertical_bars(bars_area, buf, &group_ticks);
        self.render_labels_and_values(area, buf, label_info, &group_ticks);
    }

    fn render_vertical_bars(&self, area: Rect, buf: &mut Buffer, group_ticks: &[Vec<u64>]) {
        // print all visible bars (without labels and values)
        let mut bar_x = area.left();
        for (ticks_vec, group) in group_ticks.iter().zip(&self.data) {
            for (ticks, bar) in ticks_vec.iter().zip(&group.bars) {
                let mut ticks = *ticks;
                for j in (0..area.height).rev() {
                    let symbol = match ticks {
                        0 => self.bar_set.empty,
                        1 => self.bar_set.one_eighth,
                        2 => self.bar_set.one_quarter,
                        3 => self.bar_set.three_eighths,
                        4 => self.bar_set.half,
                        5 => self.bar_set.five_eighths,
                        6 => self.bar_set.three_quarters,
                        7 => self.bar_set.seven_eighths,
                        _ => self.bar_set.full,
                    };

                    let bar_style = self.bar_style.patch(bar.style);

                    for x in 0..self.bar_width {
                        buf[(bar_x + x, area.top() + j)]
                            .set_symbol(symbol)
                            .set_style(bar_style);
                    }

                    ticks = ticks.saturating_sub(8);
                }
                bar_x += self.bar_gap + self.bar_width;
            }
            bar_x += self.group_gap;
        }
    }

    /// get the maximum data value. the returned value is always greater equal 1
    fn maximum_data_value(&self) -> u64 {
        self.max
            .unwrap_or_else(|| {
                self.data
                    .iter()
                    .map(|group| group.max().unwrap_or_default())
                    .max()
                    .unwrap_or_default()
            })
            .max(1)
    }

    fn render_labels_and_values(
        &self,
        area: Rect,
        buf: &mut Buffer,
        label_info: LabelInfo,
        group_ticks: &[Vec<u64>],
    ) {
        // print labels and values in one go
        let mut bar_x = area.left();
        let bar_y = area.bottom() - label_info.height - 1;
        for (group, ticks_vec) in self.data.iter().zip(group_ticks) {
            if group.bars.is_empty() {
                continue;
            }
            // print group labels under the bars or the previous labels
            if label_info.group_label_visible {
                let label_max_width =
                    ticks_vec.len() as u16 * (self.bar_width + self.bar_gap) - self.bar_gap;
                let group_area = Rect {
                    x: bar_x,
                    y: area.bottom() - 1,
                    width: label_max_width,
                    height: 1,
                };
                group.render_label(buf, group_area, self.label_style);
            }

            // print the bar values and numbers
            for (bar, ticks) in group.bars.iter().zip(ticks_vec) {
                if label_info.bar_label_visible {
                    bar.render_label(buf, self.bar_width, bar_x, bar_y + 1, self.label_style);
                }

                bar.render_value(buf, self.bar_width, bar_x, bar_y, self.value_style, *ticks);

                bar_x += self.bar_gap + self.bar_width;
            }
            bar_x += self.group_gap;
        }
    }
}

impl Widget for BarChart<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        self.render_ref(area, buf);
    }
}

impl WidgetRef for BarChart<'_> {
    fn render_ref(&self, area: Rect, buf: &mut Buffer) {
        buf.set_style(area, self.style);

        self.block.render_ref(area, buf);
        let inner = self.block.inner_if_some(area);

        if inner.is_empty() || self.data.is_empty() || self.bar_width == 0 {
            return;
        }

        match self.direction {
            Direction::Horizontal => self.render_horizontal(buf, inner),
            Direction::Vertical => self.render_vertical(buf, inner),
        }
    }
}

impl<'a> Styled for BarChart<'a> {
    type Item = Self;
    fn style(&self) -> Style {
        self.style
    }

    fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
        self.style(style)
    }
}

#[cfg(test)]
mod tests {
    use itertools::iproduct;

    use super::*;
    use crate::{
        layout::Alignment,
        style::{Color, Modifier, Stylize},
        text::Span,
        widgets::BorderType,
    };

    #[test]
    fn default() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default();
        widget.render(buffer.area, &mut buffer);
        assert_eq!(buffer, Buffer::with_lines(["          "; 3]));
    }

    #[test]
    fn data() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default().data(&[("foo", 1), ("bar", 2)]);
        widget.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "  █       ",
            "1 2       ",
            "f b       ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn block() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 5));
        let block = Block::bordered()
            .border_type(BorderType::Double)
            .title("Block");
        let widget = BarChart::default()
            .data(&[("foo", 1), ("bar", 2)])
            .block(block);
        widget.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "╔Block═══╗",
            "║  █     ║",
            "║1 2     ║",
            "║f b     ║",
            "╚════════╝",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn max() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let without_max = BarChart::default().data(&[("foo", 1), ("bar", 2), ("baz", 100)]);
        without_max.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "    █     ",
            "    █     ",
            "f b b     ",
        ]);
        assert_eq!(buffer, expected);
        let with_max = BarChart::default()
            .data(&[("foo", 1), ("bar", 2), ("baz", 100)])
            .max(2);
        with_max.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "  █ █     ",
            "1 2 █     ",
            "f b b     ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn bar_style() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default()
            .data(&[("foo", 1), ("bar", 2)])
            .bar_style(Style::new().red());
        widget.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let mut expected = Buffer::with_lines([
            "  █       ",
            "1 2       ",
            "f b       ",
        ]);
        for (x, y) in iproduct!([0, 2], [0, 1]) {
            expected[(x, y)].set_fg(Color::Red);
        }
        assert_eq!(buffer, expected);
    }

    #[test]
    fn bar_width() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default()
            .data(&[("foo", 1), ("bar", 2)])
            .bar_width(3);
        widget.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "    ███   ",
            "█1█ █2█   ",
            "foo bar   ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn bar_gap() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default()
            .data(&[("foo", 1), ("bar", 2)])
            .bar_gap(2);
        widget.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "   █      ",
            "1  2      ",
            "f  b      ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn bar_set() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default()
            .data(&[("foo", 0), ("bar", 1), ("baz", 3)])
            .bar_set(symbols::bar::THREE_LEVELS);
        widget.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "    █     ",
            "  ▄ 3     ",
            "f b b     ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn bar_set_nine_levels() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 18, 3));
        let widget = BarChart::default()
            .data(&[
                ("a", 0),
                ("b", 1),
                ("c", 2),
                ("d", 3),
                ("e", 4),
                ("f", 5),
                ("g", 6),
                ("h", 7),
                ("i", 8),
            ])
            .bar_set(symbols::bar::NINE_LEVELS);
        widget.render(Rect::new(0, 1, 18, 2), &mut buffer);
        let expected = Buffer::with_lines([
            "                  ",
            "  ▁ ▂ ▃ ▄ ▅ ▆ ▇ 8 ",
            "a b c d e f g h i ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn value_style() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default()
            .data(&[("foo", 1), ("bar", 2)])
            .bar_width(3)
            .value_style(Style::new().red());
        widget.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let mut expected = Buffer::with_lines([
            "    ███   ",
            "█1█ █2█   ",
            "foo bar   ",
        ]);
        expected[(1, 1)].set_fg(Color::Red);
        expected[(5, 1)].set_fg(Color::Red);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn label_style() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default()
            .data(&[("foo", 1), ("bar", 2)])
            .label_style(Style::new().red());
        widget.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let mut expected = Buffer::with_lines([
            "  █       ",
            "1 2       ",
            "f b       ",
        ]);
        expected[(0, 2)].set_fg(Color::Red);
        expected[(2, 2)].set_fg(Color::Red);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn style() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        let widget = BarChart::default()
            .data(&[("foo", 1), ("bar", 2)])
            .style(Style::new().red());
        widget.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let mut expected = Buffer::with_lines([
            "  █       ",
            "1 2       ",
            "f b       ",
        ]);
        for (x, y) in iproduct!(0..10, 0..3) {
            expected[(x, y)].set_fg(Color::Red);
        }
        assert_eq!(buffer, expected);
    }

    #[test]
    fn can_be_stylized() {
        assert_eq!(
            BarChart::default().black().on_white().bold().style,
            Style::default()
                .fg(Color::Black)
                .bg(Color::White)
                .add_modifier(Modifier::BOLD)
        );
    }

    #[test]
    fn test_empty_group() {
        let chart = BarChart::default()
            .data(BarGroup::default().label("invisible".into()))
            .data(
                BarGroup::default()
                    .label("G".into())
                    .bars(&[Bar::default().value(1), Bar::default().value(2)]),
            );

        let mut buffer = Buffer::empty(Rect::new(0, 0, 3, 3));
        chart.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "  █",
            "1 2",
            "G  ",
        ]);
        assert_eq!(buffer, expected);
    }

    fn build_test_barchart<'a>() -> BarChart<'a> {
        BarChart::default()
            .data(BarGroup::default().label("G1".into()).bars(&[
                Bar::default().value(2),
                Bar::default().value(3),
                Bar::default().value(4),
            ]))
            .data(BarGroup::default().label("G2".into()).bars(&[
                Bar::default().value(3),
                Bar::default().value(4),
                Bar::default().value(5),
            ]))
            .group_gap(1)
            .direction(Direction::Horizontal)
            .bar_gap(0)
    }

    #[test]
    fn test_horizontal_bars() {
        let chart: BarChart<'_> = build_test_barchart();

        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 8));
        chart.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "2█   ",
            "3██  ",
            "4███ ",
            "G1   ",
            "3██  ",
            "4███ ",
            "5████",
            "G2   ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn test_horizontal_bars_no_space_for_group_label() {
        let chart: BarChart<'_> = build_test_barchart();

        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 7));
        chart.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "2█   ",
            "3██  ",
            "4███ ",
            "G1   ",
            "3██  ",
            "4███ ",
            "5████",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn test_horizontal_bars_no_space_for_all_bars() {
        let chart: BarChart<'_> = build_test_barchart();

        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 5));
        chart.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "2█   ",
            "3██  ",
            "4███ ",
            "G1   ",
            "3██  ",
        ]);
        assert_eq!(buffer, expected);
    }

    fn test_horizontal_bars_label_width_greater_than_bar(bar_color: Option<Color>) {
        let mut bar = Bar::default()
            .value(2)
            .text_value("label".into())
            .value_style(Style::default().red());

        if let Some(color) = bar_color {
            bar = bar.style(Style::default().fg(color));
        }

        let chart: BarChart<'_> = BarChart::default()
            .data(BarGroup::default().bars(&[bar, Bar::default().value(5)]))
            .direction(Direction::Horizontal)
            .bar_style(Style::default().yellow())
            .value_style(Style::default().italic())
            .bar_gap(0);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
        chart.render(buffer.area, &mut buffer);

        let mut expected = Buffer::with_lines(["label", "5████"]);

        // first line has a yellow foreground. first cell contains italic "5"
        expected[(0, 1)].modifier.insert(Modifier::ITALIC);
        for x in 0..5 {
            expected[(x, 1)].set_fg(Color::Yellow);
        }

        let expected_color = bar_color.unwrap_or(Color::Yellow);

        // second line contains the word "label". Since the bar value is 2,
        // then the first 2 characters of "label" are italic red.
        // the rest is white (using the Bar's style).
        let cell = expected[(0, 0)].set_fg(Color::Red);
        cell.modifier.insert(Modifier::ITALIC);
        let cell = expected[(1, 0)].set_fg(Color::Red);
        cell.modifier.insert(Modifier::ITALIC);
        expected[(2, 0)].set_fg(expected_color);
        expected[(3, 0)].set_fg(expected_color);
        expected[(4, 0)].set_fg(expected_color);

        assert_eq!(buffer, expected);
    }

    #[test]
    fn test_horizontal_bars_label_width_greater_than_bar_without_style() {
        test_horizontal_bars_label_width_greater_than_bar(None);
    }

    #[test]
    fn test_horizontal_bars_label_width_greater_than_bar_with_style() {
        test_horizontal_bars_label_width_greater_than_bar(Some(Color::White));
    }

    /// Tests horizontal bars label are presents
    #[test]
    fn test_horizontal_label() {
        let chart = BarChart::default()
            .direction(Direction::Horizontal)
            .bar_gap(0)
            .data(&[("Jan", 10), ("Feb", 20), ("Mar", 5)]);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 3));
        chart.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "Jan 10█   ",
            "Feb 20████",
            "Mar 5     ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn test_group_label_style() {
        let chart: BarChart<'_> = BarChart::default()
            .data(
                BarGroup::default()
                    .label(Span::from("G1").red().into())
                    .bars(&[Bar::default().value(2)]),
            )
            .group_gap(1)
            .direction(Direction::Horizontal)
            .label_style(Style::default().bold().yellow());

        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
        chart.render(buffer.area, &mut buffer);

        // G1 should have the bold red style
        // bold: because of BarChart::label_style
        // red: is included with the label itself
        let mut expected = Buffer::with_lines(["2████", "G1   "]);
        let cell = expected[(0, 1)].set_fg(Color::Red);
        cell.modifier.insert(Modifier::BOLD);
        let cell = expected[(1, 1)].set_fg(Color::Red);
        cell.modifier.insert(Modifier::BOLD);

        assert_eq!(buffer, expected);
    }

    #[test]
    fn test_group_label_center() {
        // test the centered group position when one bar is outside the group
        let group = BarGroup::from(&[("a", 1), ("b", 2), ("c", 3), ("c", 4)]);
        let chart = BarChart::default()
            .data(
                group
                    .clone()
                    .label(Line::from("G1").alignment(Alignment::Center)),
            )
            .data(group.label(Line::from("G2").alignment(Alignment::Center)));

        let mut buffer = Buffer::empty(Rect::new(0, 0, 13, 5));
        chart.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "    ▂ █     ▂",
            "  ▄ █ █   ▄ █",
            "▆ 2 3 4 ▆ 2 3",
            "a b c c a b c",
            "  G1     G2  ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn test_group_label_right() {
        let chart: BarChart<'_> = BarChart::default().data(
            BarGroup::default()
                .label(Line::from(Span::from("G")).alignment(Alignment::Right))
                .bars(&[Bar::default().value(2), Bar::default().value(5)]),
        );

        let mut buffer = Buffer::empty(Rect::new(0, 0, 3, 3));
        chart.render(buffer.area, &mut buffer);
        #[rustfmt::skip]
        let expected = Buffer::with_lines([
            "  █",
            "▆ 5",
            "  G",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn test_unicode_as_value() {
        let group = BarGroup::default().bars(&[
            Bar::default()
                .value(123)
                .label("B1".into())
                .text_value("写".into()),
            Bar::default()
                .value(321)
                .label("B2".into())
                .text_value("写".into()),
            Bar::default()
                .value(333)
                .label("B2".into())
                .text_value("写".into()),
        ]);
        let chart = BarChart::default().data(group).bar_width(3).bar_gap(1);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 11, 5));
        chart.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "    ▆▆▆ ███",
            "    ███ ███",
            "▃▃▃ ███ ███",
            "写█ 写█ 写█",
            "B1  B2  B2 ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn handles_zero_width() {
        // this test is to ensure that a BarChart with zero bar / gap width does not panic
        let chart = BarChart::default()
            .data(&[("A", 1)])
            .bar_width(0)
            .bar_gap(0);
        let mut buffer = Buffer::empty(Rect::new(0, 0, 0, 10));
        chart.render(buffer.area, &mut buffer);
        assert_eq!(buffer, Buffer::empty(Rect::new(0, 0, 0, 10)));
    }

    #[test]
    fn single_line() {
        let mut group: BarGroup = (&[
            ("a", 0),
            ("b", 1),
            ("c", 2),
            ("d", 3),
            ("e", 4),
            ("f", 5),
            ("g", 6),
            ("h", 7),
            ("i", 8),
        ])
            .into();
        group = group.label("Group".into());

        let chart = BarChart::default()
            .data(group)
            .bar_set(symbols::bar::NINE_LEVELS);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 17, 1));
        chart.render(buffer.area, &mut buffer);
        assert_eq!(buffer, Buffer::with_lines(["  ▁ ▂ ▃ ▄ ▅ ▆ ▇ 8"]));
    }

    #[test]
    fn two_lines() {
        let mut group: BarGroup = (&[
            ("a", 0),
            ("b", 1),
            ("c", 2),
            ("d", 3),
            ("e", 4),
            ("f", 5),
            ("g", 6),
            ("h", 7),
            ("i", 8),
        ])
            .into();
        group = group.label("Group".into());

        let chart = BarChart::default()
            .data(group)
            .bar_set(symbols::bar::NINE_LEVELS);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 17, 3));
        chart.render(Rect::new(0, 1, buffer.area.width, 2), &mut buffer);
        let expected = Buffer::with_lines([
            "                 ",
            "  ▁ ▂ ▃ ▄ ▅ ▆ ▇ 8",
            "a b c d e f g h i",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn three_lines() {
        let mut group: BarGroup = (&[
            ("a", 0),
            ("b", 1),
            ("c", 2),
            ("d", 3),
            ("e", 4),
            ("f", 5),
            ("g", 6),
            ("h", 7),
            ("i", 8),
        ])
            .into();
        group = group.label(Line::from("Group").alignment(Alignment::Center));

        let chart = BarChart::default()
            .data(group)
            .bar_set(symbols::bar::NINE_LEVELS);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 17, 3));
        chart.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "  ▁ ▂ ▃ ▄ ▅ ▆ ▇ 8",
            "a b c d e f g h i",
            "      Group      ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn three_lines_double_width() {
        let mut group = BarGroup::from(&[
            ("a", 0),
            ("b", 1),
            ("c", 2),
            ("d", 3),
            ("e", 4),
            ("f", 5),
            ("g", 6),
            ("h", 7),
            ("i", 8),
        ]);
        group = group.label(Line::from("Group").alignment(Alignment::Center));

        let chart = BarChart::default()
            .data(group)
            .bar_width(2)
            .bar_set(symbols::bar::NINE_LEVELS);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 26, 3));
        chart.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "   1▁ 2▂ 3▃ 4▄ 5▅ 6▆ 7▇ 8█",
            "a  b  c  d  e  f  g  h  i ",
            "          Group           ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn four_lines() {
        let mut group: BarGroup = (&[
            ("a", 0),
            ("b", 1),
            ("c", 2),
            ("d", 3),
            ("e", 4),
            ("f", 5),
            ("g", 6),
            ("h", 7),
            ("i", 8),
        ])
            .into();
        group = group.label(Line::from("Group").alignment(Alignment::Center));

        let chart = BarChart::default()
            .data(group)
            .bar_set(symbols::bar::NINE_LEVELS);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 17, 4));
        chart.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "          ▂ ▄ ▆ █",
            "  ▂ ▄ ▆ 4 5 6 7 8",
            "a b c d e f g h i",
            "      Group      ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn two_lines_without_bar_labels() {
        let group = BarGroup::default()
            .label(Line::from("Group").alignment(Alignment::Center))
            .bars(&[
                Bar::default().value(0),
                Bar::default().value(1),
                Bar::default().value(2),
                Bar::default().value(3),
                Bar::default().value(4),
                Bar::default().value(5),
                Bar::default().value(6),
                Bar::default().value(7),
                Bar::default().value(8),
            ]);

        let chart = BarChart::default().data(group);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 17, 3));
        chart.render(Rect::new(0, 1, buffer.area.width, 2), &mut buffer);
        let expected = Buffer::with_lines([
            "                 ",
            "  ▁ ▂ ▃ ▄ ▅ ▆ ▇ 8",
            "      Group      ",
        ]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn one_lines_with_more_bars() {
        let bars: Vec<Bar> = (0..30).map(|i| Bar::default().value(i)).collect();

        let chart = BarChart::default().data(BarGroup::default().bars(&bars));

        let mut buffer = Buffer::empty(Rect::new(0, 0, 59, 1));
        chart.render(buffer.area, &mut buffer);
        let expected =
            Buffer::with_lines(["        ▁ ▁ ▁ ▁ ▂ ▂ ▂ ▃ ▃ ▃ ▃ ▄ ▄ ▄ ▄ ▅ ▅ ▅ ▆ ▆ ▆ ▆ ▇ ▇ ▇ █"]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn first_bar_of_the_group_is_half_outside_view() {
        let chart = BarChart::default()
            .data(&[("a", 1), ("b", 2)])
            .data(&[("a", 1), ("b", 2)])
            .bar_width(2);

        let mut buffer = Buffer::empty(Rect::new(0, 0, 7, 6));
        chart.render(buffer.area, &mut buffer);
        let expected = Buffer::with_lines([
            "   ██  ",
            "   ██  ",
            "▄▄ ██  ",
            "██ ██  ",
            "1█ 2█  ",
            "a  b   ",
        ]);
        assert_eq!(buffer, expected);
    }
}