src/util.rs

194 lines · 5652 bytes

  1//! # Utility functions
  2use std::borrow::Cow;
  3
  4use unicode_segmentation::UnicodeSegmentation;
  5use unicode_width::UnicodeWidthStr;
  6
  7use modalkit::tui::style::Style;
  8use modalkit::tui::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 idx = 0;
 30    let mut w = 0;
 31
 32    for (i, g) in UnicodeSegmentation::grapheme_indices(s.as_ref(), true) {
 33        let gw = UnicodeWidthStr::width(g);
 34        idx = i;
 35
 36        if w + gw > width {
 37            break;
 38        }
 39
 40        w += gw;
 41    }
 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
150#[cfg(test)]
151pub mod tests {
152    use super::*;
153
154    #[test]
155    fn test_wrapped_lines_ascii() {
156        let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
157
158        let mut iter = wrap(s, 100);
159        assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12)));
160        assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26)));
161        assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7)));
162        assert_eq!(iter.next(), None);
163
164        let mut iter = wrap(s, 5);
165        assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
166        assert_eq!(iter.next(), Some((Cow::Borrowed(" worl"), 5)));
167        assert_eq!(iter.next(), Some((Cow::Borrowed("d!"), 2)));
168        assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
169        assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
170        assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));
171        assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5)));
172        assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5)));
173        assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1)));
174        assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5)));
175        assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2)));
176        assert_eq!(iter.next(), None);
177    }
178
179    #[test]
180    fn test_wrapped_lines_unicode() {
181        let s = "CHICKEN";
182
183        let mut iter = wrap(s, 14);
184        assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14)));
185        assert_eq!(iter.next(), None);
186
187        let mut iter = wrap(s, 5);
188        assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4)));
189        assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4)));
190        assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4)));
191        assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2)));
192        assert_eq!(iter.next(), None);
193    }
194}