Skip to main content

ratatui_table/table/
highlight_placement.rs

1use alloc::vec::Vec;
2
3use strum::{Display, EnumString};
4
5/// Where the highlight symbol gets space, i.e. *which* columns are indented to make room for it.
6///
7/// [`HighlightSpacing`] decides *when* the symbol column is allocated; this decides *where*.
8///
9/// [`HighlightSpacing`]: super::HighlightSpacing
10///
11/// # How the layout moves
12///
13/// Every column that gets a slot is pushed right by the symbol width, and the remaining width is
14/// split between the columns. With a 2-cell symbol `>>` and three columns:
15///
16/// ```text
17/// FirstColumn      >>Alice   Engineer  Berlin
18/// SelectedColumn     Alice >>Engineer  Berlin      (column 1 selected)
19/// SelectedColumn     Alice   Engineer>>Berlin      (column 2 selected)
20/// AllColumns       >>Alice >>Engineer>>Berlin
21/// ```
22///
23/// Note the consequence of [`SelectedColumn`]: moving the selection from one column to the next
24/// moves the slot with it, so text to the left of the new slot shifts left and text to its right
25/// shifts right. Use [`FirstColumn`] (the default) or [`AllColumns`] if you need the columns to
26/// stay put as the selection moves.
27///
28/// [`SelectedColumn`]: HighlightPlacement::SelectedColumn
29/// [`FirstColumn`]: HighlightPlacement::FirstColumn
30/// [`AllColumns`]: HighlightPlacement::AllColumns
31#[derive(Debug, Display, EnumString, PartialEq, Eq, Clone, Default, Hash)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33pub enum HighlightPlacement {
34    /// Only the first column gets a slot.
35    ///
36    /// This is the default, and reproduces the behavior of a table without column selection: the
37    /// symbol sits at the left edge of the row and the layout never moves.
38    #[default]
39    FirstColumn,
40
41    /// Only the selected column gets a slot.
42    ///
43    /// The slot follows the selection, so the columns shift as the selected column changes. With
44    /// no column selected, falls back to the first column.
45    SelectedColumn,
46
47    /// Each listed column gets a slot.
48    ///
49    /// Indices at or beyond the column count are ignored. Parsing this variant from a string
50    /// yields an empty list, i.e. no slots.
51    Columns(Vec<usize>),
52
53    /// Every column gets a slot.
54    AllColumns,
55}
56
57impl HighlightPlacement {
58    /// Returns a `column_count`-long mask: `mask[i]` is true when column `i` gets a symbol slot.
59    ///
60    /// A mask rather than a list of indices because the render path asks "does column `i` have a
61    /// slot" once per column; a `contains()` lookup inside that loop would be quadratic.
62    pub(crate) fn column_mask(
63        &self,
64        selected_column: Option<usize>,
65        column_count: usize,
66    ) -> Vec<bool> {
67        let mut mask = alloc::vec![false; column_count];
68        match self {
69            Self::AllColumns => mask.fill(true),
70            Self::FirstColumn => {
71                if let Some(first) = mask.first_mut() {
72                    *first = true;
73                }
74            }
75            Self::SelectedColumn => {
76                // No column selected: behave like `FirstColumn` rather than showing no symbol.
77                if let Some(slot) = mask.get_mut(selected_column.unwrap_or(0)) {
78                    *slot = true;
79                }
80            }
81            Self::Columns(indices) => {
82                for &index in indices {
83                    if let Some(slot) = mask.get_mut(index) {
84                        *slot = true;
85                    }
86                }
87            }
88        }
89        mask
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use alloc::string::ToString;
96    use alloc::vec;
97
98    use super::*;
99
100    #[test]
101    fn to_string() {
102        assert_eq!(
103            HighlightPlacement::FirstColumn.to_string(),
104            "FirstColumn".to_string()
105        );
106        assert_eq!(
107            HighlightPlacement::SelectedColumn.to_string(),
108            "SelectedColumn".to_string()
109        );
110        assert_eq!(
111            HighlightPlacement::Columns(vec![1]).to_string(),
112            "Columns".to_string()
113        );
114        assert_eq!(
115            HighlightPlacement::AllColumns.to_string(),
116            "AllColumns".to_string()
117        );
118    }
119
120    #[test]
121    fn from_str() {
122        assert_eq!(
123            "FirstColumn".parse::<HighlightPlacement>(),
124            Ok(HighlightPlacement::FirstColumn)
125        );
126        assert_eq!(
127            "SelectedColumn".parse::<HighlightPlacement>(),
128            Ok(HighlightPlacement::SelectedColumn)
129        );
130        assert_eq!(
131            "Columns".parse::<HighlightPlacement>(),
132            Ok(HighlightPlacement::Columns(Vec::new()))
133        );
134        assert_eq!(
135            "AllColumns".parse::<HighlightPlacement>(),
136            Ok(HighlightPlacement::AllColumns)
137        );
138        assert_eq!(
139            "".parse::<HighlightPlacement>(),
140            Err(strum::ParseError::VariantNotFound)
141        );
142    }
143
144    #[test]
145    fn mask_first_column() {
146        let mask = HighlightPlacement::FirstColumn.column_mask(Some(2), 3);
147        assert_eq!(mask, vec![true, false, false]);
148    }
149
150    #[test]
151    fn mask_selected_column() {
152        let mask = HighlightPlacement::SelectedColumn.column_mask(Some(2), 3);
153        assert_eq!(mask, vec![false, false, true]);
154    }
155
156    #[test]
157    fn mask_selected_column_without_selection() {
158        let mask = HighlightPlacement::SelectedColumn.column_mask(None, 3);
159        assert_eq!(mask, vec![true, false, false]);
160    }
161
162    #[test]
163    fn mask_columns_ignores_out_of_range() {
164        let mask = HighlightPlacement::Columns(vec![1, 9]).column_mask(None, 3);
165        assert_eq!(mask, vec![false, true, false]);
166    }
167
168    #[test]
169    fn mask_all_columns() {
170        let mask = HighlightPlacement::AllColumns.column_mask(None, 3);
171        assert_eq!(mask, vec![true, true, true]);
172    }
173
174    #[test]
175    fn mask_zero_columns() {
176        assert_eq!(
177            HighlightPlacement::AllColumns.column_mask(Some(0), 0),
178            Vec::<bool>::new()
179        );
180        assert_eq!(
181            HighlightPlacement::FirstColumn.column_mask(None, 0),
182            Vec::<bool>::new()
183        );
184    }
185}