ratatui_widgets/table/
highlight_spacing.rs

1use strum::{Display, EnumString};
2
3/// This option allows the user to configure the "highlight symbol" column width spacing
4#[derive(Debug, Display, EnumString, PartialEq, Eq, Clone, Default, Hash)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub enum HighlightSpacing {
7    /// Always add spacing for the selection symbol column
8    ///
9    /// With this variant, the column for the selection symbol will always be allocated, and so the
10    /// table will never change size, regardless of if a row is selected or not
11    Always,
12
13    /// Only add spacing for the selection symbol column if a row is selected
14    ///
15    /// With this variant, the column for the selection symbol will only be allocated if there is a
16    /// selection, causing the table to shift if selected / unselected
17    #[default]
18    WhenSelected,
19
20    /// Never add spacing to the selection symbol column, regardless of whether something is
21    /// selected or not
22    ///
23    /// This means that the highlight symbol will never be drawn
24    Never,
25}
26
27impl HighlightSpacing {
28    /// Determine if a selection column should be displayed
29    ///
30    /// `has_selection`: true if a row is selected in the table
31    ///
32    /// Returns true if a selection column should be displayed
33    pub(crate) const fn should_add(&self, has_selection: bool) -> bool {
34        match self {
35            Self::Always => true,
36            Self::WhenSelected => has_selection,
37            Self::Never => false,
38        }
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use alloc::string::ToString;
45
46    use super::*;
47
48    #[test]
49    fn to_string() {
50        assert_eq!(HighlightSpacing::Always.to_string(), "Always".to_string());
51        assert_eq!(
52            HighlightSpacing::WhenSelected.to_string(),
53            "WhenSelected".to_string()
54        );
55        assert_eq!(HighlightSpacing::Never.to_string(), "Never".to_string());
56    }
57
58    #[test]
59    fn from_str() {
60        assert_eq!(
61            "Always".parse::<HighlightSpacing>(),
62            Ok(HighlightSpacing::Always)
63        );
64        assert_eq!(
65            "WhenSelected".parse::<HighlightSpacing>(),
66            Ok(HighlightSpacing::WhenSelected)
67        );
68        assert_eq!(
69            "Never".parse::<HighlightSpacing>(),
70            Ok(HighlightSpacing::Never)
71        );
72        assert_eq!(
73            "".parse::<HighlightSpacing>(),
74            Err(strum::ParseError::VariantNotFound)
75        );
76    }
77}