src/util.rs

214 lines · 6342 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::from(vec![Line::from(vec![join.clone()]); height]);
132
133    for (mut t, w) in texts.into_iter() {
134        for i in 0..height {
135            if let Some(line) = t.lines.get_mut(i) {
136                text.lines[i].spans.append(&mut line.spans);
137            } else {
138                text.lines[i].spans.push(space_span(w, style));
139            }
140
141            text.lines[i].spans.push(join.clone());
142        }
143    }
144
145    text
146}
147
148fn replace_emoji_in_grapheme(grapheme: &str) -> String {
149    emojis::get(grapheme)
150        .and_then(|emoji| emoji.shortcode())
151        .map(|shortcode| format!(":{shortcode}:"))
152        .unwrap_or_else(|| grapheme.to_owned())
153}
154
155pub fn replace_emojis_in_str(s: &str) -> String {
156    let graphemes = s.graphemes(true);
157    graphemes.map(replace_emoji_in_grapheme).collect()
158}
159
160pub fn replace_emojis_in_span(span: &mut Span) {
161    span.content = Cow::Owned(replace_emojis_in_str(span.content.as_ref()))
162}
163
164pub fn replace_emojis_in_line(line: &mut Line) {
165    for span in &mut line.spans {
166        replace_emojis_in_span(span);
167    }
168}
169
170#[cfg(test)]
171pub mod tests {
172    use super::*;
173
174    #[test]
175    fn test_wrapped_lines_ascii() {
176        let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
177
178        let mut iter = wrap(s, 100);
179        assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12)));
180        assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26)));
181        assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7)));
182        assert_eq!(iter.next(), None);
183
184        let mut iter = wrap(s, 5);
185        assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
186        assert_eq!(iter.next(), Some((Cow::Borrowed(" worl"), 5)));
187        assert_eq!(iter.next(), Some((Cow::Borrowed("d!"), 2)));
188        assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
189        assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
190        assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));
191        assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5)));
192        assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5)));
193        assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1)));
194        assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5)));
195        assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2)));
196        assert_eq!(iter.next(), None);
197    }
198
199    #[test]
200    fn test_wrapped_lines_unicode() {
201        let s = "CHICKEN";
202
203        let mut iter = wrap(s, 14);
204        assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14)));
205        assert_eq!(iter.next(), None);
206
207        let mut iter = wrap(s, 5);
208        assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4)));
209        assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4)));
210        assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4)));
211        assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2)));
212        assert_eq!(iter.next(), None);
213    }
214}