src/util.rs
192 lines · 5616 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::{Span, Spans, 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 = Spans(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 { lines: vec![Spans(vec![join.clone()]); height] };
132
133 for (mut t, w) in texts.into_iter() {
134 for i in 0..height {
135 if let Some(spans) = t.lines.get_mut(i) {
136 text.lines[i].0.append(&mut spans.0);
137 } else {
138 text.lines[i].0.push(space_span(w, style));
139 }
140
141 text.lines[i].0.push(join.clone());
142 }
143 }
144
145 text
146}
147
148#[cfg(test)]
149pub mod tests {
150 use super::*;
151
152 #[test]
153 fn test_wrapped_lines_ascii() {
154 let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
155
156 let mut iter = wrap(s, 100);
157 assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12)));
158 assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26)));
159 assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7)));
160 assert_eq!(iter.next(), None);
161
162 let mut iter = wrap(s, 5);
163 assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
164 assert_eq!(iter.next(), Some((Cow::Borrowed(" worl"), 5)));
165 assert_eq!(iter.next(), Some((Cow::Borrowed("d!"), 2)));
166 assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
167 assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
168 assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));
169 assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5)));
170 assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5)));
171 assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1)));
172 assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5)));
173 assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2)));
174 assert_eq!(iter.next(), None);
175 }
176
177 #[test]
178 fn test_wrapped_lines_unicode() {
179 let s = "CHICKEN";
180
181 let mut iter = wrap(s, 14);
182 assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14)));
183 assert_eq!(iter.next(), None);
184
185 let mut iter = wrap(s, 5);
186 assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4)));
187 assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4)));
188 assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4)));
189 assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2)));
190 assert_eq!(iter.next(), None);
191 }
192}