src/util.rs

216 lines · 6359 bytes

  1//! # Utility functions
  2use std::borrow::Cow;
  3
  4use unicode_segmentation::UnicodeSegmentation;
  5use unicode_width::UnicodeWidthStr;
  6
  7use ratatui::style::Style;
  8use ratatui::text::{Line, Span, Text};
  9
 10pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) {
 11    match cow {
 12        Cow::Borrowed(s) => {
 13            let s1 = Cow::Borrowed(&s[idx..]);
 14            let s0 = Cow::Borrowed(&s[..idx]);
 15
 16            (s0, s1)
 17        },
 18        Cow::Owned(mut s) => {
 19            let s1 = Cow::Owned(s.split_off(idx));
 20            let s0 = Cow::Owned(s);
 21
 22            (s0, s1)
 23        },
 24    }
 25}
 26
 27pub fn take_width(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) {
 28    // Find where to split the line.
 29    let mut w = 0;
 30
 31    let idx = UnicodeSegmentation::grapheme_indices(s.as_ref(), true)
 32        .find_map(|(i, g)| {
 33            let gw = UnicodeWidthStr::width(g);
 34            if w + gw > width {
 35                Some(i)
 36            } else {
 37                w += gw;
 38                None
 39            }
 40        })
 41        .unwrap_or(s.len());
 42
 43    let (s0, s1) = split_cow(s, idx);
 44
 45    ((s0, w), s1)
 46}
 47
 48pub struct WrappedLinesIterator<'a> {
 49    iter: std::vec::IntoIter<Cow<'a, str>>,
 50    curr: Option<Cow<'a, str>>,
 51    width: usize,
 52}
 53
 54impl<'a> WrappedLinesIterator<'a> {
 55    fn new<T>(input: T, width: usize) -> Self
 56    where
 57        T: Into<Cow<'a, str>>,
 58    {
 59        let width = width.max(2);
 60
 61        let cows: Vec<Cow<'a, str>> = match input.into() {
 62            Cow::Borrowed(s) => s.lines().map(Cow::Borrowed).collect(),
 63            Cow::Owned(s) => s.lines().map(ToOwned::to_owned).map(Cow::Owned).collect(),
 64        };
 65
 66        WrappedLinesIterator { iter: cows.into_iter(), curr: None, width }
 67    }
 68}
 69
 70impl<'a> Iterator for WrappedLinesIterator<'a> {
 71    type Item = (Cow<'a, str>, usize);
 72
 73    fn next(&mut self) -> Option<Self::Item> {
 74        if self.curr.is_none() {
 75            self.curr = self.iter.next();
 76        }
 77
 78        if let Some(s) = self.curr.take() {
 79            let width = UnicodeWidthStr::width(s.as_ref());
 80
 81            if width <= self.width {
 82                return Some((s, width));
 83            } else {
 84                let (prefix, s1) = take_width(s, self.width);
 85                self.curr = Some(s1);
 86                return Some(prefix);
 87            }
 88        } else {
 89            return None;
 90        }
 91    }
 92}
 93
 94pub fn wrap<'a, T>(input: T, width: usize) -> WrappedLinesIterator<'a>
 95where
 96    T: Into<Cow<'a, str>>,
 97{
 98    WrappedLinesIterator::new(input, width)
 99}
100
101pub fn wrapped_text<'a, T>(s: T, width: usize, style: Style) -> Text<'a>
102where
103    T: Into<Cow<'a, str>>,
104{
105    let mut text = Text::default();
106
107    for (line, w) in wrap(s, width) {
108        let space = space_span(width.saturating_sub(w), style);
109        let spans = Line::from(vec![Span::styled(line, style), space]);
110
111        text.lines.push(spans);
112    }
113
114    return text;
115}
116
117pub fn space(width: usize) -> String {
118    " ".repeat(width)
119}
120
121pub fn space_span(width: usize, style: Style) -> Span<'static> {
122    Span::styled(space(width), style)
123}
124
125pub fn space_text(width: usize, style: Style) -> Text<'static> {
126    space_span(width, style).into()
127}
128
129pub fn join_cell_text<'a>(texts: Vec<(Text<'a>, usize)>, join: Span<'a>, style: Style) -> Text<'a> {
130    let height = texts.iter().map(|t| t.0.height()).max().unwrap_or(0);
131    let mut text = Text {
132        lines: vec![Line::from(vec![join.clone()]); height],
133    };
134
135    for (mut t, w) in texts.into_iter() {
136        for i in 0..height {
137            if let Some(line) = t.lines.get_mut(i) {
138                text.lines[i].spans.append(&mut line.spans);
139            } else {
140                text.lines[i].spans.push(space_span(w, style));
141            }
142
143            text.lines[i].spans.push(join.clone());
144        }
145    }
146
147    text
148}
149
150fn replace_emoji_in_grapheme(grapheme: &str) -> String {
151    emojis::get(grapheme)
152        .and_then(|emoji| emoji.shortcode())
153        .map(|shortcode| format!(":{shortcode}:"))
154        .unwrap_or_else(|| grapheme.to_owned())
155}
156
157pub fn replace_emojis_in_str(s: &str) -> String {
158    let graphemes = s.graphemes(true);
159    graphemes.map(replace_emoji_in_grapheme).collect()
160}
161
162pub fn replace_emojis_in_span(span: &mut Span) {
163    span.content = Cow::Owned(replace_emojis_in_str(span.content.as_ref()))
164}
165
166pub fn replace_emojis_in_line(line: &mut Line) {
167    for span in &mut line.spans {
168        replace_emojis_in_span(span);
169    }
170}
171
172#[cfg(test)]
173pub mod tests {
174    use super::*;
175
176    #[test]
177    fn test_wrapped_lines_ascii() {
178        let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
179
180        let mut iter = wrap(s, 100);
181        assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12)));
182        assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26)));
183        assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7)));
184        assert_eq!(iter.next(), None);
185
186        let mut iter = wrap(s, 5);
187        assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
188        assert_eq!(iter.next(), Some((Cow::Borrowed(" worl"), 5)));
189        assert_eq!(iter.next(), Some((Cow::Borrowed("d!"), 2)));
190        assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
191        assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
192        assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));
193        assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5)));
194        assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5)));
195        assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1)));
196        assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5)));
197        assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2)));
198        assert_eq!(iter.next(), None);
199    }
200
201    #[test]
202    fn test_wrapped_lines_unicode() {
203        let s = "CHICKEN";
204
205        let mut iter = wrap(s, 14);
206        assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14)));
207        assert_eq!(iter.next(), None);
208
209        let mut iter = wrap(s, 5);
210        assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4)));
211        assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4)));
212        assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4)));
213        assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2)));
214        assert_eq!(iter.next(), None);
215    }
216}