tui_widget_list/view.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
use ratatui::{
buffer::Buffer,
layout::{Position, Rect},
style::{Style, Styled},
widgets::{block::BlockExt, Block, StatefulWidget, Widget},
};
use crate::{utils::layout_on_viewport, ListState};
/// A struct representing a list view.
/// The widget displays a scrollable list of items.
#[allow(clippy::module_name_repetitions)]
pub struct ListView<'a, T> {
/// The total number of items in the list
pub item_count: usize,
/// A `ListBuilder<T>` responsible for constructing the items in the list.
pub builder: ListBuilder<'a, T>,
/// Specifies the scroll axis. Either `Vertical` or `Horizontal`.
pub scroll_axis: ScrollAxis,
/// The base style of the list view.
pub style: Style,
/// The base block surrounding the widget list.
pub block: Option<Block<'a>>,
/// The scroll padding.
pub(crate) scroll_padding: u16,
/// Whether infinite scrolling is enabled or not.
/// Disabled by default.
pub(crate) infinite_scrolling: bool,
}
impl<'a, T> ListView<'a, T> {
/// Creates a new `ListView` with a builder an item count.
#[must_use]
pub fn new(builder: ListBuilder<'a, T>, item_count: usize) -> Self {
Self {
builder,
item_count,
scroll_axis: ScrollAxis::Vertical,
style: Style::default(),
block: None,
scroll_padding: 0,
infinite_scrolling: true,
}
}
/// Checks whether the widget list is empty.
#[must_use]
pub fn is_empty(&self) -> bool {
self.item_count == 0
}
/// Returns the length of the widget list.
#[must_use]
pub fn len(&self) -> usize {
self.item_count
}
/// Sets the block style that surrounds the whole List.
#[must_use]
pub fn block(mut self, block: Block<'a>) -> Self {
self.block = Some(block);
self
}
/// Set the base style of the List.
#[must_use]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
self
}
/// Set the scroll axis of the list.
#[must_use]
pub fn scroll_axis(mut self, scroll_axis: ScrollAxis) -> Self {
self.scroll_axis = scroll_axis;
self
}
/// Set the scroll padding of the list.
#[must_use]
pub fn scroll_padding(mut self, scroll_padding: u16) -> Self {
self.scroll_padding = scroll_padding;
self
}
/// Specify whether infinite scrolling should be enabled or not.
#[must_use]
pub fn infinite_scrolling(mut self, infinite_scrolling: bool) -> Self {
self.infinite_scrolling = infinite_scrolling;
self
}
}
impl<T> Styled for ListView<'_, T> {
type Item = Self;
fn style(&self) -> Style {
self.style
}
fn set_style<S: Into<Style>>(mut self, style: S) -> Self::Item {
self.style = style.into();
self
}
}
impl<'a, T: Copy + 'a> From<Vec<T>> for ListView<'a, T> {
fn from(value: Vec<T>) -> Self {
let item_count = value.len();
let builder = ListBuilder::new(move |context| (value[context.index], 1));
ListView::new(builder, item_count)
}
}
/// This structure holds information about the item's position, selection
/// status, scrolling behavior, and size along the cross axis.
pub struct ListBuildContext {
/// The position of the item in the list.
pub index: usize,
/// A boolean flag indicating whether the item is currently selected.
pub is_selected: bool,
/// Defines the axis along which the list can be scrolled.
pub scroll_axis: ScrollAxis,
/// The size of the item along the cross axis.
pub cross_axis_size: u16,
}
/// A type alias for the closure.
type ListBuilderClosure<'a, T> = dyn Fn(&ListBuildContext) -> (T, u16) + 'a;
/// The builder for constructing list elements in a `ListView<T>`
pub struct ListBuilder<'a, T> {
closure: Box<ListBuilderClosure<'a, T>>,
}
impl<'a, T> ListBuilder<'a, T> {
/// Creates a new `ListBuilder` taking a closure as a parameter
///
/// # Example
/// ```
/// use ratatui::text::Line;
/// use tui_widget_list::ListBuilder;
///
/// let builder = ListBuilder::new(|context| {
/// let mut item = Line::from(format!("Item {:0}", context.index));
///
/// // Return the size of the widget along the main axis.
/// let main_axis_size = 1;
///
/// (item, main_axis_size)
/// });
/// ```
pub fn new<F>(closure: F) -> Self
where
F: Fn(&ListBuildContext) -> (T, u16) + 'a,
{
ListBuilder {
closure: Box::new(closure),
}
}
/// Method to call the stored closure.
pub(crate) fn call_closure(&self, context: &ListBuildContext) -> (T, u16) {
(self.closure)(context)
}
}
/// Represents the scroll axis of a list.
#[derive(Debug, Default, Clone, Copy)]
pub enum ScrollAxis {
/// Indicates vertical scrolling. This is the default.
#[default]
Vertical,
/// Indicates horizontal scrolling.
Horizontal,
}
impl<T: Widget> StatefulWidget for ListView<'_, T> {
type State = ListState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
state.set_num_elements(self.item_count);
state.set_infinite_scrolling(self.infinite_scrolling);
// Set the base style
buf.set_style(area, self.style);
// Set the base block
self.block.render(area, buf);
let area = self.block.inner_if_some(area);
// List is empty
if self.item_count == 0 {
return;
}
// Set the dimension along the scroll axis and the cross axis
let (main_axis_size, cross_axis_size) = match self.scroll_axis {
ScrollAxis::Vertical => (area.height, area.width),
ScrollAxis::Horizontal => (area.width, area.height),
};
// The coordinates of the first item with respect to the top left corner
let (mut scroll_axis_pos, cross_axis_pos) = match self.scroll_axis {
ScrollAxis::Vertical => (area.top(), area.left()),
ScrollAxis::Horizontal => (area.left(), area.top()),
};
// Determine which widgets to show on the viewport and how much space they
// get assigned to.
let mut viewport = layout_on_viewport(
state,
&self.builder,
self.item_count,
main_axis_size,
cross_axis_size,
self.scroll_axis,
self.scroll_padding,
);
let (start, end) = (
state.view_state.offset,
viewport.len() + state.view_state.offset,
);
for i in start..end {
let Some(element) = viewport.remove(&i) else {
break;
};
let visible_main_axis_size = element
.main_axis_size
.saturating_sub(element.truncation.value());
let area = match self.scroll_axis {
ScrollAxis::Vertical => Rect::new(
cross_axis_pos,
scroll_axis_pos,
cross_axis_size,
visible_main_axis_size,
),
ScrollAxis::Horizontal => Rect::new(
scroll_axis_pos,
cross_axis_pos,
visible_main_axis_size,
cross_axis_size,
),
};
// Render truncated widgets.
if element.truncation.value() > 0 {
render_truncated(
element.widget,
area,
buf,
element.main_axis_size,
&element.truncation,
self.style,
self.scroll_axis,
);
} else {
element.widget.render(area, buf);
}
scroll_axis_pos += visible_main_axis_size;
}
}
}
/// Render a truncated widget into a buffer. The method renders the widget fully into
/// a hidden buffer and moves the visible content into `buf`.
fn render_truncated<T: Widget>(
item: T,
available_area: Rect,
buf: &mut Buffer,
untruncated_size: u16,
truncation: &Truncation,
base_style: Style,
scroll_axis: ScrollAxis,
) {
// Create an hidden buffer for rendering the truncated element
let (width, height) = match scroll_axis {
ScrollAxis::Vertical => (available_area.width, untruncated_size),
ScrollAxis::Horizontal => (untruncated_size, available_area.height),
};
let mut hidden_buffer = Buffer::empty(Rect {
x: available_area.left(),
y: available_area.top(),
width,
height,
});
hidden_buffer.set_style(hidden_buffer.area, base_style);
item.render(hidden_buffer.area, &mut hidden_buffer);
// Copy the visible part from the hidden buffer to the main buffer
match scroll_axis {
ScrollAxis::Vertical => {
let offset = match truncation {
Truncation::Top(value) => *value,
_ => 0,
};
for y in available_area.top()..available_area.bottom() {
let y_off = y + offset;
for x in available_area.left()..available_area.right() {
if let Some(to) = buf.cell_mut(Position::new(x, y)) {
if let Some(from) = hidden_buffer.cell(Position::new(x, y_off)) {
*to = from.clone();
}
}
}
}
}
ScrollAxis::Horizontal => {
let offset = match truncation {
Truncation::Top(value) => *value,
_ => 0,
};
for x in available_area.left()..available_area.right() {
let x_off = x + offset;
for y in available_area.top()..available_area.bottom() {
if let Some(to) = buf.cell_mut(Position::new(x, y)) {
if let Some(from) = hidden_buffer.cell(Position::new(x_off, y)) {
*to = from.clone();
}
}
}
}
}
};
}
#[derive(Debug, Clone, Default, PartialEq, PartialOrd, Eq, Ord)]
pub(crate) enum Truncation {
#[default]
None,
Top(u16),
Bot(u16),
}
impl Truncation {
pub(crate) fn value(&self) -> u16 {
match self {
Self::Top(value) | Self::Bot(value) => *value,
Self::None => 0,
}
}
}
#[cfg(test)]
mod test {
use crate::ListBuilder;
use ratatui::widgets::Block;
use super::*;
use ratatui::widgets::Borders;
struct TestItem {}
impl Widget for TestItem {
fn render(self, area: Rect, buf: &mut Buffer)
where
Self: Sized,
{
Block::default().borders(Borders::ALL).render(area, buf);
}
}
fn test_data(total_height: u16) -> (Rect, Buffer, ListView<'static, TestItem>, ListState) {
let area = Rect::new(0, 0, 5, total_height);
let list = ListView::new(ListBuilder::new(|_| (TestItem {}, 3)), 3);
(area, Buffer::empty(area), list, ListState::default())
}
#[test]
fn not_truncated() {
// given
let (area, mut buf, list, mut state) = test_data(9);
// when
list.render(area, &mut buf, &mut state);
// then
assert_buffer_eq(
buf,
Buffer::with_lines(vec![
"┌───┐",
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
]),
)
}
#[test]
fn empty_list() {
// given
let area = Rect::new(0, 0, 5, 2);
let mut buf = Buffer::empty(area);
let mut state = ListState::default();
let builder = ListBuilder::new(|_| (TestItem {}, 0));
let list = ListView::new(builder, 0);
// when
list.render(area, &mut buf, &mut state);
// then
assert_buffer_eq(buf, Buffer::with_lines(vec![" ", " "]))
}
#[test]
fn zero_size() {
// given
let (area, mut buf, list, mut state) = test_data(0);
// when
list.render(area, &mut buf, &mut state);
// then
assert_buffer_eq(buf, Buffer::empty(area))
}
#[test]
fn truncated_bot() {
// given
let (area, mut buf, list, mut state) = test_data(8);
// when
list.render(area, &mut buf, &mut state);
// then
assert_buffer_eq(
buf,
Buffer::with_lines(vec![
"┌───┐",
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
"┌───┐",
"│ │",
]),
)
}
#[test]
fn truncated_top() {
// given
let (area, mut buf, list, mut state) = test_data(8);
state.select(Some(2));
// when
list.render(area, &mut buf, &mut state);
// then
assert_buffer_eq(
buf,
Buffer::with_lines(vec![
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
]),
)
}
#[test]
fn scroll_up() {
let (area, mut buf, list, mut state) = test_data(8);
// Select last element and render
state.select(Some(2));
list.render(area, &mut buf, &mut state);
assert_buffer_eq(
buf,
Buffer::with_lines(vec![
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
]),
);
// Select first element and render
let (_, mut buf, list, _) = test_data(8);
state.select(Some(1));
list.render(area, &mut buf, &mut state);
assert_buffer_eq(
buf,
Buffer::with_lines(vec![
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
"┌───┐",
"│ │",
"└───┘",
]),
)
}
fn assert_buffer_eq(actual: Buffer, expected: Buffer) {
if actual.area != expected.area {
panic!(
"buffer areas not equal expected: {:?} actual: {:?}",
expected, actual
);
}
let diff = expected.diff(&actual);
if !diff.is_empty() {
panic!(
"buffer contents not equal\nexpected: {:?}\nactual: {:?}",
expected, actual,
);
}
assert_eq!(actual, expected, "buffers not equal");
}
}