aboutsummaryrefslogtreecommitdiff
path: root/helix-view/src/info.rs
blob: b5a002fa437abfcd0da094e778409394e97678da (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use crate::input::KeyEvent;
use helix_core::unicode::width::UnicodeWidthStr;
use std::{collections::BTreeSet, fmt::Write};

#[derive(Debug)]
/// Info box used in editor. Rendering logic will be in other crate.
pub struct Info {
    /// Title shown at top.
    pub title: String,
    /// Text body, should contain newlines.
    pub text: String,
    /// Body width.
    pub width: u16,
    /// Body height.
    pub height: u16,
}

impl Info {
    pub fn new(title: &str, body: Vec<(&str, BTreeSet<KeyEvent>)>) -> Info {
        let body = body
            .into_iter()
            .map(|(desc, events)| {
                let events = events.iter().map(ToString::to_string).collect::<Vec<_>>();
                (desc, events.join(", "))
            })
            .collect::<Vec<_>>();

        let keymaps_width = body.iter().map(|r| r.1.len()).max().unwrap();
        let mut text = String::new();

        for (desc, keyevents) in &body {
            let _ = writeln!(
                text,
                "{:width$}  {}",
                keyevents,
                desc,
                width = keymaps_width
            );
        }

        Info {
            title: title.to_string(),
            width: text.lines().map(|l| l.width()).max().unwrap() as u16,
            height: body.len() as u16,
            text,
        }
    }
}