| 1 | pub mod column; |
| 2 | pub mod data_type; |
| 3 | pub mod draw; |
| 4 | pub mod props; |
| 5 | pub mod sortable; |
| 6 | pub mod state; |
| 7 | pub mod styling; |
| 8 | |
| 9 | use std::{convert::TryInto, marker::PhantomData}; |
| 10 | |
| 11 | pub use column::*; |
| 12 | pub use data_type::*; |
| 13 | pub use draw::*; |
| 14 | pub use props::DataTableProps; |
| 15 | pub use sortable::*; |
| 16 | pub use state::{DataTableState, ScrollDirection}; |
| 17 | pub use styling::*; |
| 18 | |
| 19 | use crate::utils::general::ClampExt; |
| 20 | |
| 21 | /// A [`DataTable`] is a component that displays data in a tabular form. |
| 22 | /// |
| 23 | /// Note that [`DataTable`] takes a generic type `S`, bounded by [`SortType`]. |
| 24 | /// This controls whether this table expects sorted data or not, with two |
| 25 | /// expected types: |
| 26 | /// |
| 27 | /// - [`Unsortable`]: The default if otherwise not specified. This table does |
| 28 | /// not expect sorted data. |
| 29 | /// - [`Sortable`]: This table expects sorted data, and there are helper |
| 30 | /// functions to facilitate things like sorting based on a selected column, |
| 31 | /// shortcut column selection support, mouse column selection support, etc. |
| 32 | /// |
| 33 | /// FIXME: We already do all the text width checks - can we skip the underlying |
| 34 | /// ones? |
| 35 | pub struct DataTable<DataType, Header, S = Unsortable, C = Column<Header>> { |
| 36 | pub columns: Vec<C>, |
| 37 | pub state: DataTableState, |
| 38 | pub props: DataTableProps, |
| 39 | pub styling: DataTableStyling, |
| 40 | data: Vec<DataType>, |
| 41 | sort_type: S, |
| 42 | first_draw: bool, |
| 43 | first_index: Option<usize>, |
| 44 | _pd: PhantomData<(DataType, S, Header)>, |
| 45 | } |
| 46 | |
| 47 | impl<DataType: DataToCell<H>, H: ColumnHeader> DataTable<DataType, H, Unsortable, Column<H>> { |
| 48 | pub fn new<C: Into<Vec<Column<H>>>>( |
| 49 | columns: C, props: DataTableProps, styling: DataTableStyling, |
| 50 | ) -> Self { |
| 51 | Self { |
| 52 | columns: columns.into(), |
| 53 | state: DataTableState::default(), |
| 54 | props, |
| 55 | styling, |
| 56 | data: vec![], |
| 57 | sort_type: Unsortable, |
| 58 | first_draw: true, |
| 59 | first_index: None, |
| 60 | _pd: PhantomData, |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | impl<DataType: DataToCell<H>, H: ColumnHeader, S: SortType, C: DataTableColumn<H>> |
| 66 | DataTable<DataType, H, S, C> |
| 67 | { |
| 68 | /// Sets the default value selected on first initialization, if possible. |
| 69 | pub fn first_draw_index(mut self, first_index: usize) -> Self { |
| 70 | self.first_index = Some(first_index); |
| 71 | self |
| 72 | } |
| 73 | |
| 74 | /// Sets the scroll position to the first value. |
| 75 | pub fn scroll_to_first(&mut self) { |
| 76 | self.state.current_index = 0; |
| 77 | self.state.scroll_direction = ScrollDirection::Up; |
| 78 | } |
| 79 | |
| 80 | /// Sets the scroll position to the last value. |
| 81 | pub fn scroll_to_last(&mut self) { |
| 82 | self.state.current_index = self.data.len().saturating_sub(1); |
| 83 | self.state.scroll_direction = ScrollDirection::Down; |
| 84 | } |
| 85 | |
| 86 | /// Updates the scroll position to be valid for the number of entries. |
| 87 | pub fn set_data(&mut self, data: Vec<DataType>) { |
| 88 | self.data = data; |
| 89 | let max_pos = self.data.len().saturating_sub(1); |
| 90 | if self.state.current_index > max_pos { |
| 91 | self.state.current_index = max_pos; |
| 92 | self.state.display_start_index = 0; |
| 93 | self.state.scroll_direction = ScrollDirection::Down; |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /// Increments the scroll position if possible by a positive/negative |
| 98 | /// offset. If there is a valid change, this function will also return |
| 99 | /// the new position wrapped in an [`Option`]. |
| 100 | /// |
| 101 | /// Note that despite the name, this handles both incrementing (positive |
| 102 | /// change) and decrementing (negative change). |
| 103 | pub fn increment_position(&mut self, change: i64) -> Option<usize> { |
| 104 | let num_entries = self.data.len(); |
| 105 | |
| 106 | if num_entries == 0 { |
| 107 | return None; |
| 108 | } |
| 109 | |
| 110 | let Ok(current_index): Result<i64, _> = self.state.current_index.try_into() else { |
| 111 | return None; |
| 112 | }; |
| 113 | |
| 114 | // We do this to clamp the proposed index to 0 if the change is greater |
| 115 | // than the number of entries left from the current index. This gives |
| 116 | // a more intuitive behaviour when using things like page up/down. |
| 117 | let proposed = current_index + change; |
| 118 | |
| 119 | // We check num_entries > 0 above. |
| 120 | self.state.current_index = proposed.clamp(0, (num_entries - 1) as i64) as usize; |
| 121 | |
| 122 | self.state.scroll_direction = if change < 0 { |
| 123 | ScrollDirection::Up |
| 124 | } else { |
| 125 | ScrollDirection::Down |
| 126 | }; |
| 127 | |
| 128 | Some(self.state.current_index) |
| 129 | } |
| 130 | |
| 131 | /// Updates the scroll position to a selected index. |
| 132 | pub fn set_position(&mut self, new_index: usize) { |
| 133 | let new_index = new_index.clamp_upper(self.data.len().saturating_sub(1)); |
| 134 | if self.state.current_index < new_index { |
| 135 | self.state.scroll_direction = ScrollDirection::Down; |
| 136 | } else if self.state.current_index > new_index { |
| 137 | self.state.scroll_direction = ScrollDirection::Up; |
| 138 | } |
| 139 | self.state.current_index = new_index; |
| 140 | } |
| 141 | |
| 142 | /// Returns the current scroll index. |
| 143 | pub fn current_index(&self) -> usize { |
| 144 | self.state.current_index |
| 145 | } |
| 146 | |
| 147 | /// Optionally returns the currently selected item, if there is one. |
| 148 | pub fn current_item(&self) -> Option<&DataType> { |
| 149 | self.data.get(self.state.current_index) |
| 150 | } |
| 151 | |
| 152 | /// Returns ratatui's internal selection. |
| 153 | pub fn ratatui_selected(&self) -> Option<usize> { |
| 154 | self.state.table_state.selected() |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | #[cfg(test)] |
| 159 | mod test { |
| 160 | use std::{borrow::Cow, num::NonZeroU16}; |
| 161 | |
| 162 | use super::*; |
| 163 | use crate::options::config::flags::TableGap; |
| 164 | |
| 165 | #[derive(Clone, PartialEq, Eq, Debug)] |
| 166 | struct TestType { |
| 167 | index: usize, |
| 168 | } |
| 169 | |
| 170 | impl DataToCell<&'static str> for TestType { |
| 171 | fn to_cell_text( |
| 172 | &self, _column: &&'static str, _calculated_width: NonZeroU16, |
| 173 | ) -> Option<Cow<'static, str>> { |
| 174 | None |
| 175 | } |
| 176 | |
| 177 | fn column_widths<C: DataTableColumn<&'static str>>( |
| 178 | _data: &[Self], _columns: &[C], |
| 179 | ) -> Vec<u16> |
| 180 | where |
| 181 | Self: Sized, |
| 182 | { |
| 183 | vec![] |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | fn create_test_table() -> DataTable<TestType, &'static str> { |
| 188 | let columns = [Column::hard("a", 10), Column::hard("b", 10)]; |
| 189 | let props = DataTableProps { |
| 190 | title: Some("test".into()), |
| 191 | table_gap: TableGap::Space, |
| 192 | left_to_right: false, |
| 193 | is_basic: false, |
| 194 | show_table_scroll_position: true, |
| 195 | show_table_scroll_bar: false, |
| 196 | show_current_entry_when_unfocused: false, |
| 197 | }; |
| 198 | let styling = DataTableStyling::default(); |
| 199 | |
| 200 | DataTable::new(columns, props, styling) |
| 201 | } |
| 202 | |
| 203 | #[test] |
| 204 | fn test_scrolling() { |
| 205 | let mut table = create_test_table(); |
| 206 | table.set_data((0..=4).map(|index| TestType { index }).collect::<Vec<_>>()); |
| 207 | |
| 208 | table.scroll_to_last(); |
| 209 | assert_eq!(table.current_index(), 4); |
| 210 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 211 | |
| 212 | table.scroll_to_first(); |
| 213 | assert_eq!(table.current_index(), 0); |
| 214 | assert_eq!(table.state.scroll_direction, ScrollDirection::Up); |
| 215 | } |
| 216 | |
| 217 | #[test] |
| 218 | fn test_set_position() { |
| 219 | let mut table = create_test_table(); |
| 220 | table.set_data((0..=4).map(|index| TestType { index }).collect::<Vec<_>>()); |
| 221 | |
| 222 | table.set_position(4); |
| 223 | assert_eq!(table.current_index(), 4); |
| 224 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 225 | |
| 226 | table.set_position(100); |
| 227 | assert_eq!(table.current_index(), 4); |
| 228 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 229 | assert_eq!(table.current_item(), Some(&TestType { index: 4 })); |
| 230 | } |
| 231 | |
| 232 | #[test] |
| 233 | fn test_increment_position() { |
| 234 | let mut table = create_test_table(); |
| 235 | table.set_data((0..=4).map(|index| TestType { index }).collect::<Vec<_>>()); |
| 236 | |
| 237 | table.set_position(4); |
| 238 | assert_eq!(table.current_index(), 4); |
| 239 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 240 | |
| 241 | table.increment_position(-1); |
| 242 | assert_eq!(table.current_index(), 3); |
| 243 | assert_eq!(table.state.scroll_direction, ScrollDirection::Up); |
| 244 | assert_eq!(table.current_item(), Some(&TestType { index: 3 })); |
| 245 | |
| 246 | table.increment_position(-3); |
| 247 | assert_eq!(table.current_index(), 0); |
| 248 | assert_eq!(table.state.scroll_direction, ScrollDirection::Up); |
| 249 | assert_eq!(table.current_item(), Some(&TestType { index: 0 })); |
| 250 | |
| 251 | table.increment_position(-3); |
| 252 | assert_eq!(table.current_index(), 0); |
| 253 | assert_eq!(table.state.scroll_direction, ScrollDirection::Up); |
| 254 | assert_eq!(table.current_item(), Some(&TestType { index: 0 })); |
| 255 | |
| 256 | table.increment_position(1); |
| 257 | assert_eq!(table.current_index(), 1); |
| 258 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 259 | assert_eq!(table.current_item(), Some(&TestType { index: 1 })); |
| 260 | |
| 261 | table.increment_position(3); |
| 262 | assert_eq!(table.current_index(), 4); |
| 263 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 264 | assert_eq!(table.current_item(), Some(&TestType { index: 4 })); |
| 265 | |
| 266 | table.increment_position(10); |
| 267 | assert_eq!(table.current_index(), 4); |
| 268 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 269 | assert_eq!(table.current_item(), Some(&TestType { index: 4 })); |
| 270 | |
| 271 | // Make sure that overscrolling up causes clamping. |
| 272 | table.increment_position(-10); |
| 273 | assert_eq!(table.current_index(), 0); |
| 274 | assert_eq!(table.state.scroll_direction, ScrollDirection::Up); |
| 275 | assert_eq!(table.current_item(), Some(&TestType { index: 0 })); |
| 276 | |
| 277 | // Make sure that overscrolling down causes clamping. |
| 278 | table.increment_position(100); |
| 279 | assert_eq!(table.current_index(), 4); |
| 280 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 281 | assert_eq!(table.current_item(), Some(&TestType { index: 4 })); |
| 282 | } |
| 283 | |
| 284 | /// A test to ensure that scroll offsets are correctly handled when we |
| 285 | /// "lose" rows. |
| 286 | #[test] |
| 287 | fn test_lose_data() { |
| 288 | let mut table = create_test_table(); |
| 289 | table.set_data((0..=4).map(|index| TestType { index }).collect::<Vec<_>>()); |
| 290 | |
| 291 | table.set_position(4); |
| 292 | assert_eq!(table.current_index(), 4); |
| 293 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 294 | assert_eq!(table.current_item(), Some(&TestType { index: 4 })); |
| 295 | |
| 296 | table.set_data((0..=2).map(|index| TestType { index }).collect::<Vec<_>>()); |
| 297 | assert_eq!(table.current_index(), 2); |
| 298 | assert_eq!(table.state.scroll_direction, ScrollDirection::Down); |
| 299 | assert_eq!(table.current_item(), Some(&TestType { index: 2 })); |
| 300 | } |
| 301 | } |