src/util.rs

191 lines · 5592 bytes

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