src/util.rs

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