Skip to main content

promkit_widgets/text/
text.rs

1use promkit_core::grapheme::StyledGraphemes;
2
3use crate::cursor::Cursor;
4
5#[derive(Clone)]
6pub struct Text(Cursor<Vec<StyledGraphemes>>);
7
8impl Default for Text {
9    fn default() -> Self {
10        Self(Cursor::new(vec![], 0, false))
11    }
12}
13
14impl<T: AsRef<str>> From<T> for Text {
15    fn from(text: T) -> Self {
16        let lines: Vec<StyledGraphemes> = text
17            .as_ref()
18            .split('\n')
19            // Replace empty lines with null character to
20            // prevent them from being ignored at `style::Print`
21            .map(|line| if line.is_empty() { "\0" } else { line })
22            .map(StyledGraphemes::from)
23            .collect();
24        Self(Cursor::new(lines, 0, false))
25    }
26}
27
28impl Text {
29    /// Creates a new `Text` from styled graphemes without parsing a string.
30    /// Useful when the caller already has styled content prepared.
31    pub fn from_styled_graphemes(lines: Vec<StyledGraphemes>) -> Self {
32        Self(Cursor::new(lines, 0, false))
33    }
34
35    /// Replaces the contents with new contents and adjusts the position if necessary.
36    pub fn replace_contents(&mut self, text: Vec<StyledGraphemes>) {
37        self.0.replace_contents(text);
38    }
39
40    /// Returns a reference to the vector of items in the listbox.
41    pub fn items(&self) -> &Vec<StyledGraphemes> {
42        self.0.contents()
43    }
44
45    /// Returns the current position of the cursor within the listbox.
46    pub fn position(&self) -> usize {
47        self.0.position()
48    }
49
50    /// Moves the cursor backward in the listbox, if possible.
51    /// Returns `true` if the cursor was successfully moved backward, `false` otherwise.
52    pub fn backward(&mut self) -> bool {
53        self.0.backward()
54    }
55
56    /// Moves the cursor forward in the listbox, if possible.
57    /// Returns `true` if the cursor was successfully moved forward, `false` otherwise.
58    pub fn forward(&mut self) -> bool {
59        self.0.forward()
60    }
61}