1
//! The end-of-text clip of cells whose tail matters more than their start.
2

            
3
use std::borrow::Cow;
4

            
5
use ratatui::layout::Rect;
6
use tvui::ARROW_CELLS;
7
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
8

            
9
use super::Item;
10

            
11
impl Item<'_> {
12
    /// The item shows the end of its text, not the start, while it is not focused and clipped.
13
    #[must_use]
14
802
    pub fn tail(mut self) -> Self {
15
802
        self.tail = true;
16
802
        self
17
802
    }
18

            
19
    /// The text to draw in `rect`: a clipped tail item keeps the end of its text after a `…`.
20
    #[must_use]
21
1823
    pub fn shown(&self, rect: Rect) -> Cow<'_, str> {
22
1823
        let room = usize::from(self.area(rect).width.saturating_sub(ARROW_CELLS));
23
1823
        if !self.tail || self.focused || self.text.width() <= room {
24
1699
            return Cow::Borrowed(&self.text);
25
124
        }
26
124
        let mut used = 1;
27
1456
        let kept = self.text.char_indices().rev().take_while(|(_, ch)| {
28
1456
            used += ch.width().unwrap_or(0);
29
1456
            used <= room
30
1456
        });
31
124
        let start = kept.last().map_or(self.text.len(), |(at, _)| at);
32
124
        let tail = self.text[start..].trim_start_matches(|ch: char| ch.width() == Some(0));
33
124
        Cow::Owned(format!("…{tail}"))
34
1823
    }
35
}