Skip to main content

tui/widgets/grid/
tail.rs

1//! The end-of-text clip of cells whose tail matters more than their start.
2
3use std::borrow::Cow;
4
5use ratatui::layout::Rect;
6use tvui::ARROW_CELLS;
7use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
8
9use super::Item;
10
11impl Item<'_> {
12    /// The item shows the end of its text, not the start, while it is not focused and clipped.
13    #[must_use]
14    pub fn tail(mut self) -> Self {
15        self.tail = true;
16        self
17    }
18
19    /// The text to draw in `rect`: a clipped tail item keeps the end of its text after a `…`.
20    #[must_use]
21    pub fn shown(&self, rect: Rect) -> Cow<'_, str> {
22        let room = usize::from(self.area(rect).width.saturating_sub(ARROW_CELLS));
23        if !self.tail || self.focused || self.text.width() <= room {
24            return Cow::Borrowed(&self.text);
25        }
26        let mut used = 1;
27        let kept = self.text.char_indices().rev().take_while(|(_, ch)| {
28            used += ch.width().unwrap_or(0);
29            used <= room
30        });
31        let start = kept.last().map_or(self.text.len(), |(at, _)| at);
32        let tail = self.text[start..].trim_start_matches(|ch: char| ch.width() == Some(0));
33        Cow::Owned(format!("…{tail}"))
34    }
35}