summaryrefslogtreecommitdiff
path: root/helix-view/src/info.rs
blob: eef8d3a1031a80536defd43debb4fb32730de374 (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
49
50
51
use crate::input::KeyEvent;
use std::fmt::Write;
use unicode_width::UnicodeWidthStr;

#[derive(Debug)]
/// Info box used in editor. Rendering logic will be in other crate.
pub struct Info {
    /// Title kept as static str for now.
    pub title: &'static str,
    /// Text body, should contains newline.
    pub text: String,
    /// Body width.
    pub width: u16,
    /// Body height.
    pub height: u16,
}

impl Info {
    pub fn key(title: &'static str, body: Vec<(Vec<KeyEvent>, &'static str)>) -> Info {
        let keymaps_width: u16 = body
            .iter()
            .map(|r| r.0.iter().map(|e| e.width() as u16 + 2).sum::<u16>() - 2)
            .max()
            .unwrap();
        let mut text = String::new();
        let mut width = 0;
        let height = body.len() as u16;
        for (mut keyevents, desc) in body {
            let keyevent = keyevents.remove(0);
            let mut left = keymaps_width - keyevent.width() as u16;
            write!(text, "{}", keyevent).ok();
            for keyevent in keyevents {
                write!(text, ", {}", keyevent).ok();
                left -= 2 + keyevent.width() as u16;
            }
            for _ in 0..left {
                text.push(' ');
            }
            if keymaps_width + 2 + (desc.width() as u16) > width {
                width = keymaps_width + 2 + desc.width() as u16;
            }
            writeln!(text, "  {}", &desc).ok();
        }
        Info {
            title,
            text,
            width,
            height,
        }
    }
}