crates/tui-core/src/border.rs 6.5 KiB raw
1
//! Shared border drawing primitives.
2
//!
3
//! `Border` owns both the glyph set and style used for box edges, corners, and
4
//! divider junctions. Widgets use it to draw consistent chrome while keeping
5
//! their child content and divider fill cells independently styled.
6
7
use crate::layout::Rect;
8
use crate::{Buffer, Color, Line, Paint, Style};
9
10
/// Border glyph set.
11
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12
pub struct BorderChars {
13
    /// Top-left corner.
14
    pub top_left: char,
15
    /// Top-right corner.
16
    pub top_right: char,
17
    /// Bottom-left corner.
18
    pub bottom_left: char,
19
    /// Bottom-right corner.
20
    pub bottom_right: char,
21
    /// Vertical edge.
22
    pub vertical: char,
23
    /// Horizontal edge.
24
    pub horizontal: char,
25
    /// Left divider junction.
26
    pub divider_left: char,
27
    /// Right divider junction.
28
    pub divider_right: char,
29
}
30
31
impl BorderChars {
32
    /// Rounded border glyphs.
33
    pub const ROUNDED: Self = Self {
34
        top_left: '╭',
35
        top_right: '╮',
36
        bottom_left: '╰',
37
        bottom_right: '╯',
38
        vertical: '│',
39
        horizontal: '─',
40
        divider_left: '├',
41
        divider_right: '┤',
42
    };
43
}
44
45
impl Default for BorderChars {
46
    fn default() -> Self {
47
        Self::ROUNDED
48
    }
49
}
50
51
/// A border style.
52
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53
pub struct Border {
54
    /// Border style.
55
    pub style: Style,
56
    /// Border characters.
57
    pub chars: BorderChars,
58
}
59
60
impl Border {
61
    /// Creates a rounded border from a foreground color.
62
    pub const fn new(color: Color) -> Self {
63
        Self::with_style(Style::new(color))
64
    }
65
66
    /// Creates a rounded border from a style.
67
    pub const fn with_style(style: Style) -> Self {
68
        Self {
69
            style,
70
            chars: BorderChars::ROUNDED,
71
        }
72
    }
73
74
    /// Returns a top border line with `cols` inner columns.
75
    pub fn top(self, cols: usize) -> Line {
76
        self.horizontal(
77
            self.chars.top_left,
78
            self.chars.horizontal,
79
            self.chars.top_right,
80
            cols,
81
        )
82
    }
83
84
    /// Returns a divider line with `cols` inner columns.
85
    pub fn divider(self, cols: usize, sigil: char) -> Line {
86
        Line::default()
87
            .item(self.paint(self.chars.divider_left))
88
            .item(self.paint(std::iter::repeat_n(sigil, cols).collect::<String>()))
89
            .item(self.paint(self.chars.divider_right))
90
    }
91
92
    /// Returns a bottom border line with `cols` inner columns.
93
    pub fn bottom(self, cols: usize) -> Line {
94
        self.horizontal(
95
            self.chars.bottom_left,
96
            self.chars.horizontal,
97
            self.chars.bottom_right,
98
            cols,
99
        )
100
    }
101
102
    /// Returns a left border segment with padding.
103
    pub fn left(self, padding: usize) -> Paint<String> {
104
        self.paint(format!("{}{}", self.chars.vertical, " ".repeat(padding)))
105
    }
106
107
    /// Returns a right border segment with padding.
108
    pub fn right(self, padding: usize) -> Paint<String> {
109
        self.paint(format!("{}{}", " ".repeat(padding), self.chars.vertical))
110
    }
111
112
    /// Draws the border into a buffer.
113
    pub fn draw(self, area: Rect, buf: &mut Buffer) {
114
        if area.is_empty() {
115
            return;
116
        }
117
        if area.cols == 1 && area.rows == 1 {
118
            self.set(buf, area.x, area.y, self.chars.top_left);
119
            return;
120
        }
121
        if area.rows == 1 {
122
            let right = area.right().saturating_sub(1);
123
            self.set(buf, area.x, area.y, self.chars.top_left);
124
            for x in area.x + 1..right {
125
                self.set(buf, x, area.y, self.chars.horizontal);
126
            }
127
            self.set(buf, right, area.y, self.chars.top_right);
128
            return;
129
        }
130
        if area.cols == 1 {
131
            let bottom = area.bottom().saturating_sub(1);
132
            self.set(buf, area.x, area.y, self.chars.top_left);
133
            for y in area.y + 1..bottom {
134
                self.set(buf, area.x, y, self.chars.vertical);
135
            }
136
            self.set(buf, area.x, bottom, self.chars.bottom_left);
137
            return;
138
        }
139
140
        let right = area.right().saturating_sub(1);
141
        let bottom = area.bottom().saturating_sub(1);
142
143
        self.set(buf, area.x, area.y, self.chars.top_left);
144
        self.set(buf, right, area.y, self.chars.top_right);
145
        self.set(buf, area.x, bottom, self.chars.bottom_left);
146
        self.set(buf, right, bottom, self.chars.bottom_right);
147
148
        for x in area.x + 1..right {
149
            self.set(buf, x, area.y, self.chars.horizontal);
150
            self.set(buf, x, bottom, self.chars.horizontal);
151
        }
152
        for y in area.y + 1..bottom {
153
            self.set(buf, area.x, y, self.chars.vertical);
154
            self.set(buf, right, y, self.chars.vertical);
155
        }
156
    }
157
158
    fn horizontal(self, left: char, fill: char, right: char, cols: usize) -> Line {
159
        Line::default()
160
            .item(self.paint(left))
161
            .item(self.paint(std::iter::repeat_n(fill, cols).collect::<String>()))
162
            .item(self.paint(right))
163
    }
164
165
    fn paint<T>(self, item: T) -> Paint<T> {
166
        Paint::new(item).with_style(self.style)
167
    }
168
169
    fn set(self, buf: &mut Buffer, x: usize, y: usize, glyph: char) {
170
        buf.set_char(x, y, glyph, self.style);
171
    }
172
}
173
174
#[cfg(test)]
175
mod tests {
176
    use super::*;
177
    use crate::Buffer;
178
179
    #[test]
180
    fn border_lines_use_shared_glyphs_and_style() {
181
        let border = Border::new(Color::Red);
182
        let line = border.top(3);
183
184
        assert_eq!(line.to_string(), "╭───╮");
185
        assert!(
186
            line.labels()
187
                .iter()
188
                .all(|label| { label.paint.style().fg_color() == Color::Red })
189
        );
190
        assert_eq!(border.divider(2, '┄').to_string(), "├┄┄┤");
191
        assert_eq!(border.bottom(1).to_string(), "╰─╯");
192
    }
193
194
    #[test]
195
    fn border_draws_degenerate_and_rectangular_buffers() {
196
        let border = Border::new(Color::Unset);
197
        let mut one = Buffer::empty(Rect::new(0, 0, 1, 1));
198
        let mut row = Buffer::empty(Rect::new(0, 0, 4, 1));
199
        let mut column = Buffer::empty(Rect::new(0, 0, 1, 3));
200
        let mut rect = Buffer::empty(Rect::new(0, 0, 4, 3));
201
202
        border.draw(one.area(), &mut one);
203
        border.draw(row.area(), &mut row);
204
        border.draw(column.area(), &mut column);
205
        border.draw(rect.area(), &mut rect);
206
207
        assert_eq!(one.lines(), vec!["╭"]);
208
        assert_eq!(row.lines(), vec!["╭──╮"]);
209
        assert_eq!(column.lines(), vec!["╭", "│", "╰"]);
210
        assert_eq!(rect.lines(), vec!["╭──╮", "│  │", "╰──╯"]);
211
    }
212
}